
04/11/2024
The CIFAR-10 dataset is a popular benchmark dataset in machine learning, consisting of 60,000 32x32 color images in 10 different classes, with 6,000 images per class (e.g., airplane, car, bird, cat, etc.). This dataset is often used for training image classification models, and it provides a convenient starting point for beginners interested in deep learning.
First, ensure you have the necessary libraries installed:
pip install tensorflow keras
Now, let's import the required libraries for our CNN:
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, models # Set random seeds for reproducibility np.random.seed(42) tf.random.set_seed(42)
Next, we'll load the CIFAR-10 dataset directly from Keras:
# Load dataset (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data() # Normalize the data to values 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 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10)
Here, we split the dataset into training and testing sets, normalized pixel values, and one-hot encoded the labels.
Now it’s time to build our convolutional neural network. Here's a simple, yet effective architecture for classifying images:
model = models.Sequential([ layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(10, activation='softmax') ]) model.summary()
After building the model, we must specify the optimizer, loss function, and metrics:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Let’s train our CNN with the training dataset:
history = model.fit(x_train, y_train, epochs=10, batch_size=64, validation_data=(x_test, y_test))
After training, we need to evaluate our model's performance on the test data:
test_loss, test_acc = model.evaluate(x_test, y_test) print("Test accuracy:", test_acc)
It's useful to visualize the training and validation accuracy over epochs to understand how well our model is performing:
import matplotlib.pyplot as plt plt.plot(history.history['accuracy'], label='accuracy') plt.plot(history.history['val_accuracy'], label='val_accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend() plt.show()
In this tutorial, we've constructed a CNN using TensorFlow and Keras to classify the CIFAR-10 dataset. We learned how to load the data, build a model, train it, and evaluate its performance. Don’t hesitate to play around with the model architecture or parameters to see how it influences the accuracy!
04/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python