Introduction
In this tutorial, we will guide you through building your first Convolutional Neural Network (CNN) using TensorFlow 2.x. CNNs are primarily used for image processing tasks such as image classification, object detection, and more. By the end of this tutorial, you will understand the basic components of a CNN and have the tools to create your own models.
Installation
To get started, make sure you have TensorFlow 2.x installed. You can install it using pip:
“`
pip install tensorflow
“`
Import Libraries
“`python
import tensorflow as tf
import matplotlib.pyplot as plt
“`
Data Preparation
For this example, we will use the MNIST dataset which consists of 70,000 grayscale images of handwritten digits for training and 10,000 for testing.
“`python
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
“`
Data Normalization
The pixel values in the MNIST dataset range from 0 to 255. To make the learning process faster and more efficient, we will normalize the data to have values between 0 and 1.
“`python
x_train = x_train / 255.0
x_test = x_test / 255.0
“`
Define Model Architecture
Our CNN will consist of three convolutional layers, each followed by max pooling, and two dense layers.
“`python
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation=’relu’, input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(pool_size=2),
tf.keras.layers.Conv2D(filters=64, kernel_size=3, activation=’relu’),
tf.keras.layers.MaxPooling2D(pool_size=2),
tf.keras.layers.Conv2D(filters=64, kernel_size=3, activation=’relu’),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(units=128, activation=’relu’),
tf.keras.layers.Dense(units=10, activation=’softmax’)
])
“`
Compile Model
Compile the model by specifying the loss function, optimizer, and evaluation metric.
“`python
model.compile(optimizer=’adam’, loss=’sparse_categorical_crossentropy’, metrics=[‘accuracy’])
“`
Train Model
Train the model on the training data for 10 epochs.
“`python
model.fit(x_train, y_train, epochs=10)
“`
Evaluate Model
Evaluate the model’s performance on the test data.
“`python
model.evaluate(x_test, y_test)
“`
Visualize a Model Layer
To visualize the weights of a layer, we can use the `plot_weights` method.
“`python
model.layers[0].plot_weights()
plt.show()
“`