python实现BP神经网络回归预测模型


Posted in Python onAugust 09, 2019

神经网络模型一般用来做分类,回归预测模型不常见,本文基于一个用来分类的BP神经网络,对它进行修改,实现了一个回归模型,用来做室内定位。模型主要变化是去掉了第三层的非线性转换,或者说把非线性激活函数Sigmoid换成f(x)=x函数。这样做的主要原因是Sigmoid函数的输出范围太小,在0-1之间,而回归模型的输出范围较大。模型修改如下:

python实现BP神经网络回归预测模型

python实现BP神经网络回归预测模型

代码如下:

#coding: utf8
''''
author: Huangyuliang
'''
import json
import random
import sys
import numpy as np
 
#### Define the quadratic and cross-entropy cost functions
class CrossEntropyCost(object):
 
  @staticmethod
  def fn(a, y):
    return np.sum(np.nan_to_num(-y*np.log(a)-(1-y)*np.log(1-a)))
 
  @staticmethod
  def delta(z, a, y):
    return (a-y)
 
#### Main Network class
class Network(object):
 
  def __init__(self, sizes, cost=CrossEntropyCost):
 
    self.num_layers = len(sizes)
    self.sizes = sizes
    self.default_weight_initializer()
    self.cost=cost
 
  def default_weight_initializer(self):
 
    self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]
    self.weights = [np.random.randn(y, x)/np.sqrt(x)
            for x, y in zip(self.sizes[:-1], self.sizes[1:])]
  def large_weight_initializer(self):
 
    self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]
    self.weights = [np.random.randn(y, x)
            for x, y in zip(self.sizes[:-1], self.sizes[1:])]
  def feedforward(self, a):
    """Return the output of the network if ``a`` is input."""
    for b, w in zip(self.biases[:-1], self.weights[:-1]): # 前n-1层
      a = sigmoid(np.dot(w, a)+b)
 
    b = self.biases[-1]  # 最后一层
    w = self.weights[-1]
    a = np.dot(w, a)+b
    return a
 
  def SGD(self, training_data, epochs, mini_batch_size, eta,
      lmbda = 0.0,
      evaluation_data=None,
      monitor_evaluation_accuracy=False): # 用随机梯度下降算法进行训练
 
    n = len(training_data)
 
    for j in xrange(epochs):
      random.shuffle(training_data)
      mini_batches = [training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size)]
      
      for mini_batch in mini_batches:
        self.update_mini_batch(mini_batch, eta, lmbda, len(training_data))
      print ("Epoch %s training complete" % j)
      
      if monitor_evaluation_accuracy:
        print ("Accuracy on evaluation data: {} / {}".format(self.accuracy(evaluation_data), j))
     
  def update_mini_batch(self, mini_batch, eta, lmbda, n):
    """Update the network's weights and biases by applying gradient
    descent using backpropagation to a single mini batch. The
    ``mini_batch`` is a list of tuples ``(x, y)``, ``eta`` is the
    learning rate, ``lmbda`` is the regularization parameter, and
    ``n`` is the total size of the training data set.
    """
    nabla_b = [np.zeros(b.shape) for b in self.biases]
    nabla_w = [np.zeros(w.shape) for w in self.weights]
    for x, y in mini_batch:
      delta_nabla_b, delta_nabla_w = self.backprop(x, y)
      nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
      nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
    self.weights = [(1-eta*(lmbda/n))*w-(eta/len(mini_batch))*nw
            for w, nw in zip(self.weights, nabla_w)]
    self.biases = [b-(eta/len(mini_batch))*nb
            for b, nb in zip(self.biases, nabla_b)]
 
  def backprop(self, x, y):
    """Return a tuple ``(nabla_b, nabla_w)`` representing the
    gradient for the cost function C_x. ``nabla_b`` and
    ``nabla_w`` are layer-by-layer lists of numpy arrays, similar
    to ``self.biases`` and ``self.weights``."""
    nabla_b = [np.zeros(b.shape) for b in self.biases]
    nabla_w = [np.zeros(w.shape) for w in self.weights]
    # feedforward
    activation = x
    activations = [x] # list to store all the activations, layer by layer
    zs = [] # list to store all the z vectors, layer by layer
    for b, w in zip(self.biases[:-1], self.weights[:-1]):  # 正向传播 前n-1层
 
      z = np.dot(w, activation)+b
      zs.append(z)
      activation = sigmoid(z)
      activations.append(activation)
