基于python的BP神经网络及异或实现过程解析


Posted in Python onSeptember 30, 2019

BP神经网络是最简单的神经网络模型了,三层能够模拟非线性函数效果。

基于python的BP神经网络及异或实现过程解析

难点:

  • 如何确定初始化参数?
  • 如何确定隐含层节点数量?
  • 迭代多少次?如何更快收敛?
  • 如何获得全局最优解?
'''
neural networks 

created on 2019.9.24
author: vince
'''
import math
import logging
import numpy 
import random
import matplotlib.pyplot as plt

'''
neural network 
'''
class NeuralNetwork:

 def __init__(self, layer_nums, iter_num = 10000, batch_size = 1):
  self.__ILI = 0;
  self.__HLI = 1;
  self.__OLI = 2;
  self.__TLN = 3;

  if len(layer_nums) != self.__TLN:
   raise Exception("layer_nums length must be 3");

  self.__layer_nums = layer_nums; #array [layer0_num, layer1_num ...layerN_num]
  self.__iter_num = iter_num;
  self.__batch_size = batch_size;
 
 def train(self, X, Y):
  X = numpy.array(X);
  Y = numpy.array(Y);

  self.L = [];
  #initialize parameters
  self.__weight = [];
  self.__bias = [];
  self.__step_len = [];
  for layer_index in range(1, self.__TLN):
   self.__weight.append(numpy.random.rand(self.__layer_nums[layer_index - 1], self.__layer_nums[layer_index]) * 2 - 1.0);
   self.__bias.append(numpy.random.rand(self.__layer_nums[layer_index]) * 2 - 1.0);
   self.__step_len.append(0.3);

  logging.info("bias:%s" % (self.__bias));
  logging.info("weight:%s" % (self.__weight));

  for iter_index in range(self.__iter_num):
   sample_index = random.randint(0, len(X) - 1);
   logging.debug("-----round:%s, select sample %s-----" % (iter_index, sample_index));
   output = self.forward_pass(X[sample_index]);
   g = (-output[2] + Y[sample_index]) * self.activation_drive(output[2]);
   logging.debug("g:%s" % (g));
   for j in range(len(output[1])):
    self.__weight[1][j] += self.__step_len[1] * g * output[1][j];
   self.__bias[1] -= self.__step_len[1] * g;

   e = [];
   for i in range(self.__layer_nums[self.__HLI]):
    e.append(numpy.dot(g, self.__weight[1][i]) * self.activation_drive(output[1][i]));
   e = numpy.array(e);
   logging.debug("e:%s" % (e));
   for j in range(len(output[0])):
    self.__weight[0][j] += self.__step_len[0] * e * output[0][j];
   self.__bias[0] -= self.__step_len[0] * e;

   l = 0;
   for i in range(len(X)):
    predictions = self.forward_pass(X[i])[2];
    l += 0.5 * numpy.sum((predictions - Y[i]) ** 2);
   l /= len(X);
   self.L.append(l);

   logging.debug("bias:%s" % (self.__bias));
   logging.debug("weight:%s" % (self.__weight));
   logging.debug("loss:%s" % (l));
  logging.info("bias:%s" % (self.__bias));
  logging.info("weight:%s" % (self.__weight));
  logging.info("L:%s" % (self.L));
 
 def activation(self, z):
  return (1.0 / (1.0 + numpy.exp(-z)));

 def activation_drive(self, y):
  return y * (1.0 - y);

 def forward_pass(self, x):
  data = numpy.copy(x);
  result = [];
  result.append(data);
  for layer_index in range(self.__TLN - 1):
   data = self.activation(numpy.dot(data, self.__weight[layer_index]) - self.__bias[layer_index]);
   result.append(data);
  return numpy.array(result);

 def predict(self, x):
  return self.forward_pass(x)[self.__OLI];


def main():
 logging.basicConfig(level = logging.INFO,
   format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
   datefmt = '%a, %d %b %Y %H:%M:%S');
   
 logging.info("trainning begin.");
 nn = NeuralNetwork([2, 2, 1]);
 X = numpy.array([[0, 0], [1, 0], [1, 1], [0, 1]]);
 Y = numpy.array([0, 1, 0, 1]);
 nn.train(X, Y);

 logging.info("trainning end. predict begin.");
 for x in X:
  print(x, nn.predict(x));

 plt.plot(nn.L)
 plt.show();

