当前位置: 首页>編程日記>正文

CNN实现手写数字识别

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 = 28height = 28file_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


https://www.fengoutiyan.com/post/14867.html

相关文章:

  • 手写卷积神经网络
  • 人工神经网络实现数字识别
  • 手写数字1
  • 手写数字识别软件
  • cnn图像识别
  • 手写数字识别代码
  • 手写字符识别
  • 数字识别
  • 鏡像模式如何設置在哪,圖片鏡像操作
  • 什么軟件可以把圖片鏡像翻轉,C#圖片處理 解決左右鏡像相反(旋轉圖片)
  • 手機照片鏡像翻轉,C#圖像鏡像
  • 視頻鏡像翻轉軟件,python圖片鏡像翻轉_python中鏡像實現方法
  • 什么軟件可以把圖片鏡像翻轉,利用PS實現圖片的鏡像處理
  • 照片鏡像翻轉app,java實現圖片鏡像翻轉
  • 什么軟件可以把圖片鏡像翻轉,python圖片鏡像翻轉_python圖像處理之鏡像實現方法
  • matlab下載,matlab如何鏡像處理圖片,matlab實現圖像鏡像
  • 圖片鏡像翻轉,MATLAB:鏡像圖片
  • 鏡像翻轉圖片的軟件,圖像處理:實現圖片鏡像(基于python)
  • canvas可畫,JavaScript - canvas - 鏡像圖片
  • 圖片鏡像翻轉,UGUI優化:使用鏡像圖片
  • Codeforces,CodeForces 1253C
  • MySQL下載安裝,Mysql ERROR: 1253 解決方法
  • 勝利大逃亡英雄逃亡方案,HDU - 1253 勝利大逃亡 BFS
  • 大一c語言期末考試試題及答案匯總,電大計算機C語言1253,1253《C語言程序設計》電大期末精彩試題及其問題詳解
  • lu求解線性方程組,P1253 [yLOI2018] 扶蘇的問題 (線段樹)
  • c語言程序設計基礎題庫,1253號C語言程序設計試題,2016年1月試卷號1253C語言程序設計A.pdf
  • 信奧賽一本通官網,【信奧賽一本通】1253:抓住那頭牛(詳細代碼)
  • c語言程序設計1253,1253c語言程序設計a(2010年1月)
  • 勝利大逃亡英雄逃亡方案,BFS——1253 勝利大逃亡
  • 直流電壓測量模塊,IM1253B交直流電能計量模塊(艾銳達光電)
  • c語言程序設計第三版課后答案,【渝粵題庫】國家開放大學2021春1253C語言程序設計答案
  • 18轉換為二進制,1253. 將數字轉換為16進制
  • light-emitting diode,LightOJ-1253 Misere Nim
  • masterroyale魔改版,1253 Dungeon Master
  • codeformer官網中文版,codeforces.1253 B
  • c語言程序設計考研真題及答案,2020C語言程序設計1253,1253計算機科學與技術專業C語言程序設計A科目2020年09月國家開 放大學(中央廣播電視大學)
  • c語言程序設計基礎題庫,1253本科2016c語言程序設計試題,1253電大《C語言程序設計A》試題和答案200901
  • 肇事逃逸車輛無法聯系到車主怎么辦,1253尋找肇事司機