excel学习库

excel表格_excel函数公式大全_execl从入门到精通

基于Python TensorFlow keras.Sequential的深度学习神经网络代码

1 写在前面

tf.estimatorKerastf.estimatorKerasKeras

直接下载

相关版本信息:

Python版本:3.8.5

TensorFlow版本:2.4.1

编译器版本:Spyder 4.1.5

2 代码分解介绍

2.1 准备工作

首先需要引入相关的库与包。

 1import
2import
3import
4importas
5importas
6importas
7importas
8importas
9importas
10fromimport
11fromimport
12fromimport
13fromimport
14fromimport
15fromimport

NumPy

14True

precisionsuppress

2.2 参数配置

深度学习代码一大特点即为具有较多的参数需要我们手动定义。为避免调参时上下翻找,我们可以将主要的参数集中在一起,方便我们后期调整。
其中,具体参数的含义在本文后续部分详细介绍。

 1# Input parameters.
2"G:/CropYield/03_DL/00_Data/AllDataAll.csv"
3"G:/CropYield/03_DL/02_DNNModle"
4"G:/CropYield/03_DL/02_DNNModle/Weights"
5"/Weights_{epoch:03d}_{val_loss:.4f}.hdf5"
6"G:/CropYield/03_DL/03_OtherResult/ParameterResult.xlsx"
70.8
82122
9'val_loss'
106412825651251210241024
110.0001
12'relu'
130.50.50.50.30.30.30.2
14'linear'
15'mean_absolute_error'
160.005
170.0005
18500
199999
200.2
21'adam'

2.3 数据导入与数据划分

pd.read_csv

Yield

 1# Fetch and divide data.
2'EVI0610''EVI0626''EVI0712''EVI0728''EVI0813''EVI0829'
3'EVI0914''EVI0930''EVI1016''Lrad06''Lrad07''Lrad08'
4'Lrad09''Lrad10''Prec06''Prec07''Prec08''Prec09'
5'Prec10''Pres06''Pres07''Pres08''Pres09''Pres10'
6'SIF161''SIF177''SIF193''SIF209''SIF225''SIF241'
7'SIF257''SIF273''SIF289''Shum06''Shum07''Shum08'
8'Shum09''Shum10''SoilType''Srad06''Srad07''Srad08'
9'Srad09''Srad10''Temp06''Temp07''Temp08''Temp09'
10'Temp10''Wind06''Wind07''Wind08''Wind09''Wind10'
11'Yield'0

随后,对导入的数据划分训练集与测试集。

1
2

TrainFracRandomSeed

2.4 联合分布图绘制

seabornseabornmatplotlib

 1# Draw the joint distribution image.
2defJointDistribution(Factors)
31
4'reg''kde'
52.0
6
7
8# Draw the joint distribution image.
9'Lrad07''Prec06''SIF161''Shum06''Srad07''Srad08''Srad10''Temp06''Yield'
10

JointFactorJointDistributionkind'reg''scatter''kde''hist''reg''scatter''kde''hist'diag_kind'hist''kde''hist''kde'font_scaleJointDistributionTrainData

图片绘制的示例如下:

要注意,绘制联合分布图比较慢,建议大家不要选取太多的变量,否则程序会卡在这里比较长的时间。

2.5 因变量分离与数据标准化

因变量分离我们就不再多解释啦;接下来,我们要知道,对于机器学习、深度学习而言,数据标准化是十分重要的——用官网所举的一个例子:不同的特征在神经网络中会乘以相同的权重weight,因此输入数据的尺度(即数据不同特征之间的大小关系)将会影响到输出数据与梯度的尺度;因此,数据标准化可以使得模型更加稳定。

在这里,首先说明数据标准化与归一化的区别。

标准化即将训练集中某列的值缩放成均值为0,方差为1的状态;而归一化是将训练集中某列的值缩放到0和1之间。而在机器学习中,标准化较之归一化通常具有更高的使用频率,且标准化后的数据在神经网络训练时,其收敛将会更快。

最后,一定要记得——标准化时只需要对训练集数据加以处理,不要把测试集Test的数据引入了!因为标准化只需要对训练数据加以处理,引入测试集反而会影响标准化的作用。

1# Separate independent and dependent variables.
2True
3True
4'Yield'
5'Yield'
6
7# Standardization data.
8
9

在这里,我们直接运用preprocessing.Normalization()建立一个预处理层,其具有数据标准化的功能;随后,通过.adapt()函数将需要标准化的数据(即训练集的自变量)放入这一层,便可以实现数据的标准化操作。

2.6 原有模型删除

我们的程序每执行一次,便会在指定路径中保存当前运行的模型。为保证下一次模型保存时不受上一次模型运行结果干扰,我们可以将模型文件夹内的全部文件删除。

 1# Delete the model result from the last run.
