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. 面试突击75:SpringBoot 有几种读取配置文件的方法?

    Spring Boot 中读取配置文件有以下 5 种方法: 使用 @Value 读取配置文件. 使用 @ConfigurationProperties 读取配置文件. 使用 Environment 读 ...

  2. Dart 异步编程(二):async/await

    对每一个异步任务返回的 Future 对象都使用链式操作-- then ,超过三个以上时,导致"倒三角"现象,降低代码的可阅读性. getHobbies() { post('htt ...

  3. 基于Go语言的xmind读写库,我主要用来把有道云笔记思维导图转为xmind

    项目地址 xmind 基于go语言的xmind接口 使用方法参考: example 本库主要加载xmind文件为json结构,保存文件时也用的json结构而不是xml结构 本库只做了最基本的主题添加功 ...

  4. JS的简介

    JS式JavaScript的简称,它是一门弱语言,它可以实现让网页动起来 JS的构成 核心(ECMAScript) 文档对象模型(DOM)-- Document Object  Module 浏览器对 ...

  5. Linux有趣命令

    通外网 下载使用阿里云镜像源:wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.re ...

  6. KingbaseES的SQL语句-CTE递归

    背景 从上下级关系表中,任意一个节点数据出发,可以获得该节点的上级或下级.CTE的递归语法,或者 connect by 与 start with的 查询语法,能够实现这个需求. 当我们需要制作上下级关 ...

  7. .NET 纯原生实现 Cron 定时任务执行,未依赖第三方组件 (Timer 优化版)

    在上个月写过一篇 .NET 纯原生实现 Cron 定时任务执行,未依赖第三方组件 的文章,当时 CronSchedule 的实现是使用了,每个服务都独立进入到一个 while 循环中,进行定期扫描是否 ...

  8. 怎么用vscode创建工程

    以下内容为本人的学习笔记,如需要转载,请声明原文链接微信公众号「englyf」https://www.cnblogs.com/englyf/p/16685082.html vs code创建工程,以k ...

  9. Java安全之Velocity模版注入

    Java安全之Velocity模版注入 Apache Velocity Apache Velocity是一个基于Java的模板引擎,它提供了一个模板语言去引用由Java代码定义的对象.它允许web 页 ...

  10. 举例:Network Policies

    本文描述了如何在 Kubernetes 集群中通过创建 NetworkPolicy 的方式来声明网络策略,以管理 Pod 之间的网络通信流量. 前提条件 创建一个Deployment并配置Servic ...