使用飞桨书写模型的时候,流程与前面介绍的是一摸一样的。
下面开始总结一下如何使用飞桨写模型
加载飞桨库
主库:paddle/fluid
动态图类库:digraph(便于调试)
静态图模式(声明式编程范式,类比C++) | 动态图模式 (命令式编程范式,类比Python) |
---|---|
先编译后执行的方式。用户需预先定义完整的网络结构,再对网络结构进行编译优化后,才能执行获得计算结果。 | 解析式的执行方式。用户无需预先定义完整的网络结构,每写一行网络代码,即可同时获得计算结果。 |
全连接层:Linear(可激活指定性函数)
数据处理
此部分包括数据导入、修改格式、分为训练测试集、数据归一化处理。
在飞桨中书写与前面完全一致。
模型设计
实质为定义线性回归的结构。
需要用到两种函数,init函数和forward函数。
init | forward |
---|---|
在类的初始化函数中声明每一层网络的实现函数。 | 构建神经网络结构,实现前向计算过程,并返回预测结果。 |
注:我们这里不使用激活函数
训练配置
-
定义工作环境
-
定义模型(有训练和预测状态)
模型实例有两种状态:训练状态.train()和预测状态.eval()。训练时要执行正向计算和反向传播梯度两个过程,而预测时只需要执行正向计算。为模型指定运行状态,有两点原因:
(1)部分高级的算子(例如Drop out和Batch Normalization,在计算机视觉的章节会详细介绍)在两个状态执行的逻辑不同。
(2)从性能和存储空间的考虑,预测状态时更节省内存,性能更好。 -
开启训练模式
-
读取数据
-
定义优化算法SDG,定义学习率0.01
-
开始训练
双层循环+四个步骤
(先将数据格式写为numpy.array格式) -
保存模型
先保存,加载,再进行测试。因为模型可以应用到不同的场景。 -
加载模型,进行预测
(1)生产模型实例,配置资源。
(2)加载模型参数,设置模型状态为“eval”(因为预测时,不需要反向传播梯度)
(3)调用模型,打印预测值与真实值
总结:编写成本大降低
感悟:飞桨提供了一个深度学习框架,可以达到事半功倍的效果。学习这一章之后其实我能够发现代码编写过程大大的减少了,但是飞桨的一些函数的定义与调用还没有特别的清楚,在init函数和forward函数的定义上还是不够理解,需要在接下来的学习过程中,去更好的理解和了解。
下面书写一下使用飞桨重写波士顿房价预测模型
直接使用python的案例在这里:完整步骤
#加载飞桨、Numpy和相关类库
import paddle
import paddle.fluid as fluid
import paddle.fluid.dygraph as dygraph
from paddle.fluid.dygraph import Linear
import numpy as np
import os
import random
#数据处理,此部分与前面的完全一致,飞桨的优化主要在模型设计和训练配置上
def load_data():
# 从文件导入数据
datafile = './work/housing.data'
data = np.fromfile(datafile, sep=' ')
<span class="token comment"># 每条数据包括14项,其中前面13项是影响因素,第14项是相应的房屋价格中位数</span>
feature_names <span class="token operator">=</span> <span class="token punctuation">[</span> <span class="token string">'CRIM'</span><span class="token punctuation">,</span> <span class="token string">'ZN'</span><span class="token punctuation">,</span> <span class="token string">'INDUS'</span><span class="token punctuation">,</span> <span class="token string">'CHAS'</span><span class="token punctuation">,</span> <span class="token string">'NOX'</span><span class="token punctuation">,</span> <span class="token string">'RM'</span><span class="token punctuation">,</span> <span class="token string">'AGE'</span><span class="token punctuation">,</span> \
<span class="token string">'DIS'</span><span class="token punctuation">,</span> <span class="token string">'RAD'</span><span class="token punctuation">,</span> <span class="token string">'TAX'</span><span class="token punctuation">,</span> <span class="token string">'PTRATIO'</span><span class="token punctuation">,</span> <span class="token string">'B'</span><span class="token punctuation">,</span> <span class="token string">'LSTAT'</span><span class="token punctuation">,</span> <span class="token string">'MEDV'</span> <span class="token punctuation">]</span>
feature_num <span class="token operator">=</span> <span class="token builtin">len</span><span class="token punctuation">(</span>feature_names<span class="token punctuation">)</span>
<span class="token comment"># 将原始数据进行Reshape,变成[N, 14]这样的形状</span>
data <span class="token operator">=</span> data<span class="token punctuation">.</span>reshape<span class="token punctuation">(</span><span class="token punctuation">[</span>data<span class="token punctuation">.</span>shape<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">//</span> feature_num<span class="token punctuation">,</span> feature_num<span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token comment"># 将原数据集拆分成训练集和测试集</span>
<span class="token comment"># 这里使用80%的数据做训练,20%的数据做测试</span>
<span class="token comment"># 测试集和训练集必须是没有交集的</span>
ratio <span class="token operator">=</span> <span class="token number">0.8</span>
offset <span class="token operator">=</span> <span class="token builtin">int</span><span class="token punctuation">(</span>data<span class="token punctuation">.</span>shape<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">*</span> ratio<span class="token punctuation">)</span>
training_data <span class="token operator">=</span> data<span class="token punctuation">[</span><span class="token punctuation">:</span>offset<span class="token punctuation">]</span>
<span class="token comment"># 计算train数据集的最大值,最小值,平均值</span>
maximums<span class="token punctuation">,</span> minimums<span class="token punctuation">,</span> avgs <span class="token operator">=</span> training_data<span class="token punctuation">.</span><span class="token builtin">max</span><span class="token punctuation">(</span>axis<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">,</span> training_data<span class="token punctuation">.</span><span class="token builtin">min</span><span class="token punctuation">(</span>axis<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">,</span> \
training_data<span class="token punctuation">.</span><span class="token builtin">sum</span><span class="token punctuation">(</span>axis<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">/</span> training_data<span class="token punctuation">.</span>shape<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>
<span class="token comment"># 记录数据的归一化参数,在预测时对数据做归一化</span>
<span class="token keyword">global</span> max_values
<span class="token keyword">global</span> min_values
<span class="token keyword">global</span> avg_values
max_values <span class="token operator">=</span> maximums
min_values <span class="token operator">=</span> minimums
avg_values <span class="token operator">=</span> avgs
<span class="token comment"># 对数据进行归一化处理</span>
<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span>feature_num<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token comment">#print(maximums[i], minimums[i], avgs[i])</span>
data<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token punctuation">,</span> i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">(</span>data<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token punctuation">,</span> i<span class="token punctuation">]</span> <span class="token operator">-</span> avgs<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token punctuation">(</span>maximums<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">-</span> minimums<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token comment"># 训练集和测试集的划分比例</span>
<span class="token comment">#ratio = 0.8</span>
<span class="token comment">#offset = int(data.shape[0] * ratio)</span>
training_data <span class="token operator">=</span> data<span class="token punctuation">[</span><span class="token punctuation">:</span>offset<span class="token punctuation">]</span>
test_data <span class="token operator">=</span> data<span class="token punctuation">[</span>offset<span class="token punctuation">:</span><span class="token punctuation">]</span>
<span class="token keyword">return</span> training_data<span class="token punctuation">,</span> test_data
#定义线性回归模型
class Regressor(fluid.dygraph.Layer):
def init(self):
super(Regressor, self).init()
#调用父类的函数init
# 定义一层全连接层,输出维度是1,激活函数为None,即不使用激活函数
self.fc = Linear(input_dim=13, output_dim=1, act=None)
<span class="token comment"># 网络的前向计算函数</span>
<span class="token keyword">def</span> <span class="token function">forward</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> inputs<span class="token punctuation">)</span><span class="token punctuation">:</span>
x <span class="token operator">=</span> self<span class="token punctuation">.</span>fc<span class="token punctuation">(</span>inputs<span class="token punctuation">)</span>
<span class="token keyword">return</span> x
# 定义飞桨动态图的工作环境
with fluid.dygraph.guard():
# 声明定义好的线性回归模型
model = Regressor()
# 开启模型训练模式
model.train()
# 加载数据
training_data, test_data = load_data()
# 定义优化算法,这里使用随机梯度下降-SGD
# 学习率设置为0.01
opt = fluid.optimizer.SGD(learning_rate=0.01, parameter_list=model.parameters())
with dygraph.guard(fluid.CPUPlace()):
EPOCH_NUM = 10 # 设置外层循环次数
BATCH_SIZE = 10 # 设置batch大小
<span class="token comment"># 定义外层循环</span>
<span class="token keyword">for</span> epoch_id <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span>EPOCH_NUM<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token comment"># 在每轮迭代开始之前,将训练数据的顺序随机的打乱</span>
np<span class="token punctuation">.</span>random<span class="token punctuation">.</span>shuffle<span class="token punctuation">(</span>training_data<span class="token punctuation">)</span>
<span class="token comment"># 将训练数据进行拆分,每个batch包含10条数据</span>
mini_batches <span class="token operator">=</span> <span class="token punctuation">[</span>training_data<span class="token punctuation">[</span>k<span class="token punctuation">:</span>k<span class="token operator">+</span>BATCH_SIZE<span class="token punctuation">]</span> <span class="token keyword">for</span> k <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token builtin">len</span><span class="token punctuation">(</span>training_data<span class="token punctuation">)</span><span class="token punctuation">,</span> BATCH_SIZE<span class="token punctuation">)</span><span class="token punctuation">]</span>
<span class="token comment"># 定义内层循环</span>
<span class="token keyword">for</span> iter_id<span class="token punctuation">,</span> mini_batch <span class="token keyword">in</span> <span class="token builtin">enumerate</span><span class="token punctuation">(</span>mini_batches<span class="token punctuation">)</span><span class="token punctuation">:</span>
x <span class="token operator">=</span> np<span class="token punctuation">.</span>array<span class="token punctuation">(</span>mini_batch<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token punctuation">,</span> <span class="token punctuation">:</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">.</span>astype<span class="token punctuation">(</span><span class="token string">'float32'</span><span class="token punctuation">)</span> <span class="token comment"># 获得当前批次训练数据</span>
y <span class="token operator">=</span> np<span class="token punctuation">.</span>array<span class="token punctuation">(</span>mini_batch<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">.</span>astype<span class="token punctuation">(</span><span class="token string">'float32'</span><span class="token punctuation">)</span> <span class="token comment"># 获得当前批次训练标签(真实房价)</span>
<span class="token comment"># 将numpy数据转为飞桨动态图variable形式</span>
house_features <span class="token operator">=</span> dygraph<span class="token punctuation">.</span>to_variable<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
prices <span class="token operator">=</span> dygraph<span class="token punctuation">.</span>to_variable<span class="token punctuation">(</span>y<span class="token punctuation">)</span>
<span class="token comment"># 前向计算</span>
predicts <span class="token operator">=</span> model<span class="token punctuation">(</span>house_features<span class="token punctuation">)</span>
<span class="token comment"># 计算损失</span>
loss <span class="token operator">=</span> fluid<span class="token punctuation">.</span>layers<span class="token punctuation">.</span>square_error_cost<span class="token punctuation">(</span>predicts<span class="token punctuation">,</span> label<span class="token operator">=</span>prices<span class="token punctuation">)</span>
avg_loss <span class="token operator">=</span> fluid<span class="token punctuation">.</span>layers<span class="token punctuation">.</span>mean<span class="token punctuation">(</span>loss<span class="token punctuation">)</span>
<span class="token keyword">if</span> iter_id<span class="token operator">%</span><span class="token number">20</span><span class="token operator">==</span><span class="token number">0</span><span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"epoch: {}, iter: {}, loss is: {}"</span><span class="token punctuation">.</span><span class="token builtin">format</span><span class="token punctuation">(</span>epoch_id<span class="token punctuation">,</span> iter_id<span class="token punctuation">,</span> avg_loss<span class="token punctuation">.</span>numpy<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token comment"># 反向传播</span>
avg_loss<span class="token punctuation">.</span>backward<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment"># 最小化loss,更新参数</span>
opt<span class="token punctuation">.</span>minimize<span class="token punctuation">(</span>avg_loss<span class="token punctuation">)</span>
<span class="token comment"># 清除梯度</span>
model<span class="token punctuation">.</span>clear_gradients<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment"># 保存模型</span>
fluid<span class="token punctuation">.</span>save_dygraph<span class="token punctuation">(</span>model<span class="token punctuation">.</span>state_dict<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">'LR_model'</span><span class="token punctuation">)</span>
# 定义飞桨动态图工作环境
with fluid.dygraph.guard():
# 保存模型参数,文件名为LR_model
fluid.save_dygraph(model.state_dict(), 'LR_model')
print("模型保存成功,模型参数保存在LR_model中")
#测试模型
def load_one_example(data_dir):
f = open(data_dir, 'r')
datas = f.readlines()
# 选择倒数第10条数据用于测试
tmp = datas[-10]
tmp = tmp.strip().split()
one_data = [float(v) for v in tmp]
<span class="token comment"># 对数据进行归一化处理</span>
<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token builtin">len</span><span class="token punctuation">(</span>one_data<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
one_data<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">(</span>one_data<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">-</span> avg_values<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token punctuation">(</span>max_values<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">-</span> min_values<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
data <span class="token operator">=</span> np<span class="token punctuation">.</span>reshape<span class="token punctuation">(</span>np<span class="token punctuation">.</span>array<span class="token punctuation">(</span>one_data<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">.</span>astype<span class="token punctuation">(</span>np<span class="token punctuation">.</span>float32<span class="token punctuation">)</span>
label <span class="token operator">=</span> one_data<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span>
<span class="token keyword">return</span> data<span class="token punctuation">,</span> label
with dygraph.guard():
# 参数为保存模型参数的文件地址
model_dict, _ = fluid.load_dygraph('LR_model')
model.load_dict(model_dict)
model.eval()
<span class="token comment"># 参数为数据集的文件地址</span>
test_data<span class="token punctuation">,</span> label <span class="token operator">=</span> load_one_example<span class="token punctuation">(</span><span class="token string">'./work/housing.data'</span><span class="token punctuation">)</span>
<span class="token comment"># 将数据转为动态图的variable格式</span>
test_data <span class="token operator">=</span> dygraph<span class="token punctuation">.</span>to_variable<span class="token punctuation">(</span>test_data<span class="token punctuation">)</span>
results <span class="token operator">=</span> model<span class="token punctuation">(</span>test_data<span class="token punctuation">)</span>
<span class="token comment"># 对结果做反归一化处理</span>
results <span class="token operator">=</span> results <span class="token operator">*</span> <span class="token punctuation">(</span>max_values<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">-</span> min_values<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">+</span> avg_values<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Inference result is {}, the corresponding label is {}"</span><span class="token punctuation">.</span><span class="token builtin">format</span><span class="token punctuation">(</span>results<span class="token punctuation">.</span>numpy<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> label<span class="token punctuation">)</span><span class="token punctuation">)</span>