CNN实现手写数字识别

手写数字识别一致是一个机器学习里面常见的案例,今天通过CNN来实现一个手写数字识别来介绍一个机器学习的流程。

数据预处理

from keras import datasets
(x_train, y_train), (x_test, y_test) = datasets.mnist.load_data()
x_train = x_train.reshape((60000, 28, 28, 1))
# 归一化,0-255不太方便神经网络进行计算,因此将范围缩小到0—1
x_train = x_train.astype('float32') / 255
x_test = x_test.reshape((10000, 28, 28, 1))
x_test = x_test.astype('float32') / 255

构建模型

from keras import models,layers
from keras import backend as K
K.clear_session()
#初始化模型,可以通过add往里面加层
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3) ))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3)))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
#查看模型结构
model.summary()

在这里插入图片描述

模型训练

model.compile() 作用:
设置优化器、损失函数和准确率评测标准。

optimizer:
1.“sgd” 或者 tf.optimizers.SGD(lr = 学习率, decay = 学习率衰减率,momentum = 动量参数)

2.“adagrad” 或者 tf.keras.optimizers.Adagrad(lr = 学习率, decay = 学习率衰减率)

3.“adadelta” 或者 tf.keras.optimizers.Adadelta(lr = 学习率,decay = 学习率衰减率)

4.“adam” 或者 tf.keras.optimizers.Adam(lr = 学习率, decay = 学习率衰减率)
loss:
1.“mse” 或者 “mean squared error” 或 tf.keras.losses.MeanSquaredError()
2.“sparse_categorical_crossentropy” 或 tf.keras.losses.SparseCatagoricalCrossentropy(from_logits = False)
Metrics:
1.“accuracy” :
2.“sparse_accuracy":
3.“sparse_categorical_accuracy” :

在这里插入图片描述


model.compile(optimizer='rmsprop',
              loss='sparse_categorical_crossentropy', # 注意此处loss形式针对未作Onehot的分类标签
              metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=2,
          batch_size=64,validation_data =(x_test,y_test))
import pandas as pd
import matplotlib.pyplot as plt
dfhistory = pd.DataFrame(history.history)
dfhistory.index = range(1,len(dfhistory) + 1)
dfhistory.index.name = 'epoch'
dfhistory.to_csv('hitory_metrics',sep = '\t')
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'bo', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

在这里插入图片描述

model.save('minst_model.h5')

我们在网上随便找一张图片实验
在这里插入图片描述

from PIL import Image
import numpy as np
def produceImage(file_in, width, height, file_out):
	image = Image.open(file_in)
	resized_image = image.resize((width, height), Image.ANTIALIAS)
	resized_image.save(file_out)
if __name__ == '__main__':
	file_in = r'image\2.png'
	width = 28
	height = 28
	file_out = r'image\2_1.png'
	produceImage(file_in, width, height, file_out)
	# 把图像转化为黑白的
	im = Image.open(r'image\2_1.png')
	L = im.convert("L")
	L.save(r'image\2_1.png')

通过以上代码进行裁切得到
在这里插入图片描述
我们通过刚刚保存的模型去实验

import tensorflow as tf
from PIL import Image
import numpy as np
im_4 = Image.open(r'image\2_1.png')
im_4 = np.reshape(im_4, [1,28,28,1])
#调用模型
new_model =tf.keras.models.load_model('minst_model.h5')
#进行预测
pe_4 = new_model.predict(im_4)
#把最大的坐标找到,因为new_model.predict返回的是[0,0,1,0,0,0,0,0,0,0]这种格式,
#所以需要转换为我们熟悉的格式
pe_4 = tf.argmax(pe_4 ,1)

with tf.Session() as sess:
    print(sess.run(pe_4))

输出结果:
2

  • 3
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
手写数字识别是一个经典的机器学习问题,可以使用卷积神经网络(CNN)来解决。下面是一个简单的CNN实现手写数字识别的步骤: 1. 加载数据集:使用MNIST数据集,它包含60,000个训练样本和10,000个测试样本,每个样本都是28×28像素的灰度图像。 2. 数据预处理:将每个像素值缩放到0到1的范围内,并将标签进行one-hot编码。 3. 构建CNN模型:使用卷积层、池化层和全连接层来构建模型。模型的输入是28×28像素的图像,输出是10个数字类别的概率分布。 4. 训练模型:使用训练集进行模型训练,可以使用交叉熵损失函数和随机梯度下降优化器。 5. 评估模型:使用测试集进行模型评估,可以计算模型的准确率。 下面是一个简单的CNN手写数字识别代码示例: ```python import tensorflow as tf from tensorflow.keras.datasets import mnist # 加载数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() # 数据预处理 x_train = x_train / 255.0 x_test = x_test / 255.0 y_train = tf.keras.utils.to_categorical(y_train) y_test = tf.keras.utils.to_categorical(y_test) # 构建CNN模型 model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(x_train.reshape(-1,28,28,1), y_train, epochs=5, batch_size=32, validation_data=(x_test.reshape(-1,28,28,1), y_test)) # 评估模型 model.evaluate(x_test.reshape(-1,28,28,1), y_test) ``` 这个模型包含了一个卷积层、一个池化层、一个flatten层和两个全连接层。在训练模型之前,我们预处理了数据并将其reshape成了28×28×1的张量。在训练模型时,我们使用了交叉熵损失函数和Adam优化器。最后,我们使用测试集评估了模型的准确率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

彭祥.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值