此模型尚未在 model.summary() 上构建错误
This model has not yet been built error on model.summary()
我的keras模型定义如下
class ConvLayer(Layer) :
def __init__(self, nf, ks=3, s=2, **kwargs):
self.nf = nf
self.grelu = GeneralReLU(leak=0.01)
self.conv = (Conv2D(filters = nf,
kernel_size = ks,
strides = s,
padding = "same",
use_bias = False,
activation = "linear"))
super(ConvLayer, self).__init__(**kwargs)
def rsub(self): return -self.grelu.sub
def set_sub(self, v): self.grelu.sub = -v
def conv_weights(self): return self.conv.weight[0]
def build(self, input_shape):
# No weight to train.
super(ConvLayer, self).build(input_shape) # Be sure to call this at the end
def compute_output_shape(self, input_shape):
output_shape = (input_shape[0],
input_shape[1]/2,
input_shape[2]/2,
self.nf)
return output_shape
def call(self, x):
return self.grelu(self.conv(x))
def __repr__(self):
return f'ConvLayer(nf={self.nf}, activation={self.grelu})'
class ConvModel(tf.keras.Model):
def __init__(self, nfs, input_shape, output_shape, use_bn=False, use_dp=False):
super(ConvModel, self).__init__(name='mlp')
self.use_bn = use_bn
self.use_dp = use_dp
self.num_classes = num_classes
# backbone layers
self.convs = [ConvLayer(nfs[0], s=1, input_shape=input_shape)]
self.convs += [ConvLayer(nf) for nf in nfs[1:]]
# classification layers
self.convs.append(AveragePooling2D())
self.convs.append(Dense(output_shape, activation='softmax'))
def call(self, inputs):
for layer in self.convs: inputs = layer(inputs)
return inputs
我可以毫无问题地编译这个模型
>>> model.compile(optimizer=tf.keras.optimizers.Adam(lr=lr),
loss='categorical_crossentropy',
metrics=['accuracy'])
但是当我查询这个模型的摘要时,我看到了这个错误
>>> model = ConvModel(nfs, input_shape=(32, 32, 3), output_shape=num_classes)
>>> model.summary()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-220-5f15418b3570> in <module>()
----> 1 model.summary()
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/network.py in summary(self, line_length, positions, print_fn)
1575 """
1576 if not self.built:
-> 1577 raise ValueError('This model has not yet been built. '
1578 'Build the model first by calling `build()` or calling '
1579 '`fit()` with some data, or specify '
ValueError: This model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.
我正在为模型的第一层提供 input_shape
,为什么会抛出此错误?
错误说明要做什么:
This model has not yet been built. Build the model first by calling build()
model.build(input_shape) # `input_shape` is the shape of the input data
# e.g. input_shape = (None, 32, 32, 3)
model.summary()
另一种方法是像这样添加属性input_shape()
:
model = Sequential()
model.add(Bidirectional(LSTM(n_hidden,return_sequences=False, dropout=0.25,
recurrent_dropout=0.1),input_shape=(n_steps,dim_input)))
# X is a train dataset with features excluding a target variable
input_shape = X.shape
model.build(input_shape)
model.summary()
keras 子类模型与其他 keras 模型(顺序模型和函数模型)有很大区别。
顺序模型和功能模型是表示层的 DAG 的数据结构。简而言之,功能模型或顺序模型是通过像乐高积木一样将一个层堆叠在一起构建的静态层图。因此,当您向第一层提供 input_shape 时,这些(功能和顺序)模型可以推断所有其他层的形状并构建模型。然后你可以打印 input/output 使用 model.summary() 的形状。
另一方面,子类模型是通过 Python 代码的主体(调用方法)定义的。对于子类模型,这里没有层图。我们不知道层是如何相互连接的(因为这是在调用主体中定义的,而不是作为显式数据结构),所以我们无法推断输入/输出形状。因此,对于子类模型,input/output 形状在首次使用适当数据进行测试之前对我们来说是未知的。在 compile() 方法中,我们将进行延迟编译并等待合适的数据。为了让它推断中间层的形状,我们需要 运行 使用适当的数据,然后使用 model.summary()。如果不使用数据 运行ning 模型,它会像您注意到的那样抛出错误。请检查 GitHub gist 以获取完整代码。
以下是Tensorflow网站的例子。
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
class ThreeLayerMLP(keras.Model):
def __init__(self, name=None):
super(ThreeLayerMLP, self).__init__(name=name)
self.dense_1 = layers.Dense(64, activation='relu', name='dense_1')
self.dense_2 = layers.Dense(64, activation='relu', name='dense_2')
self.pred_layer = layers.Dense(10, name='predictions')
def call(self, inputs):
x = self.dense_1(inputs)
x = self.dense_2(x)
return self.pred_layer(x)
def get_model():
return ThreeLayerMLP(name='3_layer_mlp')
model = get_model()
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype('float32') / 255
x_test = x_test.reshape(10000, 784).astype('float32') / 255
model.compile(loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=keras.optimizers.RMSprop())
model.summary() # This will throw an error as follows
# ValueError: This model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.
# Need to run with real data to infer shape of different layers
history = model.fit(x_train, y_train,
batch_size=64,
epochs=1)
model.summary()
谢谢!
确保正确创建模型。像下面代码这样的小错别字也可能导致问题:
model = Model(some-input, some-output, "model-name")
而正确的代码应该是:
model = Model(some-input, some-output, name="model-name")
如果您的 Tensorflow、Keras 版本是 2.5.0
则在导入 Keras 包时只需添加 Tensorflow
不是这个:
from tensorflow import keras
from keras.models import Sequential
import tensorflow as tf
像这样:
from tensorflow import keras
from tensorflow.keras.models import Sequential
import tensorflow as tf
最近更改的版本接受
来自 tensorflow.python.keras.models 导入模型
我也遇到了同样的错误,所以我删除了 model.summary()
。然后问题就解决了。如果在构建模型之前定义了摘要模型,则会出现这种情况。
这是 LINK 的说明,其中说明
Raises:
ValueError: if `summary()` is called before the model is built.**
我的keras模型定义如下
class ConvLayer(Layer) :
def __init__(self, nf, ks=3, s=2, **kwargs):
self.nf = nf
self.grelu = GeneralReLU(leak=0.01)
self.conv = (Conv2D(filters = nf,
kernel_size = ks,
strides = s,
padding = "same",
use_bias = False,
activation = "linear"))
super(ConvLayer, self).__init__(**kwargs)
def rsub(self): return -self.grelu.sub
def set_sub(self, v): self.grelu.sub = -v
def conv_weights(self): return self.conv.weight[0]
def build(self, input_shape):
# No weight to train.
super(ConvLayer, self).build(input_shape) # Be sure to call this at the end
def compute_output_shape(self, input_shape):
output_shape = (input_shape[0],
input_shape[1]/2,
input_shape[2]/2,
self.nf)
return output_shape
def call(self, x):
return self.grelu(self.conv(x))
def __repr__(self):
return f'ConvLayer(nf={self.nf}, activation={self.grelu})'
class ConvModel(tf.keras.Model):
def __init__(self, nfs, input_shape, output_shape, use_bn=False, use_dp=False):
super(ConvModel, self).__init__(name='mlp')
self.use_bn = use_bn
self.use_dp = use_dp
self.num_classes = num_classes
# backbone layers
self.convs = [ConvLayer(nfs[0], s=1, input_shape=input_shape)]
self.convs += [ConvLayer(nf) for nf in nfs[1:]]
# classification layers
self.convs.append(AveragePooling2D())
self.convs.append(Dense(output_shape, activation='softmax'))
def call(self, inputs):
for layer in self.convs: inputs = layer(inputs)
return inputs
我可以毫无问题地编译这个模型
>>> model.compile(optimizer=tf.keras.optimizers.Adam(lr=lr),
loss='categorical_crossentropy',
metrics=['accuracy'])
但是当我查询这个模型的摘要时,我看到了这个错误
>>> model = ConvModel(nfs, input_shape=(32, 32, 3), output_shape=num_classes)
>>> model.summary()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-220-5f15418b3570> in <module>()
----> 1 model.summary()
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/network.py in summary(self, line_length, positions, print_fn)
1575 """
1576 if not self.built:
-> 1577 raise ValueError('This model has not yet been built. '
1578 'Build the model first by calling `build()` or calling '
1579 '`fit()` with some data, or specify '
ValueError: This model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.
我正在为模型的第一层提供 input_shape
,为什么会抛出此错误?
错误说明要做什么:
This model has not yet been built. Build the model first by calling
build()
model.build(input_shape) # `input_shape` is the shape of the input data
# e.g. input_shape = (None, 32, 32, 3)
model.summary()
另一种方法是像这样添加属性input_shape()
:
model = Sequential()
model.add(Bidirectional(LSTM(n_hidden,return_sequences=False, dropout=0.25,
recurrent_dropout=0.1),input_shape=(n_steps,dim_input)))
# X is a train dataset with features excluding a target variable
input_shape = X.shape
model.build(input_shape)
model.summary()
keras 子类模型与其他 keras 模型(顺序模型和函数模型)有很大区别。
顺序模型和功能模型是表示层的 DAG 的数据结构。简而言之,功能模型或顺序模型是通过像乐高积木一样将一个层堆叠在一起构建的静态层图。因此,当您向第一层提供 input_shape 时,这些(功能和顺序)模型可以推断所有其他层的形状并构建模型。然后你可以打印 input/output 使用 model.summary() 的形状。
另一方面,子类模型是通过 Python 代码的主体(调用方法)定义的。对于子类模型,这里没有层图。我们不知道层是如何相互连接的(因为这是在调用主体中定义的,而不是作为显式数据结构),所以我们无法推断输入/输出形状。因此,对于子类模型,input/output 形状在首次使用适当数据进行测试之前对我们来说是未知的。在 compile() 方法中,我们将进行延迟编译并等待合适的数据。为了让它推断中间层的形状,我们需要 运行 使用适当的数据,然后使用 model.summary()。如果不使用数据 运行ning 模型,它会像您注意到的那样抛出错误。请检查 GitHub gist 以获取完整代码。
以下是Tensorflow网站的例子。
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
class ThreeLayerMLP(keras.Model):
def __init__(self, name=None):
super(ThreeLayerMLP, self).__init__(name=name)
self.dense_1 = layers.Dense(64, activation='relu', name='dense_1')
self.dense_2 = layers.Dense(64, activation='relu', name='dense_2')
self.pred_layer = layers.Dense(10, name='predictions')
def call(self, inputs):
x = self.dense_1(inputs)
x = self.dense_2(x)
return self.pred_layer(x)
def get_model():
return ThreeLayerMLP(name='3_layer_mlp')
model = get_model()
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype('float32') / 255
x_test = x_test.reshape(10000, 784).astype('float32') / 255
model.compile(loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=keras.optimizers.RMSprop())
model.summary() # This will throw an error as follows
# ValueError: This model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.
# Need to run with real data to infer shape of different layers
history = model.fit(x_train, y_train,
batch_size=64,
epochs=1)
model.summary()
谢谢!
确保正确创建模型。像下面代码这样的小错别字也可能导致问题:
model = Model(some-input, some-output, "model-name")
而正确的代码应该是:
model = Model(some-input, some-output, name="model-name")
如果您的 Tensorflow、Keras 版本是 2.5.0
则在导入 Keras 包时只需添加 Tensorflow
不是这个:
from tensorflow import keras
from keras.models import Sequential
import tensorflow as tf
像这样:
from tensorflow import keras
from tensorflow.keras.models import Sequential
import tensorflow as tf
最近更改的版本接受 来自 tensorflow.python.keras.models 导入模型
我也遇到了同样的错误,所以我删除了 model.summary()
。然后问题就解决了。如果在构建模型之前定义了摘要模型,则会出现这种情况。
这是 LINK 的说明,其中说明
Raises:
ValueError: if `summary()` is called before the model is built.**