本文主要是介绍飞桨AI Studio进行波士顿房价预测,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import paddle
from paddle.nn import Linear
import paddle.nn.functional as F
import numpy as np
import os
import randomdef load_data():# 导入数据datafile = '/home/aistudio/data/data95203/housing.data'data = np.fromfile(datafile, sep=' ', dtype=np.float32)# 每条数据包括14项,前面13项是影响因素,第14项是相应的房屋价格中位数feature_names = [ 'CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', \'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV' ]feature_num = len(feature_names)# 将原始数据进行Reshape,变成[N, 14]这样的形状data = data.reshape([data.shape[0] // feature_num, feature_num])# 将原数据集拆分成训练集和测试集# 这里使用80%的数据做训练,20%的数据做测试# 测试集和训练集必须是没有交集的ratio = 0.8offset = int(data.shape[0] * ratio)training_data = data[:offset]# 计算train数据集的最大值,最小值,平均值maximums, minimums, avgs = training_data.max(axis=0), training_data.min(axis=0), \training_data.sum(axis=0) / training_data.shape[0]# 记录数据的归一化参数,在预测时对数据做归一化global max_valuesglobal min_valuesglobal avg_valuesmax_values = maximumsmin_values = minimumsavg_values = avgs# 对数据进行归一化处理for i in range(feature_num):data[:, i] = (data[:, i] - avgs[i]) / (maximums[i] - minimums[i])# 训练集和测试集的划分比例training_data = data[:offset]test_data = data[offset:]return training_data, test_dataclass Regressor(paddle.nn.Layer):# self代表类的实例自身def __init__(self):# 初始化父类中的一些参数super(Regressor, self).__init__()# 定义一层全连接层,输入维度是13,输出维度是1self.fc = Linear(in_features=13, out_features=1)# 网络的前向计算def forward(self, inputs):x = self.fc(inputs)return x# 声明定义好的线性回归模型
model = Regressor()
# 开启模型训练模式
model.train()
# 加载数据
training_data, test_data = load_data()
# 定义优化算法,使用随机梯度下降SGD
# 学习率设置为0.01
opt = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters())EPOCH_NUM = 10 # 设置外层循环次数
BATCH_SIZE = 10 # 设置batch大小# 定义外层循环
for epoch_id in range(EPOCH_NUM):# 在每轮迭代开始之前,将训练数据的顺序随机的打乱np.random.shuffle(training_data)# 将训练数据进行拆分,每个batch包含10条数据mini_batches = [training_data[k:k+BATCH_SIZE] for k in range(0, len(training_data), BATCH_SIZE)]# 定义内层循环for iter_id, mini_batch in enumerate(mini_batches):x = np.array(mini_batch[:, :-1]) # 获得当前批次训练数据y = np.array(mini_batch[:, -1:]) # 获得当前批次训练标签(真实房价)# 将numpy数据转为飞桨动态图tensor形式house_features = paddle.to_tensor(x)prices = paddle.to_tensor(y)# 前向计算predicts = model(house_features)# 计算损失loss = F.square_error_cost(predicts, label=prices)avg_loss = paddle.mean(loss)if iter_id%20==0:print("epoch: {}, iter: {}, loss is: {}".format(epoch_id, iter_id, avg_loss.numpy()))# 反向传播avg_loss.backward()# 最小化loss,更新参数opt.step()# 清除梯度opt.clear_grad()paddle.save(model.state_dict(), 'LR_model.pdparams')
print("模型保存成功,模型参数保存在LR_model.pdparams中")def load_one_example():# 从上边已加载的测试集中,随机选择一条作为测试数据idx = np.random.randint(0, test_data.shape[0])idx = -10one_data, label = test_data[idx, :-1], test_data[idx, -1]# 修改该条数据shape为[1,13]one_data = one_data.reshape([1,-1])return one_data, label
# 参数为保存模型参数的文件地址
model_dict = paddle.load('LR_model.pdparams')
model.load_dict(model_dict)
model.eval()# 参数为数据集的文件地址
one_data, label = load_one_example()
# 将数据转为动态图的variable格式
one_data = paddle.to_tensor(one_data)
predict = model(one_data)# 对结果做反归一化处理
predict = predict * (max_values[-1] - min_values[-1]) + avg_values[-1]
# 对label数据做反归一化处理
label = label * (max_values[-1] - min_values[-1]) + avg_values[-1]print("Inference result is {}, the corresponding label is {}".format(predict.numpy(), label))
epoch: 0, iter: 0, loss is: [0.20064382]
epoch: 0, iter: 20, loss is: [0.57066244]
epoch: 0, iter: 40, loss is: [0.1300517]
epoch: 1, iter: 0, loss is: [0.15635166]
epoch: 1, iter: 20, loss is: [0.05035155]
epoch: 1, iter: 40, loss is: [0.11730953]
epoch: 2, iter: 0, loss is: [0.43430847]
epoch: 2, iter: 20, loss is: [0.05606089]
epoch: 2, iter: 40, loss is: [0.06443227]
epoch: 3, iter: 0, loss is: [0.14527342]
epoch: 3, iter: 20, loss is: [0.10418153]
epoch: 3, iter: 40, loss is: [0.09481782]
epoch: 4, iter: 0, loss is: [0.02241812]
epoch: 4, iter: 20, loss is: [0.2761887]
epoch: 4, iter: 40, loss is: [0.04885288]
epoch: 5, iter: 0, loss is: [0.03063297]
epoch: 5, iter: 20, loss is: [0.257253]
epoch: 5, iter: 40, loss is: [0.01288422]
epoch: 6, iter: 0, loss is: [0.16594654]
epoch: 6, iter: 20, loss is: [0.07751676]
epoch: 6, iter: 40, loss is: [0.00323895]
epoch: 7, iter: 0, loss is: [0.03663034]
epoch: 7, iter: 20, loss is: [0.11741225]
epoch: 7, iter: 40, loss is: [0.03940923]
epoch: 8, iter: 0, loss is: [0.06915651]
epoch: 8, iter: 20, loss is: [0.0529696]
epoch: 8, iter: 40, loss is: [0.07083032]
epoch: 9, iter: 0, loss is: [0.07428975]
epoch: 9, iter: 20, loss is: [0.05440676]
epoch: 9, iter: 40, loss is: [0.01986258]
模型保存成功,模型参数保存在LR_model.pdparams中
Inference result is [[19.797583]], the corresponding label is 19.700000762939453
通过比较“模型预测值”和“真实房价”可见,模型的预测效果与真实房价接近。房价预测仅是一个最简单的模型,使用飞桨编写均可事半功倍。那么对于工业实践中更复杂的模型,使用飞桨节约的成本是不可估量的。同时飞桨针对很多应用场景和机器资源做了性能优化,在功能和性能上远强于自行编写的模型。
这篇关于飞桨AI Studio进行波士顿房价预测的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!