代码编辑&解释工具:Jupyter Notebook 快速入门

形象说明BP神经网络的用法(图片来自推特):

Bpnn类最主要的三个方法:

  1. initialize方法,用于设定神经网络的层数、各层节点数
  2. predict方法,方便用户应用模型做预测
  3. train方法,用来训练模型

所有代码如下(需要导入numpy模块):

import numpy as np
import mathdef linear_transformation(matrix, vector):return vector.dot(matrix)# vector = np.array([1, 2])
# matrix = [[1, 2], [3, 4]]
# vector = linear_transformation(matrix, vector)
# print("linear_transformation:", vector)
# print("linear_transformation:", type(vector))def active(vector, f):return np.array(list(map(lambda x: f(x), vector)))def sigmoid(x): # 激活函数return 1.0 / (1.0 + math.exp(-x))# result = active(vector, sigmoid)
# print("active:", result)
# print("active:", type(result))class Bpnn:# model是一个list,例如[2, 2, 3, 1]表示输入结点2个,第一个隐含层有2个节点,第二个隐含层有3个节点,输出结点1个def initialize(self, model):# 随机生成模型对应的矩阵(网络权重)和偏置self.matrixs = []self.biases = []for i in range(len(model) - 1): # 矩阵个数为总层数减1,例如4层的网络只需要3个矩阵就可以了           self.matrixs.append(np.random.randn(model[i], model[i + 1])) # 矩阵的列数是对应输入节点的个数,矩阵的行数对应输出节点的个数for i in range(len(model) - 1):# 列表中的每个np数组代表一整层节点的偏置self.biases.append(np.random.randn(model[i + 1]))def predict(self, vector):result = np.array(vector)for i in range(len(self.matrixs)): # 其实就是对一个向量做多次线性变换result = linear_transformation(self.matrixs[i], result) + self.biases[i]result = active(result, sigmoid)return resultdef neural_net_output(self, feature): # 记录各层的输出result = []output = active(linear_transformation(self.matrixs[0], np.array(feature)) + self.biases[0], sigmoid)result.append(output)for i in range(len(self.matrixs) - 1):output = active(linear_transformation(self.matrixs[i + 1], output) + self.biases[i + 1], sigmoid)result.append(output)return result # 格式为[[代表第1层输出的向量], [代表第2层输出的向量], ...,[代表最终输出的向量]],所有向量都是一维的np.array,向量长度为该层节点数def compute_error(self, prediction, actual): # 计算各层的误差,actual是样本标记值(期望获得的值)result = []prediction = prediction[:] # 后面的处理都不影响原始数组prediction.reverse() # 转置便于处理error = prediction[0] * (1 - prediction[0]) * (actual - prediction[0]) # 计算最终输出的误差
        result.append(error)for i in range(len(self.matrixs) - 1): # 计算每层的误差,可以通过转置矩阵计算上一层误差的一个因子error = prediction[i + 1] * (1- prediction[i + 1]) * linear_transformation(self.matrixs[-1 - i].T, error) result.append(error)result.reverse()return result # 格式为[[代表第1层输出误差的向量], [代表第2层输出误差的向量], ...,[代表最终输出误差的向量]],所有向量都是一维的np.array,向量长度为该层节点数数def update_network(self, feature, prediction, error, LEARING_RATE):# 更新权重(手算凑出来的计算方法↓)temp = np.ones_like(self.matrixs[0]) temp = temp * LEARING_RATE * error[0]temp = temp.T * np.array(feature)temp = temp.Tself.matrixs[0] += temp;for i in range(len(self.matrixs) - 1):temp = np.ones_like(self.matrixs[i + 1]) temp = temp * LEARING_RATE * error[i + 1]temp = temp.T * prediction[i]temp = temp.Tself.matrixs[i + 1] += temp;            # 更新偏置for i in range(len(self.biases)):self.biases[i] += LEARING_RATE * error[i]def train(self, get_batch, MAX_ITERATION, LEARING_RATE, MAX_LOSS):loss = MAX_LOSS = abs(MAX_LOSS)count = MAX_ITERATIONwhile abs(loss) >= MAX_LOSS and count > 0:batch = get_batch()for example in batch:prediction = self.neural_net_output(example.feature)error = self.compute_error(prediction, example.label)self.update_network(example.feature, prediction, error, LEARING_RATE)loss = abs(np.mean(error[-1])) # 取最后一次迭代最终输出的平均值作为本批次的误差count = count - 1print("迭代次数:", MAX_ITERATION - count)print("误差:", loss)class LabeledExample:def __init__(self, feature, label):self.feature = featureself.label = label# 训练一个类似于异或(xor)运算的函数,相同为假,相异为真
labeled_examples = [LabeledExample([0, 0], [0]), LabeledExample([0, 1], [1]), LabeledExample([1, 0], [1]), LabeledExample([1, 1], [0])]def full_batch():return labeled_examplesbpnn = Bpnn()
bpnn.initialize([2, 2, 1]) # 构造一个三层的神经网络,输入节点2个,隐含层节点2个,输出节点1个
bpnn.train(full_batch, 10000, 0.6, 0.01) # 学习因子为0.6, 最大允许误差0.01
print("输入层与隐含层权值", bpnn.matrixs[0])
print("隐含层权值与输出层权值", bpnn.matrixs[1])
print("隐含层阈值", bpnn.biases[0])
print("输出层阈值", bpnn.biases[1])
sample1 = [0.05, 0.1]
sample2 = [0.2, 0.9]
sample3 = [0.86, 0.95]
print("预测样本", sample1, "的结果是:", bpnn.predict(sample1))
print("预测样本", sample2, "的结果是:", bpnn.predict(sample2))
print("预测样本", sample3, "的结果是:", bpnn.predict(sample3))