2defDeleteOldModel(ModelPath)
3
4forin
5
6if
7
8else
9
10
11# Delete the model result from the last run.
12

这里

2.7 最优Epoch保存与读取

在我们训练模型的过程中,会让模型运行几百个Epoch(一个Epoch即全部训练集数据样本均进入模型训练一次);而由于每一次的Epoch所得到的精度都不一样,那么我们自然需要挑出几百个Epoch中最优秀的那一个Epoch。

 1# Find and save optimal epoch.
2defCheckPoint(Name)
3
4
51
6True
7'auto'
8
9return
10
11# Find and save optimal epochs.
12

Namemonitorverbose1save_best_onlymodemonitormonitor'auto''min''auto'monitor

CallBack

2.8 模型构建

Keras博客

 1# Build DNN model.
2defBuildModel(Norm)
3# 数据标准化层
4
50# 指定隐藏层1的神经元个数
6# 运用L2正则化
7# activation=ActivationMethod
8
9# 引入LeakyReLU这一改良的ReLU激活函数,从而加快模型收敛,减少过拟合
10# 引入Batch Normalizing,加快网络收敛与增强网络稳固性
110# 指定隐藏层1的Dropout值
12
131
14
15# activation=ActivationMethod
16
17
18
191
20
212
22
23# activation=ActivationMethod
24
25
26
272
28
293
30
31# activation=ActivationMethod
32
33
34
353
36
374
38
39# activation=ActivationMethod
40
41
42
434
44
455
46
47# activation=ActivationMethod
48
49
50
515
52
536
54
55# activation=ActivationMethod
56
57
58# If batch normalization is set in the last hidden layer, the error image
59# will show a trend of first stable and then decline; otherwise, it will
60# decline and then stable.
61# layers.BatchNormalization(),
626
63
641
65# 最后一层就是输出层
66# 指定每个批次训练误差的减小方法
67
68# 运用学习率下降的优化方法
69return
70
71# Build DNN regression model.
72
73
74
75
76
77# batch_size=BatchSize,
781
79
80

.summary()validation_splitValFracDNNHistory

2.9 训练图像绘制

机器学习中,过拟合是影响训练精度的重要因素。因此,我们最好在训练模型的过程中绘制训练数据、验证数据的误差变化图象,从而更好获取模型的训练情况。

 1# Draw error image.
2defLossPlot(History)
32
4'loss''loss'
5'val_loss''val_loss'
604000
7'Epoch'
8'Error'
9
10True
11
12# Draw error image.
13

'loss''val_loss'

2.10 最优Epoch选取

前面提到了,我们将多个符合要求的Epoch保存在了指定的路径下,那么最终我们可以从中选取最好的那个Epoch,作为模型的最终参数,从而对测试集数据加以预测。那么在这里,我们需要将这一全局最优Epoch选取出,并带入到最终的模型里。

 1# Optimize the model based on optimal epoch.
2defBestEpochIntoModel(Path,Model)
3'/*'
4
5
6
7
8return
9
10# Optimize the model based on optimal epoch.
11

os.path.getmtimeload_weights

2.11 模型测试、拟合图像绘制、精度验证与模型参数与结果保存

博客

 1# Draw Test image.
2defTestPlot(TestY,TestPrediction)
33
4'equal'
5
6'True Values'
7'Predictions'
8010000
9
10
11
12False
13
14# Verify the accuracy and draw error hist image.
15defAccuracyVerification(TestY,TestPrediction)
16
174
1830
19'Prediction Error'
20'Count'
21False
22
23
240.5
25'Pearson correlation coefficient is {0}, and RMSE is {1}.'0
26return0
27
28# Save key parameters.
29defWriteAccuracy(*WriteVar)
300
31
320
33
34
35forin-1
36"WriteSheet.cell(MaxRowNum+1,i+1).value=WriteVar[i+1]"
370
38
39# Predict test set data.
40
41
42# Draw Test image.
43
44
45# Verify the accuracy and draw error hist image.
46
47012
48
49# Save model and key parameters.
50
51
52',''%s'forin
53',''%s'forin
54

得到拟合图像如下:

得到误差分布直方图如下:

至此,代码的分解介绍就结束啦~

3 完整代码

  1# -*- coding: utf-8 -*-
2
3
4
5
6

