---
# System prepended metadata

title: Convolutional Neural Network

---

**Convolutional Neural Network (CNN) Overview:**

Convolutional Neural Networks (CNNs) are deep learning models designed for image-related tasks, such as image classification, object detection, and image generation. CNNs are particularly effective in capturing spatial hierarchies of features in images through convolutional layers.

In this example, we'll use a dataset to demonstrate a simple CNN for image classification.

**Example Using a Dataset:**

**Step 1: Import Libraries**
```python
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.utils import to_categorical
```

**Step 2: Load and Prepare the Dataset**
```python
# Load the CIFAR-10 dataset (you can replace this with your own dataset)
(X_train, y_train), (X_test, y_test) = cifar10.load_data()

# Normalize pixel values to the range [0, 1]
X_train = X_train.astype('float32') / 255.0
X_test = X_test.astype('float32') / 255.0

# One-hot encode the labels
y_train = to_categorical(y_train, num_classes=10)
y_test = to_categorical(y_test, num_classes=10)
```

**Step 3: Create and Train the CNN Model**
```python
# Create a Sequential model
cnn_model = Sequential()

# Add convolutional layers
cnn_model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
cnn_model.add(MaxPooling2D((2, 2)))
cnn_model.add(Conv2D(64, (3, 3), activation='relu'))
cnn_model.add(MaxPooling2D((2, 2)))

# Flatten the feature maps
cnn_model.add(Flatten())

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

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

# Train the model on the training data
cnn_model.fit(X_train, y_train, epochs=10, batch_size=64, validation_split=0.2)
```

**Params That Can Be Changed**
1. **Conv2D** parameters:
   - `filters`: Specifies the number of convolutional filters or kernels.
   - `kernel_size`: Defines the size of the convolutional kernel.
   - `activation`: Specifies the activation function for the layer.

2. **MaxPooling2D** parameters:
   - `pool_size`: Defines the size of the pooling window.

3. **Dense** layer parameters:
   - `units`: Specifies the number of neurons or units in the layer.
   - `activation`: Specifies the activation function for the layer.

4. **Compile parameters**:
   - `optimizer`: Specifies the optimization algorithm (e.g., 'adam').
   - `loss`: Defines the loss function (e.g., 'categorical_crossentropy').

**Step 4: Evaluate the Model**
```python
# Evaluate the model on the test data
test_loss, test_accuracy = cnn_model.evaluate(X_test, y_test, verbose=0)
print(f"Test Accuracy: {test_accuracy * 100:.2f}%")
```

**Explanation:**

1. We import the necessary libraries, including NumPy for numerical operations, Matplotlib for visualization, TensorFlow for deep learning, and more.

2. We load the CIFAR-10 dataset, which contains 60,000 32x32 color images in 10 different classes. We normalize pixel values to the range [0, 1] and one-hot encode the labels.

3. We create a Sequential model, which allows us to build a deep learning model layer by layer.

4. We add convolutional layers to the model using `Conv2D` and max-pooling layers using `MaxPooling2D`. These layers learn hierarchical features from the input images.

5. We flatten the feature maps into a one-dimensional vector to connect them to fully connected layers.

6. Fully connected layers are added with `Dense` layers. The last layer has 10 units with softmax activation for multiclass classification.

7. We compile the model, specifying the optimizer and loss function.

8. The model is trained on the training data for a specified number of epochs and batch size.

9. We evaluate the model's performance on the test data, calculating test accuracy.

CNNs are powerful for image-related tasks, but their architecture can be customized with various parameters like filter size, pool size, number of units, and more. These parameters allow you to adapt the model to your specific image classification task and dataset.