我有一个在 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.
我有: