Keras Exercises
Problem 1: Create a neural network designed to look at a dataset with 4 features (like the Iris dataset) and classify them into 3 different categories. Add one hidden layer with 8 neurons, and an output layer with 3 neurons. Then, print out the blueprint of your model.
keras-exercises.py
import tensorflow as tf
# 1. Initialize the Sequential model
model = tf.keras.Sequential([
# Hidden layer: 8 neurons, ReLU activation, expecting 4 input features
tf.keras.layers.Dense(units=8, activation='relu', input_shape=(4,)),
# Output layer: 3 neurons (one for each category), Softmax activation for probabilities
tf.keras.layers.Dense(units=3, activation='softmax')
])
# 2. Print the blueprint of the network
model.summary()
Problem 2: Generate some random dummy data (100 samples, 5 features each) and random binary labels (0 or 1). Build a simple model, compile it for binary classification, and train it for 10 epochs. Save the training history and print out the final accuracy.
keras-exercises.py
import tensorflow as tf
import numpy as np
# 1. Generate dummy data
X_train = np.random.random((100, 5))
y_train = np.random.randint(2, size=(100, 1))
# 2. Build a simple model
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='relu', input_shape=(5,)),
tf.keras.layers.Dense(1, activation='sigmoid') # Sigmoid outputs a value between 0 and 1
])
# 3. Compile the model
model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
# 4. Train the model and capture the history
print("Training started...
")
history = model.fit(X_train, y_train, epochs=10, verbose=0) # verbose=0 hides the progress bar
# 5. Extract the final accuracy from the history dictionary
final_accuracy = history.history['accuracy'][-1]
print(f"Training completed! Final Accuracy: {final_accuracy * 100:.2f}%")
Problem 3: Training a model can take hours or days, so you need to be able to save your work. Create a tiny model, save it to your local disk, delete it from memory, and then successfully load it back up.
keras-exercises.py
import tensorflow as tf
# 1. Create and compile a basic model
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(optimizer='adam', loss='mse')
# 2. Save the entire model (architecture, weights, and optimizer state)
model.save('my_simple_model.keras')
print("Model saved to disk!")
# Delete the model from memory to prove it works
del model
# 3. Load the model back from the file
loaded_model = tf.keras.models.load_model('my_simple_model.keras')
print("
Model successfully loaded from disk! Here is the summary:")
# 4. Prove it's the same model
loaded_model.summary()