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

本文代码来自Tariq Rashid所著《Python神经网络编程》

代码分为三个部分,框架如下所示:

# neural network class definition
class neuralNetwork: # initialise the neural network
def __init__():
pass # train the neural network
def train():
pass # query the neural network
def query():
pass

这是一个坚实的框架,可以在这个框架之上,充实神经网络工作的详细细节。

import numpy as np
import scipy.special
import matplotlib.pyplot as plt #neural network class definition
class neuralNetwork : #initialise the neural network
def __init__(self, inputNodes, hiddenNodes, outputNodes, learningrate) :
#set number of nodes in each input, hidden, output layer
self.inodes = inputNodes
self.hnodes = hiddenNodes
self.onodes = outputNodes #learning rate
self.lr = learningrate #link weight matrices, wih and who
self.wih = np.random.normal(0.0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes))
self.who = np.random.normal(0.0, pow(self.onodes, -0.5), (self.onodes, self.hnodes)) #activation function is the sigmoid function
self.activation_function = lambda x : scipy.special.expit(x)
pass # train the neural network
def train(self, inputs_list, targets_list):
#convert inputs_list, targets_list to 2d array
inputs = np.array(inputs_list, ndmin=2).T
targets = np.array(targets_list, ndmin=2).T #calculate signals into hidden layer
hidden_inputs = np.dot(self.wih, inputs)
#calculate the signals emerging from hidden layer
hidden_outputs = self.activation_function(hidden_inputs) #calculate signals into final output layer
final_inputs = np.dot(self.who, hidden_outputs)
#calculate the signals emerging from final output layer
final_outputs = self.activation_function(final_inputs) #output layer error is the (target-actual)
output_errors = targets - final_outputs
#hidden layer error is the output_errors, split by weights, recombined at hidden nodes
hidden_errors = np.dot(self.who.T, output_errors) #update the weights for the links between the hidden and output layers
self.who += self.lr * np.dot((output_errors * final_outputs * (1.0 - final_outputs)), np.transpose(hidden_outputs))
#update the weights for the links between the input and hidden layers
self.wih += self.lr * np.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), np.transpose(inputs)) pass # query the neural network
def query(self, inputs_list):
#convert inputs_list to 2d array
inputs = np.array(inputs_list, ndmin=2).T #calculate signals into hidden layer
hidden_inputs = np.dot(self.wih, inputs)
#calculate the signals emerging from hidden layer
hidden_outputs = self.activation_function(hidden_inputs) #calculate signals into final output layer
final_inputs = np.dot(self.who, hidden_outputs)
#calculate the signals emerging from final output layer
final_outputs = self.activation_function(final_inputs) return final_outputs pass

使用以上定义的神经网络类:

#number of input,hidden and output nodes
input_nodes = 784
hidden_nodes = 200
output_nodes = 10 #learning rate is 0.1
learning_rate = 0.1 #create instance of neural network
n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate) #load the minist training data CSV file into a list
training_data_file = open("mnist_dataset/mnist_train.csv", "r")
training_data_list = training_data_file.readlines()
training_data_file.close() #train the neural network #epochs is the number of times the training data set is used for training
epochs = 5 for e in range(epochs):
#go through all records in the training data set
for record in training_data_list:
#split the record by the "," commas
all_values = record.split(",")
#scale and shift the inputs
inputs = (np.asfarray(all_values[1:])/255.0*0.99) + 0.01
#create the target output values (all 0.01, except the desired label which is 0.99)
targets = np.zeros(output_nodes) + 0.01
#all_values[0] is the target label for this record
targets[int(all_values[0])] = 0.99
n.train(inputs, targets)
pass
pass #load the minist test data CSV file into a list
test_data_file = open("mnist_dataset/mnist_test.csv", 'r')
test_data_list = test_data_file.readlines()
test_data_file.close() #test the neural network
#scorecard for how well the network performs, initially empty
scorecard = [] #go through all the records in the test data set
for record in test_data_list:
#split the record by the ',' commas
all_values = record.split(',')
#correct answer is the first value
correct_label = int(all_values[0])
#scale and shift the inputs
inputs = (np.asfarray(all_values[1:])/255.0*0.99) + 0.01
#query the network
outputs = n.query(inputs)
#the index of the highest value corresponds to the label
label = np.argmax(outputs)
#append correct or incorrect to list
if(label == correct_label):
#network's answer matches correct answer, add 1 to scorecard
scorecard.append(1)
else:
#network's answer doesn't matche correct answer, add 0 to scorecard
scorecard.append(0)
pass pass #calculate the performance score, the fraction of correct answers
scorecard_array = np.asarray(scorecard)
print("performance = ", scorecard_array.sum()/scorecard_array.size)

