深度学习(一):Python神经网络——手写数字识别
声明:本文章为阅读书籍《Python神经网络编程》而来,代码与书中略有差异,书籍封面:

源码
若要本地运行,请更改源码中图片与数据集的位置,环境为 Python3.6x.
1 import numpy as np
2 import scipy.special as ss
3 import matplotlib.pyplot as plt
4 import imageio as im
5 import glob as gl
6
7
8 class NeuralNetwork:
9 # initialise the network
10 def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
11 # set number of each layer
12 self.inodes = inputnodes
13 self.hnodes = hiddennodes
14 self.onodes = outputnodes
15 self.wih = np.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes, self.inodes))
16 self.who = np.random.normal(0.0, pow(self.hnodes, -0.5), (self.onodes, self.hnodes))
17 # learning rate
18 self.lr = learningrate
19 # activation function is sigmoid
20 self.activation_function = lambda x: ss.expit(x)
21 pass
22
23 # train the neural network
24 def train(self, inputs_list, targets_list):
25 inputs = np.array(inputs_list, ndmin=2).T
26 targets = np.array(targets_list, ndmin=2).T
27 hidden_inputs = np.dot(self.wih, inputs)
28 hidden_outputs = self.activation_function(hidden_inputs)
29 final_inputs = np.dot(self.who, hidden_outputs)
30 final_outputs = self.activation_function(final_inputs)
31 # errors
32 output_errors = targets - final_outputs
33 # b-p algorithm
34 hidden_errors = np.dot(self.who.T, output_errors)
35 # update weight
36 self.who += self.lr * np.dot((output_errors * final_outputs * (1.0 - final_outputs)),
37 np.transpose(hidden_outputs))
38 self.wih += self.lr * np.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), np.transpose(inputs))
39 pass
40
41 # query the neural network
42 def query(self, inputs_list):
43 inputs = np.array(inputs_list, ndmin=2).T
44 hidden_inputs = np.dot(self.wih, inputs)
45 hidden_outputs = self.activation_function(hidden_inputs)
46 final_inputs = np.dot(self.who, hidden_outputs)
47 final_outputs = self.activation_function(final_inputs)
48 return final_outputs
49
50 # numbers
51
52
53 input_nodes = 784
54 hidden_nodes = 100
55 output_nodes = 10
56
57 # learning rate
58 learning_rate = 0.2
59
60 # creat instance of neural network
61 global n
62 n = NeuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
63
64 # file read only ,root of the file
65 training_data_file = open(r"C:\Users\ELIO\Desktop\mnist_train.txt", 'r')
66 training_data_list = training_data_file.readlines()
67 training_data_file.close()
68
69 # train the neural network
70 epochs = 5
71 for e in range(epochs):
72 for record in training_data_list:
73 all_values = record.split(',')
74 # scale and shift the inputs
75 inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
76 targets = np.zeros(output_nodes) + 0.01
77 # all_values[0] is the target label for this record
78 targets[int(all_values[0])] = 0.99
79 n.train(inputs, targets)
80 pass
81 pass
82
83 # load the file into a list
84 test_data_file = open(r"C:\Users\ELIO\Desktop\mnist_train_100.csv.txt", 'r')
85 test_data_list = test_data_file.readlines()
86 test_data_file.close()
87
88 # test the neural network
89 # score for how well the network performs
90 score = []
91
92 # go through all the records
93 for record in test_data_list:
94 all_values = record.split(',')
95 # correct answer is the first value
96 correct_label = int(all_values[0])
97 # scale and shift the inputs
98 inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
99 # query the network
100 outputs = n.query(inputs)
101 # the index of the highest value corresponds to the label
102 label = np.argmax(outputs)
103 # append correct or incorrect to list
104 if (label == correct_label):
105 score.append(1)
106 else:
107 score.append(0)
108 pass
109 pass
110 # module1 CORRECT-RATE
111 # calculate the score, the fraction of correct answers
112 score_array = np.asarray(score)
113 print("performance = ", score_array.sum() / score_array.size)
114
115 # module2 TEST MNIST
116 all_values = test_data_list[0].split(',')
117 print(all_values[0])
118 image_array = np.asfarray(all_values[1:]).reshape((28, 28))
119 plt.imshow(image_array, cmap='Greys', interpolation='None')
120 plt.show()
121
122 # module3 USE YOUR WRITING
123 # own image test data set
124 own_dataset = []
125 for image_file_name in gl.gl(r'C:\Users\ELIO\Desktop\5.png'):
126 print("loading ... ", image_file_name)
127 # use the filename to set the label
128 label = int(image_file_name[-5:-4])
129 # load image data from png files into an array
130 img_array = im.imread(image_file_name, as_gray=True)
131 # reshape from 28x28 to list of 784 values, invert values
132 img_data = 255.0 - img_array.reshape(784)
133 # then scale data to range from 0.01 to 1.0
134 img_data = (img_data / 255.0 * 0.99) + 0.01
135 print(np.min(img_data))
136 print(np.max(img_data))
137 # append label and image data to test data set
138 record = np.append(label, img_data)
139 print(record)
140 own_dataset.append(record)
141 pass
142 all_values = own_dataset[0]
143 print(all_values[0])
数据集,实验图片
链接:百度网盘
提取码:1vbq
深度学习(一):Python神经网络——手写数字识别的更多相关文章
- TensorFlow 卷积神经网络手写数字识别数据集介绍
欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 手写数字识别 接下来将会以 MNIST 数据集为例,使用卷积层和池 ...
- 基于Numpy的神经网络+手写数字识别
基于Numpy的神经网络+手写数字识别 本文代码来自Tariq Rashid所著<Python神经网络编程> 代码分为三个部分,框架如下所示: # neural network class ...
- 深度学习-使用cuda加速卷积神经网络-手写数字识别准确率99.7%
源码和运行结果 cuda:https://github.com/zhxfl/CUDA-CNN C语言版本参考自:http://eric-yuan.me/ 针对著名手写数字识别的库mnist,准确率是9 ...
- 吴裕雄 python神经网络 手写数字图片识别(5)
import kerasimport matplotlib.pyplot as pltfrom keras.models import Sequentialfrom keras.layers impo ...
- 神经网络手写数字识别numpy实现
本文摘自Michael Nielsen的Neural Network and Deep Learning,该书的github网址为:https://github.com/mnielsen/neural ...
- 手写数字识别 ----在已经训练好的数据上根据28*28的图片获取识别概率(基于Tensorflow,Python)
通过: 手写数字识别 ----卷积神经网络模型官方案例详解(基于Tensorflow,Python) 手写数字识别 ----Softmax回归模型官方案例详解(基于Tensorflow,Pytho ...
- 【深度学习系列】手写数字识别卷积神经--卷积神经网络CNN原理详解(一)
上篇文章我们给出了用paddlepaddle来做手写数字识别的示例,并对网络结构进行到了调整,提高了识别的精度.有的同学表示不是很理解原理,为什么传统的机器学习算法,简单的神经网络(如多层感知机)都可 ...
- 深度学习面试题12:LeNet(手写数字识别)
目录 神经网络的卷积.池化.拉伸 LeNet网络结构 LeNet在MNIST数据集上应用 参考资料 LeNet是卷积神经网络的祖师爷LeCun在1998年提出,用于解决手写数字识别的视觉任务.自那时起 ...
- mnist手写数字识别——深度学习入门项目(tensorflow+keras+Sequential模型)
前言 今天记录一下深度学习的另外一个入门项目——<mnist数据集手写数字识别>,这是一个入门必备的学习案例,主要使用了tensorflow下的keras网络结构的Sequential模型 ...
随机推荐
- 推荐给 Java 程序员的 7 本书
< Java 编程思想> 适合各个阶段 Java 程序员的必备读物.书中对 Java 进行了详尽的介绍,与其它语言做了对比,解释了 Java 很多特性出现的原因和解决的问题.初学者可以通过 ...
- 云服务器部署Python项目(nginx+uwsgi+mysql+项目)
python项目部署到云服务器 关注公众号"轻松学编程"了解更多. 一.硬件准备 云服务器,系统ubuntu_16_04 . 注意:要在安全组中开放Http的80端口. 二.软件准 ...
- python pip源国内加速
Pip源国内加速list 清华:https://pypi.tuna.tsinghua.edu.cn/simple 阿里云:http://mirrors.aliyun.com/pypi/simple/ ...
- ubuntu18.04 安装RabbitVCS
因为仓库安装一直安装不上所以手动安装 第一步:下载 https://github.com/rabbitvcs/rabbitvcs/ 安装 解压安装 python setup.py install -- ...
- ubuntu下安装ESP8266开发环境步骤中可能出现的问题及解决办法
安装步骤参考如下链接 https://www.jianshu.com/p/e9ce2a60df83 1.在GitHub上拉取代码时发生错误:RPC failed; curl 18 transfer c ...
- Spring5.0源码学习系列之浅谈懒加载机制原理
前言介绍 附录:Spring源码学习专栏 在上一章的学习中,我们对Bean的创建有了一个粗略的了解,接着本文挑一个比较重要的知识点Bean的懒加载进行学习 1.什么是懒加载? 懒加载(Lazy-ini ...
- ip_rcv 中使用skb_share_check
/* * Main IP Receive routine. */ int ip_rcv(struct sk_buff *skb, struct net_device *dev, struct pack ...
- linux文件描述符、软硬连接、输入输出重定向
引用链接:https://blog.csdn.net/qq769651718/article/details/79459346 文件描述符的作用: 文件描述符是linux操作系统中特有的概念.其相当于 ...
- 如何替换Ceph的Journal
很多人会提出这样的问题: 能不能够将 Ceph journal 分区从一个磁盘替换到另一个磁盘? 怎样替换 Ceph 的 journal 分区? 有两种方法来修改Ceph的journal: 创建一个j ...
- MySQL 5.x乱码问题解决
MySQL是一款常用的开源数据库软件,但是对于初次使用者好像并不是太友好,MySQL5.x的版本中默认字符集是latin1也就是我们所知道的ISO-8859-1字符集,这个字符集编码并没有包含汉字,所 ...