0
0
TensorFlowml~15 mins

Model summary and visualization in TensorFlow - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Model summary and visualization
Problem:You have built a simple neural network model for classifying handwritten digits using the MNIST dataset. You want to understand the model's structure and visualize it to better explain it to others.
Current Metrics:Training accuracy: 95%, Validation accuracy: 94%
Issue:You do not have a clear summary or visual diagram of the model architecture to easily communicate how the model works.
Your Task
Generate a clear model summary and create a visualization image of the model architecture.
Use TensorFlow and Keras only.
Do not change the model architecture or training parameters.
Save the visualization as a PNG file.
Hint 1
Hint 2
Hint 3
Solution
TensorFlow
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.utils import plot_model

# Load MNIST dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

# Normalize data
x_train = x_train / 255.0
x_test = x_test / 255.0

# Build a simple model
model = models.Sequential([
    layers.Flatten(input_shape=(28, 28)),
    layers.Dense(128, activation='relu'),
    layers.Dense(10, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Print model summary
model.summary()

# Visualize and save the model architecture
plot_model(model, to_file='model_architecture.png', show_shapes=True, show_layer_names=True)
Added model.summary() to print the model architecture details.
Used tensorflow.keras.utils.plot_model to generate and save a PNG image of the model structure.
Results Interpretation

Before: No model summary or visualization available.

After: Model summary printed showing layers, output shapes, and parameter counts. Model architecture image saved as 'model_architecture.png' showing layer connections and shapes.

Using model.summary() helps you understand the model's layers and parameters clearly. Visualizing the model architecture with plot_model creates an easy-to-understand diagram that helps explain the model to others.
Bonus Experiment
Try adding more layers to the model and generate an updated summary and visualization to see how the architecture changes.
💡 Hint
Add another Dense layer with activation 'relu' before the output layer, then rerun model.summary() and plot_model.