最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python實(shí)現(xiàn)BP神經(jīng)網(wǎng)絡(luò)回歸預(yù)測(cè)模型

 更新時(shí)間:2019年08月09日 10:26:37   作者:-HuangYuliang-  
這篇文章主要介紹了python實(shí)現(xiàn)BP神經(jīng)網(wǎng)絡(luò)回歸預(yù)測(cè)模型,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

神經(jīng)網(wǎng)絡(luò)模型一般用來(lái)做分類,回歸預(yù)測(cè)模型不常見,本文基于一個(gè)用來(lái)分類的BP神經(jīng)網(wǎng)絡(luò),對(duì)它進(jìn)行修改,實(shí)現(xiàn)了一個(gè)回歸模型,用來(lái)做室內(nèi)定位。模型主要變化是去掉了第三層的非線性轉(zhuǎn)換,或者說(shuō)把非線性激活函數(shù)Sigmoid換成f(x)=x函數(shù)。這樣做的主要原因是Sigmoid函數(shù)的輸出范圍太小,在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):
 
  @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): # 用隨機(jī)梯度下降算法進(jìn)行訓(xùn)練
 
    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))

調(diào)用神經(jīng)網(wǎng)絡(luò)進(jìn)行訓(xùn)練并保存參數(shù):

#coding: utf8
import my_datas_loader_1
import network_0
 
training_data,test_data = my_datas_loader_1.load_data_wrapper()
#### 訓(xùn)練網(wǎng)絡(luò),保存訓(xùn)練好的參數(shù)
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輪訓(xùn)練結(jié)果如下:

調(diào)用保存好的參數(shù),進(jìn)行定位預(yù)測(cè):

#coding: utf8
import my_datas_loader_1
import network_0
import matplotlib.pyplot as plt
 
test_data = my_datas_loader_1.load_test_data()
#### 調(diào)用訓(xùn)練好的網(wǎng)絡(luò),用來(lái)進(jìn)行預(yù)測(cè)
filename=r'D:\Workspase\Nerual_networks\parameters.txt'   ## 文件保存訓(xùn)練好的參數(shù)
net = network_0.load(filename)                ## 調(diào)用參數(shù),形成網(wǎng)絡(luò)
fig=plt.figure(1)
ax=fig.add_subplot(1,1,1)
ax.axis("equal") 
# plt.grid(color='b' , linewidth='0.5' ,linestyle='-')    # 添加網(wǎng)格
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 是預(yù)測(cè)出的坐標(biāo)    
  bx=pre[0]
  by=pre[1]          
  ax.scatter(bx,by,s=4,lw=2,marker='.',alpha=1) #散點(diǎn)圖  
  plt.pause(0.001)
plt.show() 

定位精度達(dá)到了1.5米左右。定位效果如下圖所示:

真實(shí)路徑為行人從原點(diǎn)繞環(huán)形走廊一圈。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Django項(xiàng)目搭建之實(shí)現(xiàn)簡(jiǎn)單的API訪問(wèn)

    Django項(xiàng)目搭建之實(shí)現(xiàn)簡(jiǎn)單的API訪問(wèn)

    這篇文章主要給大家介紹了關(guān)于Django項(xiàng)目搭建之實(shí)現(xiàn)簡(jiǎn)單的API訪問(wèn)的相關(guān)資料,文中通過(guò)圖文以及示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Django具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2023-02-02
  • 基于Python的socket庫(kù)實(shí)現(xiàn)通信功能的示例代碼

    基于Python的socket庫(kù)實(shí)現(xiàn)通信功能的示例代碼

    本文主要給大家介紹了如何使用python的socket庫(kù)實(shí)現(xiàn)通信功能,這里簡(jiǎn)單的給每個(gè)客戶端增加一個(gè)不重復(fù)的uid,客戶端之間可以根據(jù)這個(gè)uid選擇進(jìn)行廣播通信,感興趣的小伙伴快來(lái)看看吧
    2023-08-08
  • Python基于time模塊表示時(shí)間常用方法

    Python基于time模塊表示時(shí)間常用方法

    這篇文章主要介紹了Python基于time模塊表示時(shí)間常用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • Python3.5字符串常用操作實(shí)例詳解

    Python3.5字符串常用操作實(shí)例詳解

    這篇文章主要介紹了Python3.5字符串常用操作,結(jié)合實(shí)例形式總結(jié)分析了Python3.5字符串輸入、輸出、格式化、切片以及各種常用操作函數(shù)相關(guān)使用技巧,需要的朋友可以參考下
    2019-05-05
  • 基于Python實(shí)現(xiàn)2種反轉(zhuǎn)鏈表方法代碼實(shí)例

    基于Python實(shí)現(xiàn)2種反轉(zhuǎn)鏈表方法代碼實(shí)例

    這篇文章主要介紹了基于Python實(shí)現(xiàn)2種反轉(zhuǎn)鏈表方法代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • python 并發(fā)編程 阻塞IO模型原理解析

    python 并發(fā)編程 阻塞IO模型原理解析

    這篇文章主要介紹了python 并發(fā)編程 阻塞IO模型原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • pycharm 如何取消連按兩下shift出現(xiàn)的全局搜索

    pycharm 如何取消連按兩下shift出現(xiàn)的全局搜索

    這篇文章主要介紹了pycharm 如何取消連按兩下shift出現(xiàn)的全局搜索?下面小編就為大家介紹一下解決方法,還等什么?一起跟隨小編過(guò)來(lái)看看吧
    2021-01-01
  • Python 的 f-string 可以連接字符串與數(shù)字的原因解析

    Python 的 f-string 可以連接字符串與數(shù)字的原因解析

    這篇文章主要介紹了Python 的 f-string 可以連接字符串與數(shù)字的原因解析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-02-02
  • flask操作數(shù)據(jù)庫(kù)插件Flask-SQLAlchemy的使用

    flask操作數(shù)據(jù)庫(kù)插件Flask-SQLAlchemy的使用

    Python?中最廣泛使用的ORM框架是SQLAlchemy,它是一個(gè)很強(qiáng)大的關(guān)系型數(shù)據(jù)庫(kù)框架,本文就來(lái)介紹一下flask操作數(shù)據(jù)庫(kù)插件Flask-SQLAlchemy的使用,感興趣的可以了解一下
    2023-09-09
  • python實(shí)現(xiàn)超市掃碼儀計(jì)費(fèi)

    python實(shí)現(xiàn)超市掃碼儀計(jì)費(fèi)

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)超市掃碼儀計(jì)費(fèi),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-05-05

最新評(píng)論

美姑县| 大化| 长泰县| 连山| 靖安县| 霍邱县| 喜德县| 凌源市| 溧阳市| 微山县| 板桥市| 资源县| 南木林县| 乌兰浩特市| 黄龙县| 永丰县| 闵行区| 唐河县| 时尚| 石首市| 合作市| 石城县| 望谟县| 哈尔滨市| 台中县| 仪陇县| 买车| 汉阴县| 南和县| 上虞市| 福海县| 宁安市| 五家渠市| 高邑县| 宣汉县| 招远市| 苗栗县| 苏尼特右旗| 哈巴河县| 正蓝旗| 浙江省|