【问题标题】:You tried to call count_params on ..., but the layer isn't built. TensorFlow 2.0您尝试在 ... 上调用 count_params,但未构建图层。 TensorFlow 2.0
【发布时间】:2019-10-01 09:38:47
【问题描述】:

我在 Pyhotn 3 和 TF 2.0 中收到以下错误。

“ValueError:您尝试在数字上调用 count_params,但未构建图层。您可以通过以下方式手动构建它:digits.build(batch_input_shape)。”在 new_model.summary() 行。

问题是什么以及如何解决?

inputs = keras.Input(shape=(784,), name='digits')
x = layers.Dense(64, activation='relu', name='dense_1')(inputs)
x = layers.Dense(64, activation='relu', name='dense_2')(x)
outputs = layers.Dense(10, activation='softmax', name='predictions')(x)

model = keras.Model(inputs=inputs, outputs=outputs, name='3_layer_mlp')
model.summary()

(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='sparse_categorical_crossentropy',
              optimizer=keras.optimizers.RMSprop(),
              metrics=['accuracy'])
history = model.fit(x_train, y_train,
                    batch_size=64,
                    epochs=2)

model.save('saved_model', save_format='tf')
new_model = keras.models.load_model('saved_model')
new_model.summary()

【问题讨论】:

  • 我从文件夹加载模型时出现此错误,它在未从磁盘加载的模型上正常工作。

标签: tensorflow2.0


【解决方案1】:

2.0版本模型可以保存为.h5格式,保存时请使用model.save('my_model.h5')。

请找到工作gist的链接。

在最新的 TF-nightly 版本中似乎也解决了这个问题,因为未来 2.1 将是正式版尝试使用pip install tf-nightly

找到工作要点here的链接。

【讨论】:

    【解决方案2】:

    我遇到了同样的错误,升级tf2.0到tf2.1后解决了。

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,我使用的是tensorflow==2.0.0。我尝试使用 tensorflows nightly build 运行相同的代码(在我的情况下为 pip install tf-nightly==2.1.0.dev20191003)。

      它适用于夜间构建,但您可能必须使用夜间构建再次保存模型。

      【讨论】:

        【解决方案4】:

        如果没有最后一行代码就可以正常使用模型,也就是说这里不能使用summary。

        【讨论】:

        • 我的代码的最后一行 (new_model.summary()) 有什么替代方法吗?我想使用这个新模型打印摘要。
        猜你喜欢
        • 1970-01-01
        • 2019-12-07
        • 1970-01-01
        • 2019-10-03
        • 2020-04-08
        • 1970-01-01
        • 2015-06-10
        • 2019-09-05
        • 1970-01-01
        相关资源
        最近更新 更多