BP神经网络原理及Python实现代码


Posted in Python onDecember 18, 2018

本文主要讲如何不依赖TenserFlow等高级API实现一个简单的神经网络来做分类,所有的代码都在下面;在构造的数据(通过程序构造)上做了验证,经过1个小时的训练分类的准确率可以达到97%。

完整的结构化代码见于:链接地址

先来说说原理

网络构造

BP神经网络原理及Python实现代码

上面是一个简单的三层网络;输入层包含节点X1 , X2;隐层包含H1,H2;输出层包含O1。
输入节点的数量要等于输入数据的变量数目。
隐层节点的数量通过经验来确定。
如果只是做分类,输出层一般一个节点就够了。

从输入到输出的过程

1.输入节点的输出等于输入,X1节点输入x1时,输出还是x1.
2. 隐层和输出层的输入I为上层输出的加权求和再加偏置,输出为f(I) , f为激活函数,可以取sigmoid。H1的输出为 sigmoid(w1x1 + w2x2 + b)

误差反向传播的过程

Python实现

构造测试数据

# -*- coding: utf-8 -*-
import numpy as np
from random import random as rdn

'''
说明:我们构造1000条数据,每条数据有三个属性(用a1 , a2 , a3表示)
a1 离散型 取值 1 到 10 , 均匀分布
a2 离散型 取值 1 到 10 , 均匀分布
a3 连续型 取值 1 到 100 , 且符合正态分布 
各属性之间独立。

共2个分类(0 , 1),属性值与类别之间的关系如下,
0 : a1 in [1 , 3] and a2 in [4 , 10] and a3 <= 50
1 : a1 in [1 , 3] and a2 in [4 , 10] and a3 > 50
0 : a1 in [1 , 3] and a2 in [1 , 3] and a3 > 30
1 : a1 in [1 , 3] and a2 in [1 , 3] and a3 <= 30
0 : a1 in [4 , 10] and a2 in [4 , 10] and a3 <= 50
1 : a1 in [4 , 10] and a2 in [4 , 10] and a3 > 50
0 : a1 in [4 , 10] and a2 in [1 , 3] and a3 > 30
1 : a1 in [4 , 10] and a2 in [1 , 3] and a3 <= 30
'''


def genData() :
 #为a3生成符合正态分布的数据
 a3_data = np.random.randn(1000) * 30 + 50
 data = []
 for i in range(1000) :
 #生成a1
 a1 = int(rdn()*10) + 1
 if a1 > 10 :
  a1 = 10
 #生成a2
 a2 = int(rdn()*10) + 1
 if a2 > 10 :
  a2 = 10
 #取a3
 a3 = a3_data[i] 
 #计算这条数据对应的类别
 c_id = 0
 if a1 <= 3 and a2 >= 4 and a3 <= 50 :
  c_id = 0 
 elif a1 <= 3 and a2 >= 4 and a3 > 50 :
  c_id = 1 
 elif a1 <= 3 and a2 < 4 and a3 > 30 :
  c_id = 0
 elif a1 <= 3 and a2 < 4 and a3 <= 30 :
  c_id = 1
 elif a1 > 3 and a2 >= 4 and a3 <= 50 :
  c_id = 0 
 elif a1 > 3 and a2 >= 4 and a3 > 50 :
  c_id = 1 
 elif a1 > 3 and a2 < 4 and a3 > 30 :
  c_id = 0
 elif a1 > 3 and a2 < 4 and a3 <= 30 :
  c_id = 1
 else :
  print('error')
 #拼合成字串
 str_line = str(i) + ',' + str(a1) + ',' + str(a2) + ',' + str(a3) + ',' + str(c_id)
 data.append(str_line)
 return '\n'.join(data)

激活函数

# -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 14:49:31 2018

@author: congpeiqing
"""
import numpy as np

#sigmoid函数的导数为 f(x)*(1-f(x))
def sigmoid(x) :
 return 1/(1 + np.exp(-x))

网络实现

# -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 14:49:31 2018

@author: congpeiqing
"""

from activation_funcs import sigmoid
from random import random

class InputNode(object) :
 def __init__(self , idx) :
 self.idx = idx
 self.output = None
  
 def setInput(self , value) :
 self.output = value
 
 def getOutput(self) :
 return self.output
 
 def refreshParas(self , p1 , p2) :
 pass
 
 
