用python实现神经网络
一、BP神經網絡
這里介紹目前常用的BP神經網絡,其網絡結構及數學模型如下:
x為??n 維向量, y 為?n 維向量,隱含層有?q 個神經元。假設?N 有個樣本數據,𝑦𝑡,𝑥𝑡,𝑡=1,2,…𝑁{y(t),x(t),t=1,2,…N}。從輸入層到隱含層的權重記為: 𝑊𝑘𝑖(𝑘=1,2,..,𝑞,𝑖=1,2,…𝑛)W_ki (k=1,2,..,q,i=1,2,…n),從隱含層到輸出層的權重記為:𝑊𝑘𝑖𝑘=1,2,…𝑞,𝑖=1,2,…𝑛?W_ki (k=1,2,…q,i=1,2,…n)? 。?
1)以澳大利亞信貸批準數據集為例,介紹Python神經網絡分類模型的應用。具體計算流程及思路如下:
1.數據獲取及訓練樣本、測試樣本的劃分
2.神經網絡分類模型構建
(1)導入神經網絡分類模塊MLPClassifier。
from sklearn.neural_network import MLPClassifier
(2)利用MLPClassifier創建神經網絡分類對象clf。
clf = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5,2), random_state=1)
參數說明:
Solver:神經網絡優化求解算法,包括lbfgs、sgd、adam三種,默認為adam
Alpha:模型訓練誤差,默認為0.0001
Hidden_layer_sizes:隱含層神經元個數,如果是單層神經元,設置其具體數值即可,本例中隱含層有兩層,為5*2.
random_state:默認設置為1即可。
(3)調用clf對象中的fit()方法進行網絡訓練。
clf.fit(x, y)
(4)調用clf對象中的score ()方法,獲得神經網絡的預測準確率(針對訓練數據)
rv=clf.score(x,y)
(5)調用clf對象中的predict()方法可以對測試樣本進行預測,獲得其預測結果
R=clf.predict(x1)
示例代碼如下:
import pandas as pd data = pd.read_excel('credit.xlsx') x = data.iloc[:600,:14].as_matrix() y = data.iloc[:600,14].as_matrix() x1= data.iloc[600:,:14].as_matrix() y1= data.iloc[600:,14].as_matrix() from sklearn.neural_network import MLPClassifier clf = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5,2), random_state=1) clf.fit(x, y); rv=clf.score(x,y) R=clf.predict(x1) Z=R-y1 Rs=len(Z[Z==0])/len(Z) print('預測結果為:',R) print('預測準確率為:',Rs)執行結果如下:
預測結果為: [0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 0 0 0 1 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 1 1 0 1 0 1 1 0 1 0 0 0 1 0 0 1 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 1 0 0 1 0 1 1 0 0 1 0]
預測準確率為: 0.8222222222222222
2)以5.3.3中的發電場數據為例,預測AT=28.4,V=50.6,AP=1011.9,RH=80.54時的PE值。其計算流程及思路如下:
1.數據獲取及訓練樣本構建
其中訓練樣本的特征輸入變量用x表示,輸出變量用y表示。
import pandas as pddata = pd.read_excel('發電場數據.xlsx')x = data.iloc[:,0:4]y = data.iloc[:,4]2.預測樣本的構建
其中預測樣本的輸入特征變量用x1表示
import numpy as npx1=np.array([28.4,50.6,1011.9,80.54])x1=x1.reshape(1,4)3.神經網絡回歸模型構建
(1)導入神經網絡回歸模塊MLPRegressor。
from sklearn.neural_network import MLPRegressor(2)利用MLPRegressor創建神經網絡回歸對象clf。
clf = MLPRegressor(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=8, random_state=1)參數說明:
Solver:神經網絡優化求解算法,包括lbfgs、sgd、adam三種,默認為adam
Alpha:模型訓練誤差,默認為0.0001
Hidden_layer_sizes:隱含層神經元個數,如果是單層神經元,設置其具體數值即可,如果是多層,比如隱含層有兩層5*2,則hidden_layer_sizes=(5,2).
random_state:默認設置為1即可。
(3)調用clf對象中的fit()方法進行網絡訓練。
clf.fit(x, y)(4)調用clf對象中的score ()方法,獲得神經網絡回歸的擬合優度(判決系數)。
rv=clf.score(x,y)(5)調用clf對象中的predict()可以對測試樣本進行預測,獲得其預測結果。
R=clf.predict(x1)示例代碼如下:
import pandas as pd data = pd.read_excel('發電場數據.xlsx') x = data.iloc[:,0:4] y = data.iloc[:,4] 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) import numpy as np x1=np.array([28.4,50.6,1011.9,80.54]) x1=x1.reshape(1,4) R=clf.predict(x1) print('樣本預測值為:',R)輸出結果為:
樣本預測值為: [ 439.27258187]
?
總結
以上是生活随笔為你收集整理的用python实现神经网络的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: xp计算机无法关机,xp系统不能关机解决
- 下一篇: Z-BLOG 懒人一键采集插件,自动采集