也可以用飞桨的高层API来做线性回归训练,高层API相较于底层API更加的简洁方便。
# 方式2:使用高层API完成模型训练&预测
import paddle
paddle.set_default_dtype("float64")
# step1:用高层API定义数据集,无需进行数据处理等,高层API为你一条龙搞定
train_dataset = paddle.text.datasets.UCIHousing(mode='train')
eval_dataset = paddle.text.datasets.UCIHousing(mode='test')
# step2:定义模型
class UCIHousing(paddle.nn.Layer):
def __init__(self):
super(UCIHousing, self).__init__()
self.fc = paddle.nn.Linear(13, 1, None)
def forward(self, input):
pred = self.fc(input)
return pred
# step3:训练模型
model = paddle.Model(UCIHousing())
model.prepare(paddle.optimizer.Adam(parameters=model.parameters()),
paddle.nn.MSELoss())
model.fit(train_dataset, eval_dataset, epochs=5, batch_size=8, verbose=1)
运行结果
Cache file C:\Users\YANG\.cache\paddle\dataset\uci_housing\housing.data not found, downloading http://paddlemodels.bj.bcebos.com/uci_housing/housing.data
Begin to download
item 12/12 [==========================>...] - ETA: 0s - 5ms/itemThe loss value printed in the log is the current step, and the metric is the average value of previous steps.
Download finished
Epoch 1/5
step 51/51 [==============================] - loss: 617.5771 - 1ms/step
Eval begin...
step 13/13 [==============================] - loss: 381.6220 - 780us/step
Eval samples: 102
Epoch 2/5
step 51/51 [==============================] - loss: 414.8060 - 1ms/step
Eval begin...
step 13/13 [==============================] - loss: 379.1168 - 849us/step
Eval samples: 102
Epoch 3/5
step 51/51 [==============================] - loss: 415.8149 - 1ms/step
Eval begin...
step 13/13 [==============================] - loss: 376.6546 - 812us/step
Eval samples: 102
Epoch 4/5
step 51/51 [==============================] - loss: 431.1117 - 1ms/step
Eval begin...
step 13/13 [==============================] - loss: 374.2060 - 828us/step
Eval samples: 102
Epoch 5/5
step 51/51 [==============================] - loss: 458.0943 - 1ms/step
Eval begin...
step 13/13 [==============================] - loss: 371.7430 - 724us/step
Eval samples: 102
Process finished with exit code 0
可以看出,非常简便,自动下载house.data
无需你自己做数据预处理