# 最后一层,不用非线性
    b = self.biases[-1]
    w = self.weights[-1]
    z = np.dot(w, activation)+b
    zs.append(z)
    activation = z
    activations.append(activation)
    # backward pass 反向传播
    delta = (self.cost).delta(zs[-1], activations[-1], y)  # 误差 Tj - Oj 
    nabla_b[-1] = delta
    nabla_w[-1] = np.dot(delta, activations[-2].transpose()) # (Tj - Oj) * O(j-1)
 
    for l in xrange(2, self.num_layers):
      z = zs[-l]  # w*a + b
      sp = sigmoid_prime(z) # z * (1-z)
      delta = np.dot(self.weights[-l+1].transpose(), delta) * sp # z*(1-z)*(Err*w) 隐藏层误差
      nabla_b[-l] = delta
      nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) # Errj * Oi
    return (nabla_b, nabla_w)
 
  def accuracy(self, data):
 
    results = [(self.feedforward(x), y) for (x, y) in data] 
    alist=[np.sqrt((x[0][0]-y[0])**2+(x[1][0]-y[1])**2) for (x,y) in results]
 
    return np.mean(alist)
 
  def save(self, filename):
    """Save the neural network to the file ``filename``."""
    data = {"sizes": self.sizes,
        "weights": [w.tolist() for w in self.weights],
        "biases": [b.tolist() for b in self.biases],
        "cost": str(self.cost.__name__)}
    f = open(filename, "w")
    json.dump(data, f)
    f.close()
 
#### Loading a Network
def load(filename):
  """Load a neural network from the file ``filename``. Returns an
  instance of Network.
  """
  f = open(filename, "r")
  data = json.load(f)
  f.close()
  cost = getattr(sys.modules[__name__], data["cost"])
  net = Network(data["sizes"], cost=cost)
  net.weights = [np.array(w) for w in data["weights"]]
  net.biases = [np.array(b) for b in data["biases"]]
  return net
 
def sigmoid(z):
  """The sigmoid function.""" 
  return 1.0/(1.0+np.exp(-z))
 
def sigmoid_prime(z):
  """Derivative of the sigmoid function."""
  return sigmoid(z)*(1-sigmoid(z))

调用神经网络进行训练并保存参数:

#coding: utf8
import my_datas_loader_1
import network_0
 
training_data,test_data = my_datas_loader_1.load_data_wrapper()
#### 训练网络,保存训练好的参数
net = network_0.Network([14,100,2],cost = network_0.CrossEntropyCost)
net.large_weight_initializer()
net.SGD(training_data,1000,316,0.005,lmbda =0.1,evaluation_data=test_data,monitor_evaluation_accuracy=True)
filename=r'C:\Users\hyl\Desktop\Second_158\Regression_Model\parameters.txt'
net.save(filename)

第190-199轮训练结果如下:

python实现BP神经网络回归预测模型

调用保存好的参数,进行定位预测:

#coding: utf8
import my_datas_loader_1
import network_0
import matplotlib.pyplot as plt
 
test_data = my_datas_loader_1.load_test_data()
#### 调用训练好的网络,用来进行预测
filename=r'D:\Workspase\Nerual_networks\parameters.txt'   ## 文件保存训练好的参数
net = network_0.load(filename)                ## 调用参数,形成网络
fig=plt.figure(1)
ax=fig.add_subplot(1,1,1)
ax.axis("equal") 
# plt.grid(color='b' , linewidth='0.5' ,linestyle='-')    # 添加网格
x=[-0.3,-0.3,-17.1,-17.1,-0.3]                ## 这是九楼地形的轮廓
y=[-0.3,26.4,26.4,-0.3,-0.3]
m=[1.5,1.5,-18.9,-18.9,1.5]
n=[-2.1,28.2,28.2,-2.1,-2.1]
ax.plot(x,y,m,n,c='k')
 
for i in range(len(test_data)):  
  pre = net.feedforward(test_data[i][0]) # pre 是预测出的坐标    
  bx=pre[0]
  by=pre[1]          
  ax.scatter(bx,by,s=4,lw=2,marker='.',alpha=1) #散点图  
  plt.pause(0.001)
plt.show()