if __name__ == "__main__":
 main();

具体收敛效果

基于python的BP神经网络及异或实现过程解析

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现的jpg格式图片修复代码
Apr 21 Python
python使用线程封装的一个简单定时器类实例
May 16 Python
python实现杨辉三角思路
Jul 14 Python
详解用Python练习画个美队盾牌
Mar 23 Python
Python读取stdin方法实例
May 24 Python
python networkx 包绘制复杂网络关系图的实现
Jul 10 Python
django 做 migrate 时 表已存在的处理方法
Aug 31 Python
Anaconda+vscode+pytorch环境搭建过程详解
May 25 Python
Python识别处理照片中的条形码
Nov 16 Python
Python模拟键盘输入自动登录TGP
Nov 27 Python
浅谈Python3中datetime不同时区转换介绍与踩坑
Aug 02 Python
详解Python如何批量采集京东商品数据流程
Jan 22 Python
Window10下python3.7 安装与卸载教程图解
Sep 30 #Python
Python检查图片是否损坏及图片类型是否正确过程详解
Sep 30 #Python
Python3 合并二叉树的实现
Sep 30 #Python
自适应线性神经网络Adaline的python实现详解
Sep 30 #Python
softmax及python实现过程解析
Sep 30 #Python
python根据时间获取周数代码实例
Sep 30 #Python
Win10 安装PyCharm2019.1.1(图文教程)
Sep 29 #Python
You might like
PHP 年龄计算函数(精确到天)
2012/06/07 PHP
使用PHP获取汉字的拼音(全部与首字母)
2013/06/27 PHP
详细解读PHP中接口的应用
2015/08/12 PHP
CI框架使用composer安装的依赖包步骤与方法分析
2016/11/21 PHP
PHP CodeIgniter分页实例及多条件查询解决方案(推荐)
2017/05/20 PHP
使用PHPStorm+XDebug搭建单步调试环境
2017/11/19 PHP
Laravel5框架自定义错误页面配置操作示例
2019/04/17 PHP
JS下拉缓冲菜单示例代码
2013/08/30 Javascript
JS仿百度搜索自动提示框匹配查询功能
2013/11/21 Javascript
jQuery实现列表内容的动态载入特效
2015/08/08 Javascript
jQuery设置Cookie及删除Cookie实例分析
2016/04/15 Javascript
Ext JS 实现建议词模糊动态搜索功能
2017/05/13 Javascript
JS解析url查询参数的简单代码
2017/08/06 Javascript
JS实现数组去重及数组内对象去重功能示例
2019/02/02 Javascript
基于Vant UI框架实现时间段选择器
2020/12/24 Javascript
MySQLdb ImportError: libmysqlclient.so.18解决方法
2014/08/21 Python
使用Python3中的gettext模块翻译Python源码以支持多语言
2015/03/31 Python
Django 创建新App及其常用命令的实现方法
2019/08/04 Python
PyQt5基本控件使用之消息弹出、用户输入、文件对话框的使用方法
2019/08/06 Python
django 连接数据库 sqlite的例子
2019/08/14 Python
python 发送json数据操作实例分析
2019/10/15 Python
python GUI库图形界面开发之PyQt5 UI主线程与耗时线程分离详细方法实例
2020/02/26 Python
python 等差数列末项计算方式
2020/05/03 Python
python 递归相关知识总结
2021/03/03 Python
分享CSS3制作卡片式图片的方法
2016/07/08 HTML / CSS
世界领先的以旅馆为主的在线预订平台:Hostelworld
2016/10/09 全球购物
写一个用矩形法求定积分的通用函数
2012/11/08 面试题
护理专业毕业生推荐信
2013/10/31 职场文书
酒店服务与管理毕业生求职信
2013/11/02 职场文书
课外科技活动总结
2014/08/27 职场文书
放假通知格式
2015/04/14 职场文书
销区经理年终述职报告模板
2019/11/28 职场文书
详解在SQLPlus中实现上下键翻查历史命令的功能
2022/03/18 SQL Server
SpringBoot整合Minio文件存储
2022/04/03 Java/Android
微信小程序APP的事件绑定以及传递参数时的冒泡和捕获
2022/04/19 Javascript
python神经网络学习 使用Keras进行简单分类
2022/05/04 Python