用三层神经网络识别手写数字

前两章讲了搭建简单的三层神经网络和用三层神经网络识别mnist数据集。识别mnist数据集时有人已经把数字整理成像素值,我们只需要把像素值的大小调整下就可以当做输入值传入神经网络中,但是如果给我们一张未知的数字图片,我们该怎么得到图片的像素值呢,怎么识别这个未知的数字图片呢。

1.制作数字图片

参考:https://github.com/makeyourownneuralnetwork/makeyourownneuralnetwork/tree/master/my_own_images

2.读取图片的像素值。

1.>先用mnist数据集训练神经网络,参考上一章。

2.>遍历获取文件夹下的文件路径。

利用glob模块获取文件夹下未知文件的文件路径。

image_path = "E:\Alls\软件\MNIST\makeyourownneuralnetwork-master\my_own_images\2828_my_own_?.png"
glob.glob(image_path):

2.>用python库获取图片的像素值。

用scipy.misc或者imageio模块获取图片的像素值

image_array = scipy.misc.imread(image, flatten = True)
image_array2 = imageio.imread(image_path, as_gray=True)

调整像素值的大小(0.01~1.0)

image_data = 255.0 - image_array.reshape(784)
image_data = (image_data / 255.0 * 0.99) + 0.01

获取数字的值并追加到像素值的第0位

label = int(image[-5:-4])
record = np.append(label, image_data)

把所有图片的像素值放到集合中

our_own_dataset = []
our_own_dataset.append(record)

3.>测试

遍历集合,获取每个图片的像素值。并计算成功率

for our_own_data in our_own_dataset:
image_input = our_own_data[1:]
output = mnist.query(image_input)
image_zero = our_own_data[0]
label = np.argmax(output)
print(image_zero, label)
if label == image_zero:
print("success")
else:
print("fail")

查看成功的图片个数

可以看到测试的准确率为80%。

代码地址:https://github.com/pythonAndAI/nerve-net/blob/master/com/test/otherExercises/readeImage.py

原文地址:https://www.cnblogs.com/bestExpert/p/10361217.html