欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python純代碼通過神經(jīng)網(wǎng)絡(luò)實現(xiàn)線性回歸的擬合方式

 更新時間:2023年05月31日 10:51:22   作者:Zhao-Jichao  
這篇文章主要介紹了Python純代碼通過神經(jīng)網(wǎng)絡(luò)實現(xiàn)線性回歸的擬合方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

純代碼通過神經(jīng)網(wǎng)絡(luò)實現(xiàn)線性回歸的擬合

參考鏈接中的文章,有錯誤,我給更正了。

并且原文中是需要數(shù)據(jù)集文件的,我直接給替換成了一個數(shù)組,采用直接賦值的方式。

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
class SimpleDataReader(object):
    def __init__(self, data_file):
        self.train_file_name = data_file
        self.num_train = 0
        self.XTrain = None
        self.YTrain = None
    # read data from file
    def ReadData(self):
        # data = np.load(self.train_file_name)
        # self.XTrain = data["data"]
        # self.YTrain = data["label"]
        self.XTrain = np.array([0.95, 3, 4, 5.07, 6.03, 8.21, 8.85, 12.02, 15], dtype=float)
        self.YTrain = np.array([5.1, 8.7, 11.5, 13, 15.3, 18, 21, 26.87, 32.5], dtype=float)
        self.num_train = self.XTrain.shape[0]
        #end if
    # get batch training data
    def GetSingleTrainSample(self, iteration):
        x = self.XTrain[iteration]
        y = self.YTrain[iteration]
        return x, y
    def GetWholeTrainSamples(self):
        return self.XTrain, self.YTrain
class NeuralNet(object):
    def __init__(self, eta):
        self.eta = eta
        self.w = 0
        self.b = 0
    def __forward(self, x):
        z = x * self.w + self.b
        return z
    def __backward(self, x,y,z):
        dz = z - y                  # 原錯誤為:dz = x * (z - y)
        db = dz
        dw = dz
        return dw, db
    def __update(self, dw, db):
        self.w = self.w - self.eta * dw
        self.b = self.b - self.eta * db
    def train(self, dataReader):
        for i in range(dataReader.num_train):
            # get x and y value for one sample
            x,y = dataReader.GetSingleTrainSample(i)
            # get z from x,y
            z = self.__forward(x)
            # calculate gradient of w and b
            dw, db = self.__backward(x, y, z)
            # update w,b
            self.__update(dw, db)
            # end for
    def inference(self, x):
        return self.__forward(x)
if __name__ == '__main__':
    # read data
    sdr = SimpleDataReader('ch04.npz')
    sdr.ReadData()
    # create net
    eta = 0.1
    net = NeuralNet(eta)
    net.train(sdr)
    # result
    print("w=%f,b=%f" %(net.w, net.b))
    # 繪圖部分
    trainX,trainY = sdr.GetWholeTrainSamples()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    # 繪制散點圖
    ax.scatter(trainX,trainY)
    # 繪制線性回歸
    x = np.arange(0, 15, 0.01)
    f = np.vectorize(net.inference, excluded=['x'])
    plt.plot(x,f(x),color='red')
    # 顯示圖表
    plt.show()

在這里插入圖片描述

Ref:

通過神經(jīng)網(wǎng)絡(luò)實現(xiàn)線性回歸的擬合

Python使用線性回歸和神經(jīng)網(wǎng)絡(luò)模型進行預(yù)測

公路運量主要包括公路客運量和公路貨運量兩個方面。

根據(jù)研究,某地區(qū)的公路運量主要與該地區(qū)的人數(shù)、機動車數(shù)量和公路面積有關(guān),表5-11給出了某個地區(qū)20年的公路運量相關(guān)數(shù)據(jù)。

根據(jù)相關(guān)部門數(shù)據(jù),該地區(qū)2010年和2011年的人數(shù)分別為73.39萬和75.55萬,機動車數(shù)量分別為3.9635萬輛和4.0975萬輛,公路面積分別為0.9880萬平方千米和1.0268萬平方千米。

請利用BP神經(jīng)網(wǎng)絡(luò)預(yù)測該地區(qū)2010年和2011年的公路客運量和公路貨運量。

表5-11 運力數(shù)據(jù)表

年份 人數(shù) 機動車數(shù)量 公路面積 公里客運量 公里貨運量
1990 20.55 0.6 0.09 5126 1237
1991 22.44 0.75 0.11 6217 1379
1992 25.37 0.85 0.11 7730 1385
1993 27.13 0.9 0.14 9145 1399
1994 29.45 1.05 0.2 10460 1663
1995 30.1 1.35 0.23 11387 1714
1996 30.96 1.45 0.23 12353 1834
1997 34.06 1.6 0.32 15750 4322
1998 36.42 1.7 0.32 18304 8132
1999 38.09 1.85 0.34 19836 8936
2000 39.13 2.15 0.36 21024 11099
2001 39.99 2.2 0.36 19490 11203
2002 41.93 2.25 0.38 20433 10524
2003 44.59 2.35 0.49 22598 11115
2004 47.3 2.5 0.56 25107 13320
2005 52.89 2.6 0.59 33442 16762
2006 55.73 2.7 0.59 36836 18673
2007 56.76 2.85 0.67 40548 20724
2008 59.17 2.95 0.69 42927 20803
2009 60.63 3.1 0.79 43462 21804

注:數(shù)據(jù)取自《Matlab在數(shù)學(xué)建模中的應(yīng)用(第2版)》,卓金武,第134頁。

在這里插入圖片描述

