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写数字识别的更多相关文章

  1. 基于tensorflow的MNIST手写数字识别(二)--入门篇

    http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...

  2. 持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型

    持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献Tensorflow实战Google深度学习框架 实验平台: Tens ...

  3. [Python]基于CNN的MNIST手写数字识别

    目录 一.背景介绍 1.1 卷积神经网络 1.2 深度学习框架 1.3 MNIST 数据集 二.方法和原理 2.1 部署网络模型 (1)权重初始化 (2)卷积和池化 (3)搭建卷积层1 (4)搭建卷积 ...

  4. 基于TensorFlow的MNIST手写数字识别-初级

    一:MNIST数据集    下载地址 MNIST是一个包含很多手写数字图片的数据集,一共4个二进制压缩文件 分别是test set images,test set labels,training se ...

  5. 利用c++编写bp神经网络实现手写数字识别详解

    利用c++编写bp神经网络实现手写数字识别 写在前面 从大一入学开始,本菜菜就一直想学习一下神经网络算法,但由于时间和资源所限,一直未展开比较透彻的学习.大二下人工智能课的修习,给了我一个学习的契机. ...

  6. Pytorch1.0入门实战一:LeNet神经网络实现 MNIST手写数字识别

    记得第一次接触手写数字识别数据集还在学习TensorFlow,各种sess.run(),头都绕晕了.自从接触pytorch以来,一直想写点什么.曾经在2017年5月,Andrej Karpathy发表 ...

  7. BP神经网络的手写数字识别

    BP神经网络的手写数字识别 ANN 人工神经网络算法在实践中往往给人难以琢磨的印象,有句老话叫“出来混总是要还的”,大概是由于具有很强的非线性模拟和处理能力,因此作为代价上帝让它“黑盒”化了.作为一种 ...

  8. 【TensorFlow-windows】(四) CNN(卷积神经网络)进行手写数字识别(mnist)

    主要内容: 1.基于CNN的mnist手写数字识别(详细代码注释) 2.该实现中的函数总结 平台: 1.windows 10 64位 2.Anaconda3-4.2.0-Windows-x86_64. ...

  9. 基于Numpy的神经网络+手写数字识别

    基于Numpy的神经网络+手写数字识别 本文代码来自Tariq Rashid所著<Python神经网络编程> 代码分为三个部分,框架如下所示: # neural network class ...

随机推荐

  1. benchmark性能测试

    目录 benchmark介绍 benchmark运行 benchmark运行参数 benchmark性能测试案例 benchmark介绍 基准测试主要是通过测试CPU和内存的效率问题,来评估被测试代码 ...

  2. 羽夏看Linux内核——引导启动(下)

    写在前面   此系列是本人一个字一个字码出来的,包括示例和实验截图.如有好的建议,欢迎反馈.码字不易,如果本篇文章有帮助你的,如有闲钱,可以打赏支持我的创作.如想转载,请把我的转载信息附在文章后面,并 ...

  3. Spring源码 05 IOC 注解方式

    参考源 https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click https://ww ...

  4. Express 项目,res.cookie() 设置 Cookie 无法被保存在浏览器的 Application 中

    res.cookie() 给客户端响应头封装的 Cookie 无法被保存在客户端浏览器的 Application 中,只能在 Set-Cookie 中看到有这个值: 在前后端分离项目中,存在跨域问题, ...

  5. 什么是云计算?云计算三种模式Sass、Paas、Iaas

    云计算 云计算的"云"指的是计算机网络(一般指的是 Internet),"计算"指的是多个计算机共同计算巨大的数据的过程.通过云计算平台把任务分解成一个个小的任 ...

  6. 造数字(数位DP)

    题面 JZM 想要创造两个数字 x 和 y,它们需要满足 x or y = T,且Lx ≤ x ≤ Rx, Ly ≤ y ≤ Ry,JZM 想知道 x and y 有多少种可能的不同的取值.若有多组 ...

  7. java方法---定义,调用

    定义,调用 1.方法的定义 方法就是一段用来完成特定功能的代码片段,类似于其它语言的函数. 方法用于定义该类或该类的实例的行为特征和功能实现.方法是类和对象行为特征的抽象. 方法很类似于面向过程中的函 ...

  8. ABAQUS和UG许可证冲突问题的解决方案

    前段时间重新安装了ABAQUS,更新到了2020版本后,发现NX UG怎么突然打不开了,搜索一下,发现是两个许可证有冲突.找了很多解决方案,主要归纳为以下两种: 方法一:Lmtools修改法 先说结论 ...

  9. [WPF] 使用 HandyControl 的 CirclePanel 画出表盘刻度

    1. 前言 最近需要一个 WPF 的表盘控件,之前 Cyril-hcj 写过一篇不错的博客 <WPF在圆上画出刻度线>,里面介绍了一些原理及详细实现的代码: double radius = ...

  10. const修饰符总结

    1.什么是const? const就是constant的缩写,意思是"恒定不变的",它是定义只读变量的关键字,或者说const是定义常变量的关键字,常类型的变量或对象的值是不能被更 ...