I am interested to see the output of intermediate layer, how do I do it?
I have to do it by following way:
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras import layers, models
from tensorflow.keras.callbacks import Callback
# Custom Callback to extract Dense layer values
class DenseLayerOutputCallback(Callback):
def __init__(self, model, layer_name):
super(DenseLayerOutputCallback, self).__init__()
self.model = model
self.layer_name = layer_name
self.outputs = []
def on_epoch_end(self, epoch, logs=None):
intermediate_layer_model = models.Model(inputs=self.model.input, outputs=self.model.get_layer(self.layer_name).output)
intermediate_outputs = intermediate_layer_model.predict(train_images)
self.outputs.append(intermediate_outputs)
# Load the MNIST dataset
mnist = tf.keras.datasets.mnist
(train_images, train_labels), _ = mnist.load_data()
# Normalize the pixel values to the range [0, 1]
train_images = train_images / 255.0
# Define the input shape
input_shape = train_images[0].shape
# Define the model using the Functional API
input_layer = layers.Input(shape=input_shape)
x = layers.Flatten()(input_layer)
x = layers.Dense(128, activation='relu')(x)
x = layers.Dropout(0.2)(x)
output_layer = layers.Dense(10, activation='softmax')(x)
model = tf.keras.Model(inputs=input_layer, outputs=output_layer)
# Compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Create the custom callback to extract Dense layer values
#dense_layer_name = 'dense' # Name of the Dense layer in the model
dense_layer_name = 'dense_6' # Name of the Dense layer in the model
dense_output_callback = DenseLayerOutputCallback(model, layer_name=dense_layer_name)
# Train the model with the custom callback
history = model.fit(train_images, train_labels, epochs=5, batch_size=32, validation_split=0.1, callbacks=[dense_output_callback])
but I tried using
# Define the model using the Functional API
input_layer = layers.Input(shape=input_shape)
x = layers.Flatten()(input_layer)
tf.Print(x)
x = layers.Dense(128, activation='relu')(x)
x = layers.Dropout(0.2)(x)
output_layer = layers.Dense(10, activation='softmax')(x)
That doesn’t worked out. I would appreciate reply.
I am using
tf.__version__ --> 2.12.0