本文介绍了运用计量统计软件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.
领取专属 10元无门槛券
私享最新 技术干货