class Neurode(object) :
 def __init__(self , layer_name , idx , input_nodes , activation_func = None , powers = None , bias = None) :
 self.idx = idx 
 self.layer_name = layer_name
 self.input_nodes = input_nodes 
 if activation_func is not None :
  self.activation_func = activation_func
 else :
  #默认取 sigmoid
  self.activation_func = sigmoid
 if powers is not None :
  self.powers = powers
 else :
  self.powers = [random() for i in range(len(self.input_nodes))]
 if bias is not None :
  self.bias = bias
 else :
  self.bias = random()
 self.output = None
  
 def getOutput(self) :
 self.output = self.activation_func(sum(map(lambda x : x[0].getOutput()*x[1] , zip(self.input_nodes, self.powers))) + self.bias)
 return self.output
  
 def refreshParas(self , err , learn_rate) :
 err_add = self.output * (1 - self.output) * err 
 for i in range(len(self.input_nodes)) :
  #调用子节点
  self.input_nodes[i].refreshParas(self.powers[i] * err_add , learn_rate)
  #调节参数
  power_delta = learn_rate * err_add * self.input_nodes[i].output 
  self.powers[i] += power_delta
  bias_delta = learn_rate * err_add
  self.bias += bias_delta
 
 
class SimpleBP(object) :
 def __init__(self , input_node_num , hidden_layer_node_num , trainning_data , test_data) :
 self.input_node_num = input_node_num
 self.input_nodes = [InputNode(i) for i in range(input_node_num)]
 self.hidden_layer_nodes = [Neurode('H' , i , self.input_nodes) for i in range(hidden_layer_node_num)]
 self.output_node = Neurode('O' , 0 , self.hidden_layer_nodes)
 self.trainning_data = trainning_data
 self.test_data = test_data
 
 
 #逐条训练
 def trainByItem(self) :
 cnt = 0
 while True :
  cnt += 1
  learn_rate = 1.0/cnt
  sum_diff = 0.0
  #对于每一条训练数据进行一次训练过程
  for item in self.trainning_data :
  for i in range(self.input_node_num) :
   self.input_nodes[i].setInput(item[i])
  item_output = item[-1]
  nn_output = self.output_node.getOutput()
  #print('nn_output:' , nn_output)
  diff = (item_output-nn_output)
  sum_diff += abs(diff)
  self.output_node.refreshParas(diff , learn_rate)
  #print('refreshedParas')
  #结束条件 
  print(round(sum_diff / len(self.trainning_data) , 4))
  if sum_diff / len(self.trainning_data) < 0.1 :
  break
 
 def getAccuracy(self) :
 cnt = 0
 for item in self.test_data :
  for i in range(self.input_node_num) :
  self.input_nodes[i].setInput(item[i])
  item_output = item[-1]
  nn_output = self.output_node.getOutput()
  if (nn_output > 0.5 and item_output > 0.5) or (nn_output < 0.5 and item_output < 0.5) :
  cnt += 1
 return cnt/(len(self.test_data) + 0.0)

主调流程

# -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 14:49:31 2018

