bp神经网络预测模型python_BP神经网络模型:Python
本文介紹了運用計量統計軟件Spyder(3.2.6 MAC-Python是版本3.6)建立BP神經網絡模型的方法。Spyder是一款出色的Python語言編輯器,界面類似Matlab。主要運用的方程是MLPClassifier
整理數據
在Excel中將變量按列整理好,其中1至13列為輸入變量,第14列為輸出變量,即輸入層包含13個神經元,輸出層又一個神經元。另外設定一個隱含層,包括20個神經元
每個神經元包含252個數據點,其中最后一個點不參與訓練,留作測試最終的模型,即利用前251個數據點訓練模型,利用最后一個點檢驗模型
在Spyder中輸入數據
1、打開Terminal,輸入spyder,按Enter鍵確認,打開Spyder界面
2、在Console中右擊,可選擇清除所有變量和Console歷史
3、刪除屏幕上的代碼,點擊保存,將文件保存在數據所在的文件夾
4、導入pandas包,利用其讀取Excel。導入numpy包,利用設定數據類型。導入sklearn.neural_network包,利用其MLPClassifier函數
1.import pandas # for reading excel data
2.import numpy # set data as integer
3.from sklearn.neural_network import MLPClassifier # for the modelfit
5、利用pandas.read_excel讀取Excel,提示FileNotFoundError: [Errno 2] No such file or directory:'DataForThesis.xlsx',這是因為Spyder重啟后,路徑不再是文件所在位置,需要在路徑欄調整位置
6、調整路徑后,運行pandas.read_excel,設定為無變量名稱,變量df出現在Variableexplorer欄中。252行14列,對應14個變量和采集的252個數據
1.import pandas #for excel reading
2.import numpy # for type transfer
3.import sklearn #for PCA and scale
4.
5.df = pandas.read_excel("bodyfat_dataset.xlsx",header=None)
6.
7、選定訓練數據和測試數據。需要特別說明的是numpy.int_(),她將提取的變量設定為整數,否則模型無法訓練
1.import pandas #for excel reading
2.import numpy # for type transfer
3.import sklearn #for PCA and scale
4.
5.df = pandas.read_excel("bodyfat_dataset.xlsx",header=None)
6.
7.data_train_x = numpy.int_(df.iloc[0:251,0:13])
8.data_train_y = numpy.int_(df.iloc[0:251,13])
9.data_test_x = numpy.int_(df.iloc[251,0:13])
10.data_test_y = numpy.int_(df.iloc[251,13])
11.
進行BP神經網絡建模
數據錄入完成后,繼續輸入代碼
1、直接提用sklearn.neural_network下的MLPClassifier函數,建立模型,同時設定隱含層有20個神經元,傳遞函數函數為Sigmoid函數。利用mlp.fit訓練模型
1.import pandas #for excel reading
2.import numpy # for type transfer
3.import sklearn #for PCA and scale
4.
5.df = pandas.read_excel("bodyfat_dataset.xlsx",header=None)
6.
7.data_train_x = numpy.int_(df.iloc[0:251,0:13])
8.data_train_y = numpy.int_(df.iloc[0:251,13])
9.data_test_x = numpy.int_(df.iloc[251,0:13])
10.data_test_y = numpy.int_(df.iloc[251,13])
11.
12.mlp =MLPClassifier(hidden_layer_sizes=(20),activation=('logistic'))
13.mlp.fit(data_train_x,data_train_y)
14.
2、對模型進行測試,并求得預測值與目標值的偏差
1.import pandas #for excel reading
2.import numpy # for type transfer
3.import sklearn #for PCA and scale
4.
5.df = pandas.read_excel("bodyfat_dataset.xlsx",header=None)
6.
7.data_train_x = numpy.int_(df.iloc[0:251,0:13])
8.data_train_y = numpy.int_(df.iloc[0:251,13])
9.data_test_x = numpy.int_(df.iloc[251,0:13])
10.data_test_y = numpy.int_(df.iloc[251,13])
11.
12.mlp =MLPClassifier(hidden_layer_sizes=(20),activation=('logistic'))
13.mlp.fit(data_train_x,data_train_y)
14.
15.print(mlp.predict(data_test_x)-data_test_y)
16.
總結
以上是生活随笔為你收集整理的bp神经网络预测模型python_BP神经网络模型:Python的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 根据相机内参进行图像去畸变
- 下一篇: python安装汉化插件及翻译插件