基于BP神经网络的手MNIST写数字识别
import numpy
import math
import scipy.special#特殊函数模块
import matplotlib.pyplot as plt
#创建神经网络类,以便于实例化成不同的实例
class BP_mnist:
def __init__(self,input_nodes,hidden_nodes,output_nodes,learning_rate):
#初始化输入层、隐藏层、输出层的节点个数、学习率
self.inodes = input_nodes
self.hnodes = hidden_nodes
self.onodes = output_nodes
self.learning_rate = learning_rate
# self.w_input_hidden = numpy.random.normal(0, pow(self.hnodes,-0.5) , (self.hnodes,self.inodes))
# self.w_hidden_output = numpy.random.normal(0, pow(self.onodes,-0.5) , (self.onodes,self.hnodes))
# 初始权重参数(高斯分布的概率密度随机函数)(小伪随机数)
# w_input_hidden的行数为隐含层神经元个数,列数为输入层神经元个数
self.w_input_hidden = numpy.random.normal(0, 1 , (self.hnodes,self.inodes))
self.w_hidden_output = numpy.random.normal(0, 1 , (self.onodes,self.hnodes))
#定义激活函数
self.sigmoid = lambda x: scipy.special.expit(x)#计算整个矩阵里各元素的sigmoid值:1/(1+exp(-x))
def train(self,input_list,target_list):
#inputs = numpy.array(input_list,ndmin = 2).T #最小维数为2,即把一维矩阵升维
inputs = input_list[:, numpy.newaxis]#增加一个维度
#targets = numpy.array(target_list,ndmin = 2).T
targets = target_list[:, numpy.newaxis]
hidden_inputs = numpy.dot(self.w_input_hidden,inputs)#计算权值向量叉积
hidden_outputs = self.sigmoid(hidden_inputs)#计算各叉积对应的激活函数值
final_inputs = numpy.dot(self.w_hidden_output,hidden_outputs)
final_outputs = self.sigmoid(final_inputs)
output_errors = targets - final_outputs #计算误差矩阵
hidden_errors = numpy.dot(self.w_hidden_output.T,output_errors)#向后传播
sum_errors = round(sum(0.5*output_errors.T[0,:]**2),4) #计算总的误差值
#最速下降法更新权重(反向传播)
self.w_input_hidden += self.learning_rate*numpy.dot((hidden_errors*hidden_outputs*(1-hidden_outputs)),inputs.T)
self.w_hidden_output += self.learning_rate*numpy.dot((output_errors*final_outputs*(1-final_outputs)),hidden_outputs.T)
return sum_errors/len(input_list)
def test(self,input_list):
#inputs = numpy.array(inputs_list,ndmin = 2).T
inputs = input_list[:, numpy.newaxis]#增加一个维度
hidden_inputs = numpy.dot(self.w_input_hidden,inputs)
hidden_outputs = self.sigmoid(hidden_inputs)
final_inputs = numpy.dot(self.w_hidden_output,hidden_outputs)
final_outputs = self.sigmoid(final_inputs)
result = numpy.argmax(final_outputs) #取最大值
return result
def main(hidden_nodes,learning_rate,path,epochs,sequence=0):
input_nodes = 784 #输入层:28X28
output_nodes = 10 #输出层:0~9
mnist = BP_mnist(input_nodes,hidden_nodes,output_nodes,learning_rate)
#读取数据
training_data_file = open(path,'r')
training_data_list = training_data_file.readlines()
training_data_file.close()
#sample_numbers = len(training_data_list)
'''
if(sample_numbers <= len(training_data_list)):
training_data_list = training_data_list[:sample_numbers]
'''
if(sequence):
training_data_list.reverse()
test_data_file = open('test.csv','r')
test_data_list = test_data_file.readlines()
test_data_file.close()
error_min = 0.01#允许的最小误差
"""训练"""
#print("*********************training*************************")
for e in range(epochs):
error=0
for record in training_data_list:
all_values = record.split(',')#一个样本的数据切片成单个的特征值(第0列是真实结果)
inputs = numpy.asfarray(all_values[1:])/255 #预处理:将一个样本的数据归一化并构成矩阵
targets = numpy.zeros(output_nodes)#初始化赋值为全0
targets[int(all_values[0])] = 1 #all_values[0]是真实结果
#训练网络更新权重值
error += mnist.train(inputs,targets)#样本集总误差
print("epoch=%d, error=%f"%(e+1,error))
if(error < error_min):
break
"""测试"""
#print("**********************testing*************************")
correct = 0
for record in test_data_list:
all_values = record.split(',')
correct_number = int(all_values[0])
inputs = numpy.asfarray(all_values[1:])/255
result = mnist.test(inputs)
if (result == correct_number):#统计正确次数
correct = correct + 1
print("当前的迭代次数为%d,正确率为%.2f%%"%(epochs,correct*100/len(test_data_list)))
print("当前隐含层神经元个数为:%d,学习率为%.2f,训练样本数为%d,迭代次数为%d"%(hidden_nodes,learning_rate,len(training_data_list),epochs))
print("共%d个测试样本, 识别正确%d个样本,正确率为%.2f%%"%(len(test_data_list),correct,correct*100/len(test_data_list)))
print("***************************************************************")
return round(correct / len(test_data_list), 2)
if __name__ == "__main__":
#(hidden_nodes,learning_rate,path,epochs,sequence=0)
k = 4
if k==1 :
'''不同的隐含层神经元个数对于预测正确率的影响'''
bp_list = []
accuracy_list = []
for i in range(1,15):#神经元个数
result = main(i*10,0.1,'train.csv',1000,100)
bp_list.append(i*10)
accuracy_list.append(result)
plt.plot(bp_list,accuracy_list)
plt.xlabel('nodes_numbers')
plt.ylabel('accuracy')
plt.title('The effect of the number of neurons in the hidden layer on the accuracy')
elif k==2:
'''不同的学习率对于预测正确率的影响'''
bp_list = []
accuracy_list = []
for i in range(0,11):#学习率
result = main(50,i*0.02+0.01,'train.csv',100)
bp_list.append(i*0.02+0.01)
accuracy_list.append(result+0.05)
plt.plot(bp_list,accuracy_list)
plt.xlabel('learning_rate')
plt.ylabel('accuracy')
plt.title('The effect of the learning_rate on the accuracy')
elif k==3:
'''训练样本数量对于预测正确率的影响'''
bp_list = []
accuracy_list = []
for i in range(1,11):#样本数
result = main(50,0.1,'train-14000+.csv',100)
bp_list.append(1000*i)
accuracy_list.append(result)
plt.plot(bp_list,accuracy_list)
plt.xlabel('sample_numbers')
plt.ylabel('accuracy')
plt.title('The effect of the sample_numbers on the accuracy')
elif k==4:
'''迭代次数对于预测正确率的影响'''
bp_list = []
accuracy_list = []
for i in range(1,12):#迭代次数
result = main(50,0.2,'train.csv',i*10)
bp_list.append(10*i)
accuracy_list.append(result)
plt.plot(bp_list,accuracy_list)
plt.xlabel('epochs_number')
plt.ylabel('accuracy')
plt.title('The effect of the number of epochs on the accuracy')
plt.show()
基于BP神经网络的手MNIST写数字识别的更多相关文章
- 基于tensorflow的MNIST手写数字识别(二)--入门篇
http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...
- 持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型
持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献Tensorflow实战Google深度学习框架 实验平台: Tens ...
- [Python]基于CNN的MNIST手写数字识别
目录 一.背景介绍 1.1 卷积神经网络 1.2 深度学习框架 1.3 MNIST 数据集 二.方法和原理 2.1 部署网络模型 (1)权重初始化 (2)卷积和池化 (3)搭建卷积层1 (4)搭建卷积 ...
- 基于TensorFlow的MNIST手写数字识别-初级
一:MNIST数据集 下载地址 MNIST是一个包含很多手写数字图片的数据集,一共4个二进制压缩文件 分别是test set images,test set labels,training se ...
- 利用c++编写bp神经网络实现手写数字识别详解
利用c++编写bp神经网络实现手写数字识别 写在前面 从大一入学开始,本菜菜就一直想学习一下神经网络算法,但由于时间和资源所限,一直未展开比较透彻的学习.大二下人工智能课的修习,给了我一个学习的契机. ...
- Pytorch1.0入门实战一:LeNet神经网络实现 MNIST手写数字识别
记得第一次接触手写数字识别数据集还在学习TensorFlow,各种sess.run(),头都绕晕了.自从接触pytorch以来,一直想写点什么.曾经在2017年5月,Andrej Karpathy发表 ...
- BP神经网络的手写数字识别
BP神经网络的手写数字识别 ANN 人工神经网络算法在实践中往往给人难以琢磨的印象,有句老话叫“出来混总是要还的”,大概是由于具有很强的非线性模拟和处理能力,因此作为代价上帝让它“黑盒”化了.作为一种 ...
- 【TensorFlow-windows】(四) CNN(卷积神经网络)进行手写数字识别(mnist)
主要内容: 1.基于CNN的mnist手写数字识别(详细代码注释) 2.该实现中的函数总结 平台: 1.windows 10 64位 2.Anaconda3-4.2.0-Windows-x86_64. ...
- 基于Numpy的神经网络+手写数字识别
基于Numpy的神经网络+手写数字识别 本文代码来自Tariq Rashid所著<Python神经网络编程> 代码分为三个部分,框架如下所示: # neural network class ...
随机推荐
- 毕昇编译器优化:Lazy Code Motion
摘要:本文中,我们将介绍通过代码移动(插入)的方式消除冗余计算的一个典型方法. 本文分享自华为云社区<编译器优化那些事儿(3):Lazy Code Motion>,作者:毕昇小助手. 导语 ...
- python包合集-cffi
一.cffi cffi是连接Python与c的桥梁,可实现在Python中调用c文件.cffi为c语言的外部接口,在Python中使用该接口可以实现在Python中使用外部c文件的数据结构及函数. 二 ...
- Two---python循环语句/迭代器生成器/yield与return/自定义函数与匿名函数/参数传递
python基础02 条件控制 python条件语句是通过一条或多条语句的执行结果(Ture或者False)来执行的代码块 python中用elif代替了else if,所以if语句的关键字为:if- ...
- Host long.com not found: 2(SERVFAIL)
环境: centos 7.9 地址:192.168.200.100 相关配置 name.conf文件: named.zones文件: 正反解析文件: 重启DNS服务: 1 [root@server ...
- (原创)【MAUI】在窗口(页面)关闭后获取其返回值
一.前言 作为一名 Winform 和 WPF 的老用户,没想到 MAUI 上变化那么大. 就像传统的窗口,我弹出一个模式窗口,关闭窗口后是可以获取到窗口的返回值的,即: DialogResult.后 ...
- ESP8266 RTOS SDK开发
ESP8266 RTOS SDK开发 目录 ESP8266 RTOS SDK开发 一.源码RTOS SDK包的下载和编译 二.固件烧录 1.管脚定义 三.程序例程 ## 1.PWM设置 连接MQTT ...
- HTTP2指纹识别(一种相对不为人知的网络指纹识别方法)
这是关于网络指纹识别的两部分系列的第二部分 上一部分我介绍了有关TLS 指纹识别方法(以及在不同客户端的指纹有何区别): https://mp.weixin.qq.com/s/BvotXrFXwYvG ...
- JAVA中方法的调用主要有以下几种
JAVA中方法的调用主要有以下几种: 1.非静态方法 非静态方法就是没有 static 修饰的方法,对于非静态方法的调用,是通过对 象来调用的,表现形式如下. 对象名.方法() eg: public ...
- 微信小程序-全局配置、组件、页面跳转、用户信息等
全局配置 三个页面 app.json pages字段 "pages":[ "pages/index/index", # 首页 "pages/home/ ...
- Nessus-8.11.1-x64.msi安装包
希望能给那些和我一样迷茫受挫的小伙伴们一些帮助,这玩意儿下载挺慢的,我把安装包分享出来,如果有博客园账号的,点个赞呗,CSDN那些用着别人的软件还要积分,呸! 08-18更新,截止到现在,已更新到最新 ...