Here's an example of how to train a Convolutional Neural Network (CNN) using Keras with TensorFlow for the MNIST dataset. You can modify it for other datasets:
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
# Load and preprocess data
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize pixel values to [0, 1]
train_images = train_images.astype('float32') / 255
test_images = test_images.astype('float32') / 255
# Add channel dimension for CNN (grayscale images have 1 channel)
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
# One-hot encode labels
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# Build the CNN model
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
# Print model summary
model.summary()
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
history = model.fit(
train_images,
train_labels,
epochs=5,
batch_size=64,
validation_split=0.2
)
# Evaluate the model
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f'\nTest accuracy: {test_acc}')
# Save the model (optional)
model.save('mnist_cnn.h5')
Key Components Explained:
-
Data Preparation:
- Normalize pixel values to [0, 1]
- Reshape for CNN (add channel dimension)
- One-hot encode labels
-
Model Architecture:
- 3 Convolutional layers with ReLU activation
- MaxPooling layers for downsampling
- Flatten layer to convert 2D data to 1D
- 2 Dense layers (last one with softmax for classification)
-
Compilation:
- Uses Adam optimizer
- Categorical crossentropy loss (for multi-class classification)
- Tracks accuracy metric
-
Training:
- Trains for 5 epochs
- Uses 20% of training data for validation
Customization Options:
- Adjust the number of layers/filters (e.g., add more Conv2D layers)
- Modify kernel sizes (e.g., (5,5) instead of (3,3))
- Add dropout layers for regularization:
layers.Dropout(0.2)
- Experiment with different optimizers (e.g., RMSprop)
- Increase epochs for better training (be careful about overfitting)
- Use data augmentation for better generalization
Notes:
- For different datasets, adjust:
- Input shape (e.g., (32, 32, 3) for color images)
- Number of output classes (last Dense layer units)
- Number of training epochs
- Use
model.fit_generator() if using data augmentation
- Add callbacks like EarlyStopping or TensorBoard for advanced training
Would you like to see modifications for a different dataset or architecture?