#1.?dāng)?shù)據(jù)獲取
import pandas as pd
data = pd.read_excel('運力數(shù)據(jù)表.xlsx')
x = data.iloc[:20,:4]
y = data.iloc[:20,4:]
#2.導(dǎo)入線性回歸模塊,簡稱為LR
from sklearn.linear_model import LinearRegression as LR
lr = LR()             #創(chuàng)建線性回歸模型類
lr.fit(x,y)         #擬合
slr=lr.score(x,y)   #判定系數(shù) R^2
c_x=lr.coef_         #x對應(yīng)的回歸系數(shù)
c_b=lr.intercept_   #回歸系數(shù)常數(shù)項
#3.預(yù)測
x1 = data.iloc[20:,:4]
r1=lr.predict(x1)    #采用自帶函數(shù)預(yù)測
#print('x回歸系數(shù)為:',c_x)
#print('回歸系數(shù)常數(shù)項為:',c_b)
#print('判定系數(shù)為:',slr)
#print('樣本預(yù)測值為:',r1)
n=list(data["公里客運量(萬人)"])
n.extend(r1[:,0])
num=pd.DataFrame(n).dropna()
g=list(data["公里貨運量(萬噸)"])
g.extend(r1[:,1])
gravity=pd.DataFrame(g).dropna()
import pandas as pd
import matplotlib.pyplot as plt  #導(dǎo)入繪圖庫中的pyplot模塊,并且簡稱為plt
#構(gòu)造繪圖所需的橫軸數(shù)據(jù)列和縱軸數(shù)據(jù)列
#在figure界面上繪制線性圖
plt.rcParams['font.sans-serif'] = 'SimHei'     #設(shè)置字體為SimHei
plt.figure(1)
plt.plot(data["年份"],num,'r*--')  #紅色“*”號連續(xù)圖,
plt.xlabel('日期')
plt.ylabel('公里客運量(萬人')
plt.title('公里客運量(萬人)走勢圖')
plt.xticks(data["年份"],rotation = 45)
plt.savefig('myfigure1')
plt.figure(2)
plt.plot(data["年份"],gravity,'b*--')  #紅色“*”號連續(xù)圖,
plt.xlabel('日期')
plt.ylabel('公里貨運量(萬噸)')
plt.title('公里貨運量(萬噸)走勢圖')
plt.xticks(data["年份"],rotation = 45)
plt.savefig('myfigure2')
from sklearn.neural_network import MLPRegressor 
clf = MLPRegressor(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=8, random_state=1) 
clf.fit(x, y);   
rv=clf.score(x,y)
r2=clf.predict(x1)   
print('樣本預(yù)測值為:',r2)
n2=list(data["公里客運量(萬人)"])
n2.extend(r2[:,0])
num2=pd.DataFrame(n2).dropna()
g2=list(data["公里貨運量(萬噸)"])
g2.extend(r2[:,1])
gravity2=pd.DataFrame(g2).dropna()

結(jié)果顯示:

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 如何使用python操作vmware

    如何使用python操作vmware

    這篇文章主要介紹了如何使用python操作vmware,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-07-07
  • 學(xué)習(xí)python (2)

    學(xué)習(xí)python (2)

    學(xué)習(xí)python (2)...
    2006-10-10
  • Pytorch 抽取vgg各層并進行定制化處理的方法

    Pytorch 抽取vgg各層并進行定制化處理的方法

    今天小編就為大家分享一篇Pytorch 抽取vgg各層并進行定制化處理的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • OpenCV-Python 攝像頭實時檢測人臉代碼實例

    OpenCV-Python 攝像頭實時檢測人臉代碼實例

    這篇文章主要介紹了OpenCV-Python 攝像頭實時檢測人臉,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • Python類的基本寫法與注釋風(fēng)格介紹

    Python類的基本寫法與注釋風(fēng)格介紹

    這篇文章主要介紹了Python類的基本寫法與注釋風(fēng)格,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • python實現(xiàn)自動化腳本編寫

    python實現(xiàn)自動化腳本編寫

    自動化在很多時候是很方便的,本文以修改用戶名密碼單元為案例,編寫測試腳本。完成修改用戶名密碼模塊單元測試,感興趣的可以了解一下
    2021-06-06
  • Python迭代器模塊itertools使用原理解析

    Python迭代器模塊itertools使用原理解析

    這篇文章主要介紹了Python迭代器模塊itertools使用原理解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-12-12
  • 解決django接口無法通過ip進行訪問的問題

    解決django接口無法通過ip進行訪問的問題

    這篇文章主要介紹了解決django接口無法通過ip進行訪問的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • Python異步與定時任務(wù)提高程序并發(fā)性和定時執(zhí)行效率

    Python異步與定時任務(wù)提高程序并發(fā)性和定時執(zhí)行效率

    Python異步與定時任務(wù)是Python編程中常用的兩種技術(shù),異步任務(wù)可用于高效處理I/O密集型任務(wù),提高程序并發(fā)性;定時任務(wù)可用于定時執(zhí)行計劃任務(wù),提高程序的執(zhí)行效率。這兩種技術(shù)的應(yīng)用有助于提升Python程序的性能和效率
    2023-05-05
  • Python?中給請求設(shè)置用戶代理?User-Agent的方法

    Python?中給請求設(shè)置用戶代理?User-Agent的方法

    本文介紹?HTTP?標(biāo)頭用戶代理主題以及如何使用?Python?中的請求設(shè)置用戶代理,您將了解?HTTP?標(biāo)頭及其在理解用戶代理、獲取用戶代理以及學(xué)習(xí)使用?Python?中的請求設(shè)置用戶代理的多種方法方面的重要性,感興趣的朋友跟隨小編一起看看吧
    2023-06-06

最新評論