@author: congpeiqing
"""
import os
from SimpleBP import SimpleBP
from GenData import genData

if not os.path.exists('data'):
 os.makedirs('data') 

#构造训练和测试数据
data_file = open('data/trainning_data.dat' , 'w')
data_file.write(genData())
data_file.close()

data_file = open('data/test_data.dat' , 'w')
data_file.write(genData())
data_file.close()


#文件格式:rec_id,attr1_value,attr2_value,attr3_value,class_id
#读取和解析训练数据
trainning_data_file = open('data/trainning_data.dat')
trainning_data = []
for line in trainning_data_file :
 line = line.strip()
 fld_list = line.split(',')
 trainning_data.append(tuple([float(field) for field in fld_list[1:]]))
trainning_data_file.close()

#读取和解析测试数据
test_data_file = open('data/test_data.dat')
test_data = []
for line in test_data_file :
 line = line.strip()
 fld_list = line.split(',')
 test_data.append(tuple([float(field) for field in fld_list[1:]]))
test_data_file.close()


#构造一个二分类网络 输入节点3个,隐层节点10个,输出节点一个
simple_bp = SimpleBP(3 , 10 , trainning_data , test_data)
#训练网络
simple_bp.trainByItem()
#测试分类准确率
print('Accuracy : ' , simple_bp.getAccuracy())
#训练时长比较长,准确率可以达到97%

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

Python 相关文章推荐
Python最基本的输入输出详解
Apr 25 Python
python实现查找excel里某一列重复数据并且剔除后打印的方法
May 26 Python
python制作爬虫并将抓取结果保存到excel中
Apr 06 Python
Python实现将数据库一键导出为Excel表格的实例
Dec 30 Python
python多进程和多线程究竟谁更快(详解)
May 29 Python
python-docx修改已存在的Word文档的表格的字体格式方法
May 08 Python
深入浅析Python的类
Jun 22 Python
Django ORM多对多查询方法(自定义第三张表&amp;ManyToManyField)
Aug 09 Python
利用anaconda作为python的依赖库管理方法
Aug 13 Python
Python的形参和实参使用方式
Dec 24 Python
Python如何使用27行代码绘制星星图
Jul 20 Python
Python实现智慧校园自动评教全新版
Jun 18 Python
python 执行文件时额外参数获取的实例
Dec 18 #Python
python实现基于信息增益的决策树归纳
Dec 18 #Python
Django实现一对多表模型的跨表查询方法
Dec 18 #Python
Python实现字典排序、按照list中字典的某个key排序的方法示例
Dec 18 #Python
python实现求特征选择的信息增益
Dec 18 #Python
python实现连续图文识别
Dec 18 #Python
Django ManyToManyField 跨越中间表查询的方法
Dec 18 #Python
You might like
php GeoIP的使用教程
2011/03/09 PHP
php whois查询API制作方法
2011/06/23 PHP
PHP将DateTime对象转化为友好时间显示的实现代码
2011/09/20 PHP
php实现加减法验证码代码
2014/02/14 PHP
php像数组一样存取和修改字符串字符
2014/03/21 PHP
php伪静态之APACHE篇
2014/06/02 PHP
异步加载技术实现当滚动条到最底部的瀑布流效果
2014/09/16 PHP
win10环境PHP 7 安装配置【教程】
2016/05/09 PHP
关于使用runtimeStyle属性问题讨论文章
2007/03/08 Javascript
经常用到的JavasScript事件的翻译
2007/04/09 Javascript
js 3秒后跳转页面的实现代码
2014/03/10 Javascript
小议JavaScript中Generator和Iterator的使用
2015/07/29 Javascript
window.close(); 关闭浏览器窗口js代码的总结介绍
2016/07/14 Javascript
一个有意思的鼠标点击文字特效jquery代码
2017/09/23 jQuery
基于vue-cli配置lib-flexible + rem实现移动端自适应
2017/12/26 Javascript
详解Vue源码之数据的代理访问
2018/12/11 Javascript
使用Vue.set()方法实现响应式修改数组数据步骤
2019/11/09 Javascript
vue+axios 拦截器实现统一token的案例
2020/09/11 Javascript
Python常用列表数据结构小结
2014/08/06 Python
Python语言描述连续子数组的最大和
2018/01/04 Python
python实现雪花飘落效果实例讲解
2019/06/18 Python
Python如何访问字符串中的值
2020/02/09 Python
django queryset相加和筛选教程
2020/05/18 Python
Python自动化xpath实现自动抢票抢货
2020/09/19 Python
如何Tkinter模块编写Python图形界面
2020/10/14 Python
pandas 数据类型转换的实现
2020/12/29 Python
HTML5画渐变背景图片并自动下载实现步骤
2013/11/18 HTML / CSS
关于廉洁的广播稿
2014/01/30 职场文书
大学毕业感言一句话
2014/02/06 职场文书
心理健康课教学反思
2014/02/13 职场文书
大专生求职信
2014/06/29 职场文书
嘉宾邀请函
2015/01/31 职场文书
导游欢送词
2015/01/31 职场文书
“学党章、守党纪、讲党规”学习心得体会
2016/01/14 职场文书
Java多线程并发FutureTask使用详解
2022/06/28 Java/Android
React更新渲染原理深入分析
2022/12/24 Javascript