Certainly! To conduct a Convolutional Neural Network (CNN) in Python, you would typically use a deep learning library such as TensorFlow with Keras, which simplifies the process of building and training neural networks. Below is an example of how you can create a simple CNN using TensorFlow and Keras for image classification on the MNIST dataset, which consists of handwritten digits.
First, make sure you have TensorFlow installed. You can install it using pip:
pip install tensorflow
Then, you can create a CNN using the following Python code:
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
# Load and prepare the MNIST dataset
mnist = datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0
# Reshape images to fit the convolutional layer expectations
train_images = train_images[..., tf.newaxis]
test_images = test_images[..., tf.newaxis]
# Build the convolutional base
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
])
# Add Dense layers on top
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
# Display the architecture of the model
model.summary()
# Compile and train the model
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=5,
validation_data=(test_images, test_labels))
# Evaluate the model
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
# Plot training & validation accuracy values
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt