python的神经网络编程_Python神经网络编程 第二章 使用Python进行DIY
使用神经网络识别手写数字:
import numpy
# scipy.special for the sigmoid function expit(),即S函数
import scipy.special
# library for plotting arrays
import matplotlib.pyplot
# ensure the plots are inside this notebook, not an external window
%matplotlib inline // 在notebook上绘图,而不是独立窗口
# 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
# link weight matrices, wih and who
# weights inside the arrays are w_i_j, where link is from node i to node j in the next layer
# w11 w21
# w12 w22 etc
# numpy.random.normal(loc,scale,size) loc:概率分布的均值;scale:概率分布的方差;size:输出的shape
self.wih = numpy.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes, self.inodes))
self.who = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.onodes, self.hnodes))
# learning rate
self.lr = learningrate
# activation function is the sigmoid function
# 使用lambda创建的函数是没有名字的
self.activation_function = lambda x: scipy.special.expit(x)
pass
# train the neural network
def train(self, inputs_list, targets_list):
# convert inputs list to 2d array
inputs = numpy.array(inputs_list, ndmin=2).T
targets = numpy.array(targets_list, ndmin=2).T
# calculate signals into hidden layer
hidden_inputs = numpy.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 = numpy.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 = numpy.dot(self.who.T, output_errors)
# update the weights for the links between the hidden and output layers
self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs))
# update the weights for the links between the input and hidden layers
self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs))
pass
# query the neural network
def query(self, inputs_list):
# convert inputs list to 2d array
inputs = numpy.array(inputs_list, ndmin=2).T
# calculate signals into hidden layer
hidden_inputs = numpy.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 = numpy.dot(self.who, hidden_outputs)
# calculate the signals emerging from final output layer
final_outputs = self.activation_function(final_inputs)
return final_outputs
# number of input, hidden and output nodes
# 选择784个输入节点是28*28的结果,即组成手写数字图像的像素个数
input_nodes = 784
# 选择使用100个隐藏层不是通过使用科学的方法得到的。通过选择使用比输入节点的数量小的值,强制网络尝试总结输入的主要特点。
# 但是,如果选择太少的隐藏层节点,会限制网络的能力,使网络难以找到足够的特征或模式。
# 同时,还要考虑到输出层节点数10。
# 这里应该强调一点。对于一个问题,应该选择多少个隐藏层节点,并不存在一个最佳方法。同时,我们也没有最佳方法选择需要几层隐藏层。
# 就目前而言,最好的办法是进行实验,直到找到适合你要解决的问题的一个数字。
hidden_nodes = 200
output_nodes = 10
# learning rate,需要多次尝试,0.2是最佳值
learning_rate = 0.1
# create instance of neural network
n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)
# load the mnist 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
# 就像调整学习率一样,需要使用几个不同的世代进行实验并绘图,以可视化这些效果。直觉告诉我们,所做的训练越多,所得到的的性能越好。
# 但太多的训练实际上会过犹不及,这是由于网络过度拟合训练数据。
# 在大约5或7个世代时,有一个甜蜜点。在此之后,性能会下降,这可能是过度拟合的效果。
# 性能在6个世代的情况下下降,这可能是运行中出了问题,导致网络在梯度下降过程中被卡在了一个局部的最小值中。
# 事实上,由于没有对每个数据点进行多次实验,无法减小随机过程的影响。
# 神经网络的学习过程其核心是随机过程,有时候工作得不错,有时候很糟。
# 另一个可能的原因是,在较大数目的世代情况下,学习率可能设置过高了。在更多世代的情况下,减小学习率确实能够得到更好的性能。
# 如果打算使用更长的时间(多个世代)探索梯度下降,那么可以采用较短的步长(学习率),总体上可以找到更好的路径。
# 要正确、科学地选择这些参数,必须为每个学习率和世代组合进行多次实验,尽量减少在梯度下降过程中随机性的影响。
# 还可尝试不同的隐藏层节点数量,不同的激活函数。
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
# 输入值需要避免0,输出值需要避免1
inputs = (numpy.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 = numpy.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 mnist 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 first value
correct_label = int(all_values[0])
# scale and shift the inputs
inputs = (numpy.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 = numpy.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 match correct answer, add 0 to scorecard
scorecard.append(0)
pass
pass
# calculate the performance score, the fraction of correct answers
scorecard_array = numpy.asarray(scorecard)
print ("performance = ", scorecard_array.sum() / scorecard_array.size)
# performance = 0.9712
python的神经网络编程_Python神经网络编程 第二章 使用Python进行DIY相关推荐
- 流浪的python博客园_python学习心得第二章
python基础 1.关于python编码的问题. python的编码现在主要是两种版本python2.7和python3.5 python2.7默认的是ascii码进行编译,我们可以采用 # -*- ...
- python神经网络分析案例_python神经网络实战
机器学习实战笔记(Python实现)-04-Logistic回归 转自:机器学习实战笔记(Python实现)-04-Logistic回归 转自:简单多元线性回归(梯度下降算法与矩阵法) 转自:人工神经 ...
- python 网络编程_Python网络编程(原书第2版)
Python网络编程(原书第2版) 作者:(美)埃里克·周(Eric Chou) 著 出版日期:2019年06月 文件大小:54.50M 支持设备: ¥68.00 适用客户端: 言商书局 iPad/i ...
- 《Java语言程序设计与数据结构》编程练习答案(第二章)(二)
<Java语言程序设计与数据结构>编程练习答案(第二章)(二) 英文名:Introduction to Java Programming and Data Structures, Comp ...
- python concat去除重复值语句_Python数据处理从零开始----第二章(pandas)④数据合并和处理重复值...
目录 第二章(pandas) Python数据处理从零开始----第二章(pandas)④数据合并和处理重复值 ============================================ ...
- Python基础——第二章:Python基础语法
前言 本文是根据黑马程序员Python教程所作之笔记,目的是为了方便我本人以及广大同学们查漏补缺. 不想做笔记直接来我的频道.当然啦,自己的笔记才是最好的哦! PS:感谢黑马程序员! 教程链接:黑马程 ...
- 黑帽python第二版(Black Hat Python 2nd Edition)读书笔记 之 第一章 配置python环境
黑帽python第二版(Black Hat Python 2nd Edition)读书笔记 之 第一章 配置python环境 文章目录 黑帽python第二版(Black Hat Python 2nd ...
- python 神经网络工具_python神经网络工具箱
盘点·GitHub最著名的20个Python机器学习项目 我们分析了GitHub上的前20名Python机器学习项目,发现scikit-Learn,PyLearn2和NuPic是贡献最积极的项目.让我 ...
- 《Python核心编程》第二版第36页第二章练习 -Python核心编程答案-自己做的-
<Python核心编程>第二版第36页第二章练习 这里列出的答案不是来自官方资源,是我自己做的练习,可能有误. 2.21 练习 2-1. 变量,print和字符串格式化操作符.启动交互式解 ...
- python树莓派编程_python树莓派编程
广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 例如,你可以用树莓派搭建你自己的家用云存储服务器.? 树莓派用python来进行 ...
最新文章
- Python远程连接服务器
- AI一分钟 | 谷歌或发布Home Hub;特斯拉数周内五名高管离职
- reactor与proactor模式
- tomcat 域名的配置
- tensorflow-RNN和LSTM
- [转]【Linux】一幅图秒懂LoadAverage(负载)
- 切割钢板计算机软件,板材切割优化软件钢板开料套料软件 V1.0 官方版
- Visio2016安装
- 写一份竞品分析文档的思路(模板)
- excel中折线图怎样设置成箭头处没刻度线?
- Termux基础教程(无编程基础动图展示版)
- 职场礼仪之西装十大禁忌
- 一个双非计算机学生的长远规划(考研篇)
- shopee上架接口java_Shopee虾皮店小秘ERP刊登发布产品图文教程
- python练习——恺撒密码 I
- Java 8 Stream 总结
- python 面向对象 继承之 supper 函数
- 项目组合管理(PPM)
- 40 张图带你搞懂 TCP 和 UDP,android软件开发教程
- 微信小程序 java农产品商城供销系统#计算机毕业设计
热门文章
- 剑指Offer - 面试题36. 二叉搜索树与双向链表(中序循环/递归)
- 从零开始,手把手交给你vue如何新建一个项目
- python中的集合set
- python面向对象中的类
- java非必填字段跳过校验,avalon2表单验证,非必填字段在不填写的时候不能通过验证...
- EdgeBERT:极限压缩,比ALBERT再轻13倍!树莓派上跑BERT的日子要来了?
- Spring Cloud实战小贴士:turbine如何聚合设置了context-path的hystrix数据
- 我对Spring的理解
- 玩转算法第七章-二叉树与递归
- 论文学习14-End-to-End Relation Extraction using LSTMs on Sequences and Tree Structures(端到端实体关系抽取)