先给出代码,很多代码是在其他地方借鉴过来的,大家也可以自己搜搜,主要分享一下自己做的过程
# -- coding: utf-8 --”
import numpy as np # 导入数据库
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
from PIL import Image
import tensorflow as tf
import matplotlib.pyplot as plt
seed = 7 # 设置随机种子
np.random.seed(seed)
(X_train, y_train), (X_test, y_test) = mnist.load_data() # 加载数据
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32')
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
# 数据集是3维的向量(instance length,width,height).对于多层感知机,模型的输入是二维的向量,因此这
# 里需要将数据集reshape,即将28*28的向量转成784长度的数组。可以用numpy的reshape函数轻松实现这个过
# 程。
# 给定的像素的灰度值在0-255,为了使模型的训练效果更好,通常将数值归一化映射到0-1。
X_train = X_train / 255
X_test = X_test / 255
# 最后,模型的输出是对每个类别的打分预测,对于分类结果从0-9的每个类别都有一个预测分值,表示将模型
# 输入预测为该类的概率大小,概率越大可信度越高。由于原始的数据标签是0-9的整数值,通常将其表示成#0ne-hot向量。如第一个训练数据的标签为5,one-hot表示为[0,0,0,0,0,1,0,0,0,0]。
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
# 现在需要做得就是搭建神经网络模型了,创建一个函数,建立含有一个隐层的神经网络。
# define baseline model
def baseline_model():
# create model
model = Sequential()
model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu'))
model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# 型的隐含层含有784个节点,接受的输入长度也是784(28*28),最后用softmax函数将预测结果转换为标签
# 的概率值。
# 将训练数据fit到模型,设置了迭代轮数,每轮200个训练样本,将测试集作为验证集,并查看训练的效果。
# build the model
model = baseline_model()
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2)
# Final evaluation of the model
loss,accuracy = model.evaluate(X_test, y_test, verbose=2)
print('loss:%s,accuracy:%s'%(loss,accuracy))
#这个函数是转换自己的图片成矩阵
def loadImage():
# 读取图片
im = Image.open('D:\chromeDownload\9 (3).jpg')
# 显示图片
im = im.convert("L")
data = im.getdata()
data = np.matrix(data)
# print data
# 变换成512*512
data = np.reshape(data, (1,28,28))
new_im = Image.fromarray(data)
# 显示图片
data = data/255
return data
demo = tf.reshape(loadImage(),(1,784))
y_pred = np.argmax(model.predict(demo))
print(y_pred,model.predict(demo))
img = plt.imread('D:\chromeDownload\9 (3).jpg')
plt.imshow(img)
plt.xlabel('prediction '+str(y_pred))
plt.show()
一、先书写数据
用什么呢?我用的是windows自带的画图,因为自己有画板,所以写起来更贴进真实的手写体。
我试过,如果用鼠标直接写,貌似识别率很低
先将画布涂成纯黑的
然后用记号笔,像素4,开始手写
二、转换图片
写好后,截图即可
然后用手机的photoshop转成28*28的
三、将图片路径放进代码
一共两个地方
将这两个地方改成你自己的路径
四、RUN
预测对了!!!!
对应的预测向量,能看出预测为4的概率是0.632,预测为9的概率是0.224,压倒性胜利



