import os
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
import keras
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
# Load and preprocess the dataset
def load_data():
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0
return train_images, train_labels, test_images, test_labels
# Build the CNN model
def build_model():
model = models.Sequential([
# First convolutional layer with 32 filters, kernel size of (3,3), and ReLU
activation
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
layers.MaxPooling2D((2, 2)), # Max pooling layer with pool size of (2, 2)
# Second convolutional layer with 64 filters
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
# Third convolutional layer with 64 filters
layers.Conv2D(64, (3, 3), activation='relu'),
# Flatten the 3D output from the convolutional layers to feed into dense layers
layers.Flatten(),
# Dense layer with 64 units and ReLU activation
layers.Dense(64, activation='relu'),
# Output layer with 10 units (for 10 classes), no activation since we'll use
from_logits=True
layers.Dense(10)
])
return model
# Compile and train the model
def compile_and_train(model, train_images, train_labels, test_images, test_labels):
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Train the model and validate with test data
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
return history
# Evaluate the model on the test set
def evaluate_model(model, test_images, test_labels):
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f"Test accuracy: {test_acc}")
# Plot training and validation accuracy over epochs
def plot_training_history(history):
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.show()
# Main function to run the steps
def main():
# Load dataset
train_images, train_labels, test_images, test_labels = load_data()
# Build the CNN model
model = build_model()
# Compile and train the model
history = compile_and_train(model, train_images, train_labels, test_images,
test_labels)
# Evaluate the model on test set
evaluate_model(model, test_images, test_labels)
# Plot the training history
plot_training_history(history)
if __name__ == "__main__":
main()