BP神经网络回归预测模型(python实现)
神经网络模型一般用来做分类,回归预测模型不常见,本文基于一个用来分类的BP神经网络,对它进行修改,实现了一个回归模型,用来做室内定位。模型主要变化是去掉了第三层的非线性转换,或者说把非线性激活函数Sigmoid换成f(x)=x函数。这样做的主要原因是Sigmoid函数的输出范围太小,在0-1之间,而回归模型的输出范围较大。模型修改如下:
代码如下:
#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):@staticmethoddef fn(a, y):return np.sum(np.nan_to_num(-y*np.log(a)-(1-y)*np.log(1-a)))@staticmethoddef 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 = sizesself.default_weight_initializer()self.cost=costdef 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)+breturn adef 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 gradientdescent using backpropagation to a single mini batch. The``mini_batch`` is a list of tuples ``(x, y)``, ``eta`` is thelearning 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))*nwfor w, nw in zip(self.weights, nabla_w)]self.biases = [b-(eta/len(mini_batch))*nbfor b, nb in zip(self.biases, nabla_b)]def backprop(self, x, y):"""Return a tuple ``(nabla_b, nabla_w)`` representing thegradient for the cost function C_x. ``nabla_b`` and``nabla_w`` are layer-by-layer lists of numpy arrays, similarto ``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]# feedforwardactivation = xactivations = [x] # list to store all the activations, layer by layerzs = [] # list to store all the z vectors, layer by layerfor b, w in zip(self.biases[:-1], self.weights[:-1]): # 正向传播 前n-1层z = np.dot(w, activation)+bzs.append(z)activation = sigmoid(z)activations.append(activation)
# 最后一层,不用非线性b = self.biases[-1]w = self.weights[-1]z = np.dot(w, activation)+bzs.append(z)activation = zactivations.append(activation)# backward pass 反向传播delta = (self.cost).delta(zs[-1], activations[-1], y) # 误差 Tj - Oj nabla_b[-1] = deltanabla_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 + bsp = sigmoid_prime(z) # z * (1-z)delta = np.dot(self.weights[-l+1].transpose(), delta) * sp # z*(1-z)*(Err*w) 隐藏层误差nabla_b[-l] = deltanabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) # Errj * Oireturn (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 aninstance 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 netdef 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_0training_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轮训练结果如下:
调用保存好的参数,进行定位预测:
#coding: utf8
import my_datas_loader_1
import network_0
import matplotlib.pyplot as plttest_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()
真实路径为行人从原点绕环形走廊一圈。
BP神经网络回归预测模型(python实现)相关推荐
- bp神经网络回归预测模型(python实现)_python实现BP神经网络回归预测模型
神经网络模型一般用来做分类,回归预测模型不常见,本文基于一个用来分类的BP神经网络,对它进行修改,实现了一个回归模型,用来做室内定位.模型主要变化是去掉了第三层的非线性转换,或者说把非线性激活函数Si ...
- python bp神经网络进行预测_python实现BP神经网络回归预测模型
神经网络模型一般用来做分类,回归预测模型不常见,本文基于一个用来分类的BP神经网络,对它进行修改,实现了一个回归模型,用来做室内定位.模型主要变化是去掉了第三层的非线性转换,或者说把非线性激活函数Si ...
- Python实现哈里斯鹰优化算法(HHO)优化BP神经网络回归模型(BP神经网络回归算法)项目实战
说明:这是一个机器学习实战项目(附带数据+代码+文档+视频讲解),如需数据+代码+文档+视频讲解可以直接到文章最后获取. 1.项目背景 2019年Heidari等人提出哈里斯鹰优化算法(Harris ...
- Python实现贝叶斯优化器(Bayes_opt)优化BP神经网络回归模型(BP神经网络回归算法)项目实战
说明:这是一个机器学习实战项目(附带数据+代码+文档+视频讲解),如需数据+代码+文档+视频讲解可以直接到文章最后获取. 1.项目背景 贝叶斯优化器 (BayesianOptimization) 是一 ...
- 神经网络-回归(Python)
神经网络-回归(Python) 回归与神经网络简介 回归分析 神经网络 神经网络学习算法原理 监督学习和无监督学习 多层感知器--MLP BP神经网络 代码实现(利用sklearn库) 根据算法写出B ...
- 【MATLAB第58期】基于MATLAB的PCA-Kmeans、PCA-LVQ与BP神经网络分类预测模型对比
[MATLAB第58期]基于MATLAB的PCA-Kmeans.PCA-LVQ与BP神经网络分类预测模型对比 一.数据介绍 基于UCI葡萄酒数据集进行葡萄酒分类及产地预测 共包含178组样本数据,来源 ...
- 神经网络模型预测控制,神经网络回归预测模型
bp神经网络为什么要采用非线性函数来进行预测? 提问:bp神经网络为什么要采用非线性函数来进行预测? 回答:简单的讲,主要是复杂的bp神经网络的行为动态及神经元之间的相互作用是无法用简单的线性函数来描 ...
- BP神经网络原理及Python实现
BP神经网络及Python实现 BP神经网网络原理 BP网络模型 BP学习算法 Python算法实现 多层感知器基本参数设定 最近刚好在跟着课程一起学TensorFlow,顺道把整个神经网络的理论复习 ...
- 城市客运运输量的BP神经网络预测的python实现
城市客运运输量的BP神经网络预测 今天学会了BP神经网络的python代码实现,做了一个关于城市客运运输量的预测. 首先数据来源于统计局网站 可能这个分析的角度毫无意义,但也是为了学习下BP神经网络的 ...
- 基于Tensorflow框架的BP神经网络回归小案例--预测跳高
(案例):我们将14组国内男子跳高运动员各项素质指标作为输入,即(30m行进跑,立定三级跳远,助跑摸高,助跑4-6步跳高,负重深蹲杠铃,杠铃半蹲系数,100m,抓举),将对应的跳高成绩作为输出,通过对 ...
最新文章
- 分享做LOGO 的方法和思维方式 -liuleihai
- 卡尔蔡司携手神策数据,赋能近视防控数字化
- 使用diskpart命令为windows7创建分区
- java seteditable,Java TextField.setEditable方法代碼示例
- JavaScript笔记-使用反引号格式化字符串
- 已火 2 年,Service Mesh究竟给微服务带来了什么?
- Session 实现、配置与使用详解
- date time 分开存储如何合并_如何将多个日期跨度合并/拆分为一个时间轴(Oracle 11g)?...
- The new year,new mood,new plan~~
- 重建SYSVOL和NETLOGON共享
- K-means 聚类算法的图像区域分割
- 天翼校园网连接不上服务器无响应,天翼校园网dns解析出错怎么办
- 鹏业安装算量材料表不能复制问题解答
- 公司中生存奥秘诙谐解说[转]
- 固态硬盘和传统硬盘的区别
- 神经网络算法和人工智能,神经网络的算法有哪些
- 沟通的艺术:看人入里,看出人外 - part 1
- 微信转账一次显示两个_微信转账又出新玩法!同时满足两个条件,收款转账畅通无阻...
- CSDN个人博客访问量突破300万
- 单片机烧录不进去怎么办?通用类!