A convolutional neural network, or CNN, is a deep learning neural network designed for processing structured arrays of data such as images. Convolutional neural networks are widely used in computer vision and have become the state of the art for many visual applications such as image classification, and have also found success in natural language processing for text classification.
Convolutional neural networks are very good at picking up on patterns in the input image, such as lines, gradients, circles, or even eyes and faces. It is this property that makes convolutional neural networks so powerful for computer vision. Unlike earlier computer vision algorithms, convolutional neural networks can operate directly on a raw image and do not need any preprocessing.
A convolutional neural network is a feed-forward neural network, often with up to lager number of layers. The power of a convolutional neural network comes from a special kind of layer called the convolutional layer.
from tensorflow.keras import layers from tensorflow.keras import models from tensorflow.keras.datasets import mnist from tensorflow.keras.utils import to_categorical
Define the CNN model
model = models.Sequential() model.add(layers.Conv2D(32, (5,5), activation='relu', input_shape=(28, 28,1))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (5, 5), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Flatten()) model.add(layers.Dense(10, activation='softmax')) model.summary()
Split the data into training and test sets
(train_images, train_labels), (test_images, test_labels) = mnist.load_data() train_images = train_images.reshape((60000, 28, 28, 1)) train_images = train_images.astype('float32') / 255 test_images = test_images.reshape((10000, 28, 28, 1)) test_images = test_images.astype('float32') / 255 train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels)
Train the model
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit(train_images, train_labels, batch_size=100, epochs=5, verbose=1)
Test the model’s accuracy with the test data
test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc)
Test accuracy: 0.9668999910354614