定位精度达到了1.5米左右。定位效果如下图所示:

python实现BP神经网络回归预测模型

真实路径为行人从原点绕环形走廊一圈。

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

Python 相关文章推荐
Python中dictionary items()系列函数的用法实例
Aug 21 Python
使用基于Python的Tornado框架的HTTP客户端的教程
Apr 24 Python
详细介绍Python的鸭子类型
Sep 12 Python
深入理解Python中变量赋值的问题
Jan 12 Python
python读取二进制mnist实例详解
May 31 Python
Python获取当前函数名称方法实例分享
Jan 18 Python
Python把csv数据写入list和字典类型的变量脚本方法
Jun 15 Python
Pytorch实现GoogLeNet的方法
Aug 18 Python
简单瞅瞅Python vars()内置函数的实现
Sep 27 Python
pytorch点乘与叉乘示例讲解
Dec 27 Python
Python qrcode 生成一个二维码的实例详解
Feb 12 Python
python3 使用traceback定位异常实例
Mar 09 Python
Django ORM 聚合查询和分组查询实现详解
Aug 09 #Python
解决Django后台ManyToManyField显示成Object的问题
Aug 09 #Python
详解Python中的正斜杠与反斜杠
Aug 09 #Python
图文详解Django使用Pycharm连接MySQL数据库
Aug 09 #Python
Django ORM多对多查询方法(自定义第三张表&ManyToManyField)
Aug 09 #Python
Django使用Jinja2模板引擎的示例代码
Aug 09 #Python
在Django admin中编辑ManyToManyField的实现方法
Aug 09 #Python
You might like
PHP中cookies使用指南
2007/03/16 PHP
PHP序列号生成函数和字符串替换函数代码
2012/06/07 PHP
php利用新浪接口查询ip获取地理位置示例
2014/01/20 PHP
PHP回溯法解决0-1背包问题实例分析
2015/03/23 PHP
thinkPHP3.2简单实现文件上传的方法
2016/05/16 PHP
php 使用curl模拟登录人人(校内)网的简单实例
2016/06/06 PHP
Javascript实例教程(19) 使用HoTMetal(4)
2006/12/23 Javascript
CSS+Jquery实现页面圆角框方法大全
2009/12/24 Javascript
菜鸟javascript基础资料整理3 正则
2010/12/06 Javascript
javascript语言结构小记(一)
2011/09/10 Javascript
JavaScript获得url查询参数的方法
2015/07/02 Javascript
微信小程序 Flex布局详解
2016/10/09 Javascript
深入理解Vue 的条件渲染和列表渲染
2017/09/01 Javascript
浅谈vue-cli加载不到dev-server.js的解决办法
2017/11/24 Javascript
解决vue build打包之后首页白屏的问题
2018/03/06 Javascript
深入理解JavaScript和TypeScript中的class
2018/04/22 Javascript
node 标准输入流和输出流代码实例
2019/09/19 Javascript
详解supervisor使用教程
2017/11/21 Python
Python列表推导式、字典推导式与集合推导式用法实例分析
2018/02/07 Python
pytorch ImageFolder的覆写实例
2020/02/20 Python
django在开发中取消外键约束的实现
2020/05/20 Python
Python Tornado核心及相关原理详解
2020/06/24 Python
python实现最短路径的实例方法
2020/07/19 Python
python 实现单例模式的5种方法
2020/09/23 Python
Python基于callable函数检测对象是否可被调用
2020/10/16 Python
用CSS3将你的设计带入下个高度
2009/08/08 HTML / CSS
SmartBuyGlasses台湾:名牌眼镜,名牌太阳眼镜及隐形眼镜
2017/01/04 全球购物
机械操作工岗位职责
2014/08/08 职场文书
2014年村党支部工作总结
2014/12/04 职场文书
社区文明倡议书
2015/04/28 职场文书
毕业班班主任工作总结2015
2015/07/23 职场文书
《角的度量》教学反思
2016/02/18 职场文书
react使用antd的上传组件实现文件表单一起提交功能(完整代码)
2021/06/29 Javascript
MySQL高速缓存启动方法及参数详解(query_cache_size)
2021/07/01 MySQL
python中的random模块和相关函数详解
2022/04/22 Python
CSS使用Flex和Grid布局实现3D骰子
2022/08/05 HTML / CSS