转载于:https://www.cnblogs.com/xkxf/p/9675935.html

Python笔记 #19# 实现bpnn相关推荐

  1. Python学习笔记19:列表 III

    Python学习笔记19:列表 III 其实这篇笔记标题应该是列表扩展,从列表开始,将涵盖Python中的序列容器. 关于列表的基础知识,可以看我的前两篇文章: Python学习笔记1:列表. Pyt ...

  2. python视窗编程_[PYTHON] 核心编程笔记(19.图形用户界面编程)

    19.1 简介 19.1.1 什么是Tcl,Tk和Tkinter? 19.1.2 安装和使用Tkinter # apt-get install python-tk -y # python ------ ...

  3. python了解一下_想要精通python?19个语法了解一下!

    原标题:想要精通python?19个语法了解一下! Python简单易学,但又博大精深.许多人号称精通Python,却不会写Pythonic的代码,对很多常用包的使用也并不熟悉.学海无涯,我们先来了解 ...

  4. python笔记-1(import导入、time/datetime/random/os/sys模块)

    python笔记-6(import导入.time/datetime/random/os/sys模块) 一.了解模块导入的基本知识 此部分此处不展开细说import导入,仅写几个点目前的认知即可.其它内 ...

  5. Python笔记(4) 关键字

    Python笔记(4) 关键字 1. 关键字 2. True与False 3. None 4. and,or与not 5. assert 6. await与async 7. for/while,con ...

  6. 初学者python笔记(内置函数_2)

    这篇初学者笔记是接着上一篇初学者python笔记(内置函数_1)的.同样都是介绍Python中那些常用内置函数的. max()和min()的高级用法 我们都知道,max():取最大值,min():取最 ...

  7. 初学者python笔记(map()函数、reduce()函数、filter()函数、匿名函数)

    文章目录 一.匿名函数 二.map()函数 三.reduce()函数 四.filter()函数 五.三大函数总结 本篇文章内容有Python中的匿名函数和map()函数.reduce()函数.filt ...

  8. 初学者python笔记(列表的食用方法)

    本篇是关于可迭代对象中的列表一些相关使用方法的记录. 可迭代对象简单描述:可以被for循环执行的对象(字符串,列表,元组,字典-) input()方法接收的其实只是字符串 a = input(&quo ...

  9. 菜鸡自学 Python 笔记(二)

    菜鸡自学 Python 笔记(二) 五,结构与语句 1.选择结构-- if 语句 2.循环控制语句 (1)while 语句 (2)for 语句 (3)continue 语句与break 语句 六.列表 ...

  10. Python笔记(1-20)

    Python笔记(1-20) 习题等资源来源于网络,本人只是在此收集整理,如有版权问题,归小甲鱼所属.小甲鱼:https://ilovefishc.com/ 第 1 课 1.Python 是什么类型的 ...

最新文章

  1. 直播 | Python Web开发者的破局之道
  2. Flutter 调用地图软件(高德、百度、腾讯、苹果)同时实现另类国际化
  3. php用mssql还是用pdo,php使用pdo连接mssql server数据库实例
  4. 数据结构与算法--翻转单词顺序
  5. 不错的流量卡官网html源码
  6. php7 空对象,PHP设计模式之空对象模式(Null Object)代码实例大全(26)
  7. 【Java】反转数组元素
  8. Linux卸载jdk
  9. 设计模式之——桥接模式
  10. 计算机专业毕设外文翻译springboot_计算机毕业设计之SpringBoot物流管理系统
  11. 教孩子学编程python语言pdf_教孩子学编程 PYTHON语言版 PDF 下载
  12. apr内存池简单应用
  13. 怎么获取计算机的最高权限,获取win8 64位旗舰版系统最高权限的方法【图文详解】...
  14. 苹果6s照相快门声音设置_苹果手机配件常见故障及维修注意事项
  15. 网上FLAC3D学习笔记
  16. 计算机进制算法在线,二进制转十进制和十六进制在线计算器
  17. 基本不等式凸函数拉格朗日乘子
  18. HTML:使用单选框、复选框,让用户选择
  19. 微软欲模仿“微信”,打造一款超级 App?
  20. c语言求偶数的积,动物行为学1

热门文章

  1. 在linux 命令行下从http下载东西
  2. SSM框架整合思想及步骤
  3. win10系统字体 chrome 修改苹果字体
  4. SRCNN-pytoch代码讲解
  5. java文件gzip解压_如何在Java中解压缩GZip文件?
  6. APP上架市场隐私政策被拒(关于未经用户同意收集用户信息)
  7. HBuilderX日常踩坑之隐私合规检测
  8. 深度学习面试题:计算机视觉训练技巧
  9. Android全局设置APP为黑白模式的两种方案
  10. C语言编程齿轮轮廓线坐标,c语言程序实现齿轮基本参数几何尺寸计算.pdf