以上训练中所用到的数据集:

训练集

测试集

基于Numpy的神经网络+手写数字识别的更多相关文章

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

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

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

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

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

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

  4. TensorFlow 卷积神经网络手写数字识别数据集介绍

    欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 手写数字识别 接下来将会以 MNIST 数据集为例,使用卷积层和池 ...

  5. 深度学习-使用cuda加速卷积神经网络-手写数字识别准确率99.7%

    源码和运行结果 cuda:https://github.com/zhxfl/CUDA-CNN C语言版本参考自:http://eric-yuan.me/ 针对著名手写数字识别的库mnist,准确率是9 ...

  6. 神经网络手写数字识别numpy实现

    本文摘自Michael Nielsen的Neural Network and Deep Learning,该书的github网址为:https://github.com/mnielsen/neural ...

  7. 深度学习(一):Python神经网络——手写数字识别

    声明:本文章为阅读书籍<Python神经网络编程>而来,代码与书中略有差异,书籍封面: 源码 若要本地运行,请更改源码中图片与数据集的位置,环境为 Python3.6x. 1 import ...

  8. 基于多层感知机的手写数字识别(Tensorflow实现)

    import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_dat ...

  9. 基于TensorFlow的MNIST手写数字识别-深入

    构建多层卷积神经网络时需要多组W和偏移项b,我们封装2个方法来产生W和b 初级MNIST中用0初始化W和b,这里用噪声初始化进行对称打破,防止产生梯度0,同时用一个小的正值来初始化b避免dead ne ...

随机推荐

  1. JavaScript学习---简易图片轮播

    效果如下: 图片定时轮播 点击左右控制显示下一张或上一张图片 index.html文件 <html> <head> <title> js编写实现幻灯片效果 < ...

  2. 跨域请求Ajax(POST)处理方法

    getXSSAjax(function() {  //跨域请求        that.ajaxDara(self);}, (bs_tita.webapi || "http://webapi ...

  3. 使用URL Rewrite实现网站伪静态

    下载urlwrite包 将urlrewrite-***.jar复制到web应用lib文件夹下 web.xml中配置URL Rewrite: 例: <filter> <filter-n ...

  4. 信息收集工具recon-ng详细使用教程

    前言: 最近在找Recon-ng详细一点的教程,可是Google才发现资料都很零散而且不详细,所以我打算具体写一下.Recon-ng在渗透过程中主要扮演信息收集工作的角色,同时也可以当作渗透工具,不过 ...

  5. IOS开发UI篇--一个支持图文混排的ActionSheet

    一.简单介绍 UIActionSheet是IOS提供给我们开发人员的底部弹出菜单控件.一般用于菜单选择.操作确认.删除确认等功能.IOS官方提供的下面方式对UIActionView进行实例化: - ( ...

  6. 菜鸟运维笔记:安装与配置Apacheserver

    前几天在在阿里花了49.5买了一个月的主机. 试着好用再续费吧. 地域:青岛 可用区:青岛可用区A CPU:1核 内存:512MB 带宽:1Mbps 操作系统:CentOS 6.5 64位 云盾:是 ...

  7. boost::mpl::eval_if的使用方法

    近期看boost的时候总是遇见这个eval_if,不知道啥意思,就没法看下去了,比方 前篇文章boost::serialization 拆分serialize函数分析时就出现这样一段代码: templ ...

  8. Justinmind使用教程(2)——计算表达式及条件用法

    Justinmind的计算表达式以及条件condition的使用对于刚開始学习的人而言比較麻烦. 结合网上了一个教程本文主要针对计算器演示样例进行计算表达式以及条件的使用. 实现目标:依据单位价格(静 ...

  9. 省市县三级联动js代码

    省市县三级联动菜单,JS全国省市县(区)联动代码,一般可以用于用户注册或分类信息二手交易网站,需要的朋友直接复制代码就可以用了,不过有朋友反馈说缺少某些城市,具体缺少哪个尚不知,请想用的朋友自己补全吧 ...

  10. (六)Net Core项目使用Controller之一 c# log4net 不输出日志 .NET Standard库引用导致的FileNotFoundException探究 获取json串里的某个属性值 common.js 如何调用common.js js 筛选数据 Join 具体用法

    (六)Net Core项目使用Controller之一 一.简介 1.当前最流行的开发模式是前后端分离,Controller作为后端的核心输出,是开发人员使用最多的技术点. 2.个人所在的团队已经选择 ...