尚未在model.summary()上建立此模型错误

时间:2019-04-29 17:25:45

标签: python tensorflow keras tensorflow2.0

我将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,为什么会引发此错误?

6 个答案:

答案 0 :(得分:5)

keras子类化模型与其他keras模型(顺序模型和功能模型)之间存在很大差异。

顺序模型和功能模型是表示层DAG的数据结构。简而言之,功能模型或顺序模型是通过像乐高积木一样彼此堆叠而构建的静态层图。因此,当您向第一层提供input_shape时,这些(功能和顺序)模型可以推断所有其他层的形状并构建模型。然后,您可以使用model.summary()打印输入/输出形状。

另一方面,子类化模型是通过Python代码的主体(调用方法)定义的。对于子类模型,此处没有层图。我们不知道各层如何相互连接(因为这是在调用主体中定义的,而不是作为显式数据结构定义的),因此我们无法推断输入/输出形状。因此,对于子类模型,输入/输出形状对我们来说是未知的,直到首先使用适当的数据对其进行测试。在compile()方法中,我们将进行延迟编译并等待适当的数据。为了推断中间层的形状,我们需要使用适当的数据运行,然后使用model.summary()。如果不使用数据运行模型,则会如您所注意到的那样引发错误。请检查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()

谢谢!

答案 1 :(得分:2)

错误说明了怎么办:

  

此模型尚未构建。首先通过调用build()

来构建模型
model.build(input_shape) # `input_shape` is the shape of the input data
                         # e.g. input_shape = (None, 32, 32, 3)
model.summary()

答案 2 :(得分:1)

如果你的 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

答案 3 :(得分:0)

另一种方法是像这样添加属性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)))

答案 4 :(得分:0)

$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) { ........

答案 5 :(得分:0)

确保正确创建模型。像以下代码这样的小错字错误也可能导致问题:

model = Model(some-input, some-output, "model-name")

正确的代码应为:

model = Model(some-input, some-output, name="model-name")