7
8import
9import
10import
11importas
12importas
13importas
14importas
15importas
16importas
17fromimport
18fromimport
19fromimport
20fromimport
21fromimport
22fromimport
23
244True
25
26# Draw the joint distribution image.
27defJointDistribution(Factors)
281
29'reg''kde'
302.0
31
32
33# Delete the model result from the last run.
34defDeleteOldModel(ModelPath)
35
36forin
37
38if
39
40else
41
42
43# Find and save optimal epoch.
44defCheckPoint(Name)
45
46
471
48True
49'auto'
50
51return
52
53# Build DNN model.
54defBuildModel(Norm)
55# 数据标准化层
56
570# 指定隐藏层1的神经元个数
58# 运用L2正则化
59# activation=ActivationMethod
60
61# 引入LeakyReLU这一改良的ReLU激活函数,从而加快模型收敛,减少过拟合
62# 引入Batch Normalizing,加快网络收敛与增强网络稳固性
630# 指定隐藏层1的Dropout值
64
651
66
67# activation=ActivationMethod
68
69
70
711
72
732
74
75# activation=ActivationMethod
76
77
78
792
80
813
82
83# activation=ActivationMethod
84
85
86
873
88
894
90
91# activation=ActivationMethod
92
93
94
954
96
975
98
99# activation=ActivationMethod
100
101
102
1035
104
1056
106
107# activation=ActivationMethod
108
109
110# If batch normalization is set in the last hidden layer, the error image
111# will show a trend of first stable and then decline; otherwise, it will
112# decline and then stable.
113# layers.BatchNormalization(),
1146
115
1161
117# 最后一层就是输出层
118# 指定每个批次训练误差的减小方法
119
120# 运用学习率下降的优化方法
121return
122
123# Draw error image.
124defLossPlot(History)
1252
126'loss''loss'
127'val_loss''val_loss'
12804000
129'Epoch'
130'Error'
131
132True
133
134# Optimize the model based on optimal epoch.
135defBestEpochIntoModel(Path,Model)
136'/*'
137
138
139
140
141return
142
143# Draw Test image.
144defTestPlot(TestY,TestPrediction)
1453
146'equal'
147
148'True Values'
149'Predictions'
150010000
151
152
153
154False
155
156# Verify the accuracy and draw error hist image.
157defAccuracyVerification(TestY,TestPrediction)
158
1594
16030
161'Prediction Error'
162'Count'
163False
164
165
1660.5
167'Pearson correlation coefficient is {0}, and RMSE is {1}.'0
168return0
169
170# Save key parameters.
171defWriteAccuracy(*WriteVar)
1720
173
1740
175
176
177forin-1
178"WriteSheet.cell(MaxRowNum+1,i+1).value=WriteVar[i+1]"
1790
180
181# Input parameters.
182"G:/CropYield/03_DL/00_Data/AllDataAll.csv"
183"G:/CropYield/03_DL/02_DNNModle"
184"G:/CropYield/03_DL/02_DNNModle/Weights"
185"/Weights_{epoch:03d}_{val_loss:.4f}.hdf5"
186"G:/CropYield/03_DL/03_OtherResult/ParameterResult.xlsx"
1870.8
1882122
189'val_loss'
1906412825651251210241024
1910.0001
192'relu'
1930.50.50.50.30.30.30.2
194'linear'
195'mean_absolute_error'
1960.005
1970.0005
198500
1999999
2000.2
201'adam'
202
203# Fetch and divide data.
204'EVI0610''EVI0626''EVI0712''EVI0728''EVI0813''EVI0829'
205'EVI0914''EVI0930''EVI1016''Lrad06''Lrad07''Lrad08'
206'Lrad09''Lrad10''Prec06''Prec07''Prec08''Prec09'
207'Prec10''Pres06''Pres07''Pres08''Pres09''Pres10'
208'SIF161''SIF177''SIF193''SIF209''SIF225''SIF241'
209'SIF257''SIF273''SIF289''Shum06''Shum07''Shum08'
210'Shum09''Shum10''SoilType''Srad06''Srad07''Srad08'
211'Srad09''Srad10''Temp06''Temp07''Temp08''Temp09'
212'Temp10''Wind06''Wind07''Wind08''Wind09''Wind10'
213'Yield'0
214
215
216
217# Draw the joint distribution image.
218# JointFactor=['Lrad07','Prec06','SIF161','Shum06','Srad07','Srad08','Srad10','Temp06','Yield']
219# JointDistribution(JointFactor)
220
221# Separate independent and dependent variables.
222True
223True
224'Yield'
225'Yield'
226
227# Standardization data.
228
229
230
231# Delete the model result from the last run.
232
233
234# Find and save optimal epochs.
235
236
237# Build DNN regression model.
238
239
240
241
242
243# batch_size=BatchSize,
2441
245
246
247
248# Draw error image.
249
250
251# Optimize the model based on optimal epoch.
252
253
254# Predict test set data.
255
256
257# Draw Test image.
258
259
260# Verify the accuracy and draw error hist image.
261
262012
263
264# Save model and key parameters.
265
266
267',''%s'forin
268',''%s'forin
269

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2024年12月    »
1
2345678
9101112131415
16171819202122
23242526272829
3031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
    文章归档
      友情链接