Home  >  Article  >  Backend Development  >  Handwritten digit recognition example in Python

Handwritten digit recognition example in Python

WBOY
WBOYOriginal
2023-06-11 10:13:362156browse

Python is a very powerful programming language that is widely used in data analysis, machine learning, image processing and other fields. In the field of machine learning, handwritten digit recognition is a very important issue and can be applied to many fields such as verification code recognition, autonomous driving, and speech recognition. In this article, we will introduce how to implement handwritten digit recognition using Python.

  1. Introduction to data sets

In machine learning, the selection of data sets is very important. For the problem of handwritten digit recognition, we need a labeled dataset. The most commonly used data set is the MNIST (Modified National Institute of Standards and Technology) data set, which contains a total of 60,000 training images and 10,000 test images. Each image is a 28x28 pixel grayscale image.

  1. Loading the data set

In order to use the MNIST data set, we can load it through the python library. In this example, we use Tensorflow’s Keras library to load the MNIST dataset.

from keras.datasets import mnist

# 加载MNIST数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

Here we store the training images and labels in train_images and train_labels and the test images and labels in test_images and test_labels in.

  1. Data preprocessing

In machine learning, we usually need to preprocess data to improve the performance of the model. For the MNIST dataset, we need to convert the pixel values ​​into floating point numbers between 0 and 1, and convert the 28x28 image into a 784-dimensional vector so that we can input it into the model.

# 数据预处理
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255

test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
  1. Building the model

Building a neural network in Keras is very simple, we only need to define a Sequential object and then add layers. For this handwritten digit recognition problem, we use a simple neural network with two dense layers.

from keras import models
from keras import layers

network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))

Here we use a Dense layer, each neuron is connected to all neurons in the previous layer, and uses the ReLU activation function to add nonlinearity.

  1. Compile the model

Before training the model, we need to configure the learning process through compilation. Here, we use the cross-entropy loss function and the RMSprop optimizer. At the same time, we will also add accuracy as a metric.

network.compile(optimizer='rmsprop',
                loss='categorical_crossentropy',
                metrics=['accuracy'])
  1. Training the model

Now we can train the model using the dataset we loaded. Here, we will train the model 5 times (epochs=5).

network.fit(train_images, train_labels, epochs=5, batch_size=128)
  1. Test model

Use the trained model to predict the test data and calculate the accuracy.

test_loss, test_acc = network.evaluate(test_images, test_labels)
  1. Practical Application

Now we have trained a handwritten digit recognition model that can be used in practical applications. Below is an example that demonstrates how to use a model to recognize handwritten digits.

import numpy as np
from keras.preprocessing import image

# 加载手写数字图像
img = image.load_img(path_to_img, grayscale=True, target_size=(28, 28))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

# 预测手写数字
prediction = network.predict(x)

# 输出结果
print(prediction)

Here we first use the image.load_img function to load an image of handwritten digits and then convert it to the format required by the model. Finally, use the network.predict function to predict and output the results.

  1. Summary

In this article, we introduced how to implement handwritten digit recognition using Python and the Keras library. In this process, we learned about loading the MNIST data set, data preprocessing, building a neural network model, compiling the model, training the model, testing the model and practical applications. Hope this example can help beginners understand machine learning better.

The above is the detailed content of Handwritten digit recognition example in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn