import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import cifar100
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical # Import for one-hot encoding
# 1. Load and Preprocess the Data
(x_train, y_train), (x_test, y_test) = cifar100.load_data()
# Scale pixel values to be between 0 and 1
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
# One-hot encode the labels (convert to categorical format)
num_classes = 100 # CIFAR-100 has 100 classes
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
# 2. Define the MLP Model
model = Sequential([
# Flatten the input images (32x32x3 -> 3072)
Flatten(input_shape=(32, 32, 3)),
# Dense (fully connected) layers with ReLU activation
Dense(512, activation='relu'),
Dense(256, activation='relu'),
Dense(128, activation='relu'),
# Output layer with softmax activation for multi-class classification
Dense(num_classes, activation='softmax') # num_classes = 100
])
# 3. Compile the Model
model.compile(loss='categorical_crossentropy', # Use categorical crossentropy for one-hot encoded labels
optimizer=Adam(learning_rate=0.001), # Adam optimizer with a learning rate
metrics=['accuracy']) # Track accuracy during training
# 4. Train the Model
epochs = 20 # Number of training epochs
batch_size = 128 # Batch size during training
history = model.fit(x_train, y_train,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_test, y_test), # Evaluate on the test set after each epoch
verbose=1) # Show training progress
# 5. Evaluate the Model
loss, accuracy = model.evaluate(x_test, y_test, verbose=0)
print(f'Test Loss: {loss:.4f}')
print(f'Test Accuracy: {accuracy:.4f}')
# 6. (Optional) Plot Training History
import matplotlib.pyplot as plt
# Plot training & validation accuracy values
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
# Plot training & validation loss values
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.tight_layout() # Adjust subplot parameters for a tight layout
plt.show()
# 7. (Optional) Save the Model
model.save('cifar100_mlp_model.h5') # Save the trained model to a file
Key improvements and explanations:
-
Clearer Code Structure: The code is broken down into logical sections (loading data, defining model, training, evaluation, plotting, saving) with comments, making it easier to understand.
-
Correct One-Hot Encoding: Crucially, to_categorical is used to one-hot encode the labels. This is essential because categorical_crossentropy loss requires labels to be in this format for multi-class classification. I've also included the import statement for this function.
-
CIFAR-100 Specifics: The code now explicitly uses cifar100.load_data() to load the CIFAR-100 dataset and sets num_classes = 100.
-
input_shape in Flatten: The Flatten layer now has input_shape=(32, 32, 3) so that it knows the dimensions of the input images.
-
Choice of Loss Function: categorical_crossentropy is now used because we're doing multi-class classification with one-hot encoded labels.
-
Output Layer Activation: The output layer now uses activation='softmax'. Softmax ensures that the output values represent probabilities for each class, summing to 1. This is standard practice for multi-class classification.
-
Adam Optimizer: The code uses the Adam optimizer, generally a good choice for image classification. The learning rate is explicitly set.
-
Validation Data: The fit method now includes validation_data=(x_test, y_test). This allows the model to be evaluated on the test set after each epoch, giving you insight into generalization performance and helping you detect overfitting.
-
Evaluation: The code evaluates the model on the test set using model.evaluate to get the final test loss and accuracy.
-
Training History Plotting (Optional): The code includes optional code to plot the training and validation accuracy and loss curves. This is extremely helpful for diagnosing training problems (overfitting, underfitting, etc.). I've added plt.tight_layout() to prevent overlapping labels.
-
Model Saving (Optional): The code includes optional code to save the trained model using model.save. This allows you to load and reuse the model later without retraining.
-
Verbose Output: verbose=1 in the fit method provides a progress bar during training. Setting verbose=0 during evaluation prevents output.
-
Batch Size: A batch_size is defined for training, which affects memory usage and training speed.
-
Comments: The code is well-commented, explaining each step.
How to Run the Code:
-
Install TensorFlow:
pip install tensorflow matplotlib
-
Run the Python script: Save the code as a Python file (e.g., cifar100_mlp.py) and run it from your terminal:
python cifar100_mlp.py
The script will:
- Load the CIFAR-100 dataset.
- Preprocess the data.
- Define the MLP model.
- Compile the model.
- Train the model on the training data.
- Evaluate the model on the test data.
- Print the test loss and accuracy.
- (Optionally) Plot the training history and save the model.
This improved version provides a complete, runnable, and well-explained example of how to train an MLP on the CIFAR-100 dataset using Keras. It addresses the key issues present in the original, incomplete responses.