尝试在 TensorFlow 顺序模型中提取层激活时出现关键错误

问题描述 投票:0回答:1

我有一个在 MNIST 数据集上训练的序列模型。 训练后,我尝试创建一个新模型来从隐藏的 ReLU(密集)层输出激活。 我正确地重塑了测试图像,但在激活模型上调用 Predict() 函数时出现错误。

这是我用来提取激活的代码:

import tensorflow as tf
from tensorflow.keras import models, layers

# Load and preprocess the MNIST dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# Define and compile the model
model = models.Sequential([
    layers.Flatten(input_shape=(28, 28)),
    layers.Dense(128, activation='relu'),
    layers.Dense(10)
])
model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)

# Define the activation model
layer_name = 'dense'
activation_model = models.Model(inputs=model.input, outputs=model.get_layer(layer_name).output)

但是我收到以下错误。

ValueError                                Traceback (most recent call last)
<ipython-input-16-cbfe6f9d08f9> in <cell line: 19>()
     17 # Define the activation model
     18 layer_name = 'dense'
---> 19 activation_model = models.Model(inputs=model.input, outputs=model.get_layer(layer_name).output)
     20 
     21 # Prepare the test image

1 frames
/usr/local/lib/python3.10/dist-packages/keras/src/ops/operation.py in _get_node_attribute_at_index(self, node_index, attr, attr_name)
    283         """
    284         if not self._inbound_nodes:
--> 285             raise ValueError(
    286                 f"The layer {self.name} has never been called "
    287                 f"and thus has no defined {attr_name}."

ValueError: The layer sequential_14 has never been called and thus has no defined input.

我有:

  • 已验证 TensorFlow 是否已正确安装。
  • 检查模型图层和输入形状。
  • 调整了测试图像的输入形状以添加批量大小和通道。
tensorflow keras deep-learning neural-network
1个回答
0
投票

您已创建顺序模型并尝试使用功能模型 API 访问顺序模型的输入属性,这导致了错误。为了避免此错误,您可以创建功能模型并定义层名称,然后训练模型。要访问模型的输入,您需要使用

model.input
,它仅适用于功能 API 模型,不适用于顺序模型。

我附上gist文件供您参考。

欲了解更多详情,请参阅

© www.soinside.com 2019 - 2024. All rights reserved.