0
0
TensorFlowml~20 mins

Why Keras simplifies model building in TensorFlow - Experiment to Prove It

Choose your learning style9 modes available
Experiment - Why Keras simplifies model building
Problem:You want to build a neural network model to classify handwritten digits using the MNIST dataset. Currently, you are writing long and complex code with low readability and many manual steps.
Current Metrics:Training accuracy: 95%, Validation accuracy: 93%, Training loss: 0.15, Validation loss: 0.18
Issue:The code is hard to write and understand, making it difficult to experiment and improve the model quickly.
Your Task
Simplify the model building process using Keras Sequential API to make the code shorter, clearer, and easier to modify, while maintaining similar accuracy and loss.
Use the Keras Sequential API only
Keep the model architecture similar (two hidden layers)
Use the same dataset (MNIST)
Maintain training for 5 epochs
Hint 1
Hint 2
Hint 3
Hint 4
Solution
TensorFlow
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten

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

# Normalize pixel values
X_train, X_test = X_train / 255.0, X_test / 255.0

# Build model using Keras Sequential API
model = Sequential([
    Flatten(input_shape=(28, 28)),
    Dense(128, activation='relu'),
    Dense(64, activation='relu'),
    Dense(10, activation='softmax')
])

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

# Train model
history = model.fit(X_train, y_train, epochs=5, validation_split=0.2)

# Evaluate on test data
test_loss, test_acc = model.evaluate(X_test, y_test)
Replaced manual layer creation and training loops with Keras Sequential API
Used Flatten layer to convert 2D images to 1D vectors automatically
Used Dense layers with activation functions in a simple list format
Compiled model with optimizer, loss, and metrics in one step
Used model.fit with validation_split to handle validation automatically
Results Interpretation

Before: Complex code with manual steps, training accuracy 95%, validation accuracy 93%, loss around 0.15-0.18.

After: Simple, readable code using Keras Sequential API, training accuracy improved to ~97%, validation accuracy ~96%, loss reduced to ~0.08-0.10.

Keras simplifies building neural networks by providing a clear, concise API that handles many details automatically. This makes your code easier to write, read, and modify, while achieving good model performance.
Bonus Experiment
Try adding a Dropout layer after the first Dense layer to reduce overfitting and observe the effect on validation accuracy.
💡 Hint
Use keras.layers.Dropout with a rate like 0.2 between Dense layers and retrain the model.