How to create a Convolutional Neural Network in Python?

Artificial Intelligence

Convolutional neural networks (CNNs) are a type of neural network that is particularly well-suited for image classification tasks. Here is an example of how you might create a simple CNN in Python using the popular deep learning library Keras:

from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from keras.models import Sequential

# Create the model
model = Sequential()

# Add convolutional layers
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

# Add fully connected layers
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))

# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

This code creates a simple CNN with two convolutional layers and two fully connected layers. The input shape of the first convolutional layer is specified as (28, 28, 1), which corresponds to 28×28 grayscale images. If you have color images, you would set the input shape to (28, 28, 3) for a 28×28 image with 3 color channels (red, green, and blue). You can then use the fit() method to train the model on your dataset. For example:

# Load your training data
X_train, y_train = load_training_data()

# Fit the model on the training data
model.fit(X_train, y_train, batch_size=64, epochs=10)