1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 深度学习案例分享 | 房价预测 - PyTorch 实现

深度学习案例分享 | 房价预测 - PyTorch 实现

时间:2023-01-05 19:12:57

相关推荐

深度学习案例分享 | 房价预测 - PyTorch 实现

原文链接

大家好,我是小寒。

今天来分享一个真实的 Kaggle ⽐赛案例:预测房价。此数据集由 Bart DeCock 于 年收集,涵盖了- 年期间亚利桑那州埃姆斯市的房价。

读取数据集

数据分为训练集和测试集。每条记录包括了房屋的属性,如街道类型、施⼯年份、屋顶类型、地下室状况等。这些特征由各种数据类型组成。

我们使⽤pandas分别加载包含训练数据和测试数据的两个 CSV ⽂件。

train_data = pd.read_csv("../data/kaggle_house_pred_train.csv")test_data = pd.read_csv("../data/kaggle_house_pred_test.csv")

让我们看看前四个和最后两个特征,以及相应标签(房价)。

print(train_data.iloc[0:4, [0, 1, 2, 3, -3, -2, -1]])

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qhJcXfer-1660285359822)(https://p3-/tos-cn-i-k3u1fbpfcp/7d065713a75c4730bfd4f650fead8cb6~tplv-k3u1fbpfcp-zoom-1.image)]

我们可以看到,在每个样本中,第⼀个特征是 ID,这有助于模型识别每个训练样本。虽然这很⽅便,但它不携带任何⽤于预测的信息。因此,在将数据提供给模型之前,我们将其从数据集中删除。

all_features = pd.concat((train_data.iloc[:, 1:-1], test_data.iloc[:, 1:]))

数据预处理

在开始建模之前,我们需要对数据进⾏预处理。

⾸先,我们将所有缺失的值替换为相应特征的平均值。然后,为了将所有特征放在⼀个共同的尺度上,我们将特征重新缩放到零均值和单位⽅差来标准化数据。

# 若⽆法获得测试数据,则可根据训练数据计算均值和标准差numeric_features = all_features.dtypes[all_features.dtypes != 'object'].indexall_features[numeric_features] = all_features[numeric_features].apply(lambda x: (x - x.mean()) / (x.std()))# 在标准化数据之后,所有均值消失,因此我们可以将缺失值设置为0all_features[numeric_features] = all_features[numeric_features].fillna(0)

接下来,我们处理离散值。这里使用独热编码替换它们。

# “Dummy_na=True”将“na”(缺失值)视为有效的特征值,并为其创建指⽰符特征all_features = pd.get_dummies(all_features, dummy_na=True)

最后转换为张量格式,以便进行下一步的训练步骤。

#训练集的样本个数n_train = train_data.shape[0]#获取训练集和测试集train_features = torch.tensor(all_features[:n_train].values, dtype=torch.float32)test_features = torch.tensor(all_features[n_train:].values, dtype=torch.float32)#训练集对应的标签train_labels = torch.tensor(train_data.SalePrice.values.reshape(-1, 1), dtype=torch.float32)

模型架构

我们这里使用最简单的线性回归模型来预估房屋的价格。它的模型结构如下图所示。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l19G69Rk-1660285359823)(https://p3-/tos-cn-i-k3u1fbpfcp/faa4b232bb3a4388a0adf22d4af9f345~tplv-k3u1fbpfcp-zoom-1.image)]

线性回归也可以看做是一个单层的神经网络,我们在 Pytorch 定义一个线性回归模型。

def get_net():net = nn.Sequential(nn.Linear(in_features,1))return net

训练

房价就像股票价格⼀样,我们关⼼的是相对数量,⽽不是绝对数量。因此,我们更关⼼相对误差 (y - yˆ)/ y,⽽不是绝对误差 y - yˆ。例如,如果我们在俄亥俄州农村地区估计⼀栋房⼦的价格时,假设我们的预测,偏差了10万美元,然⽽那⾥⼀栋典型的房⼦的价值是12.5万美元,那么模型可能做得很糟糕。

另⼀⽅⾯,如果我们在加州豪宅区的预测出现同样的10 万美元的偏差,(在那⾥,房价中位数超过400万美元)这可能是⼀个不错的预测。

解决这个问题的⼀种⽅法是⽤价格预测的对数来衡量差异。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-u7aol3OF-1660285359824)(https://p3-/tos-cn-i-k3u1fbpfcp/09d24831870e408f872a67a0a91332e9~tplv-k3u1fbpfcp-zoom-1.image)]

def log_rmse(net, features, labels):#为了在取对数时进⼀步稳定该值,将⼩于1的值设置为1clipped_preds = torch.clamp(net(features), 1, float('inf'))rmse = torch.sqrt(loss(torch.log(clipped_preds),torch.log(labels)))return rmse.item()

我们这里使用 Adam 优化器进行优化。Adam优化器的主要吸引⼒在于它对初始学习率不那么敏感。

def train(net, train_features, train_labels, test_features, test_labels,num_epochs, learning_rate, weight_decay, batch_size):train_ls, test_ls = [], []train_iter = load_array((train_features, train_labels), batch_size)# 这⾥使⽤的是Adam优化算法optimizer = torch.optim.Adam(net.parameters(),lr = learning_rate,weight_decay = weight_decay)for epoch in range(num_epochs):for X, y in train_iter:optimizer.zero_grad()l = loss(net(X), y)l.backward()optimizer.step()train_ls.append(log_rmse(net, train_features, train_labels))if test_labels is not None:test_ls.append(log_rmse(net, test_features, test_labels))return train_ls, test_ls

K折交叉验证

使用 K 折交叉验证,它有助于模型选择和超参数调整。

我们⾸先需要定义⼀个函数,在K折交叉验证过程中返回第i折的数据。

def get_k_fold_data(k, i, X, y):fold_size = X.shape[0] // kX_train, y_train = None, Nonefor j in range(k):idx = slice(j * fold_size, (j + 1) * fold_size)X_part, y_part = X[idx, :], y[idx]if j == i:X_valid, y_valid = X_part, y_partelif X_train is None:X_train, y_train = X_part, y_partelse:X_train = torch.cat([X_train, X_part], 0)y_train = torch.cat([y_train, y_part], 0)return X_train, y_train, X_valid, y_valid

当我们在K折交叉验证中训练K次后,返回训练和验证误差的平均值。

def k_fold(k, X_train, y_train, num_epochs, learning_rate, weight_decay,batch_size):train_l_sum, valid_l_sum = 0, 0for i in range(k):data = get_k_fold_data(k, i, X_train, y_train)net = get_net()train_ls, valid_ls = train(net, *data, num_epochs, learning_rate,weight_decay, batch_size)train_l_sum += train_ls[-1]valid_l_sum += valid_ls[-1]print(f'折{i + 1},训练 log rmse{float(train_ls[-1]):f}, ' f'验证log rmse{float(valid_ls[-1]):f}')return train_l_sum / k, valid_l_sum / k

模型选择

我们这里只是给出了⼀组未调优的超参数。

你可以多选择一些超参数,然后进行调优,选择一组误差最小的超参数。

k, num_epochs, lr, weight_decay, batch_size = 5, 100, 5, 0, 64train_l, valid_l = k_fold(k, train_features, train_labels, num_epochs, lr,weight_decay, batch_size)print(f'{k}-折验证: 平均训练log rmse: {float(train_l):f}, ' f'平均验证log rmse: {float(valid_l):f}')

进行训练和预测

既然我们知道应该选择什么样的超参数,我们不妨使⽤所有数据对其进⾏训练(⽽不是仅使⽤交叉验证中使⽤的 1 - 1/K 的数据)。

然后,我们通过这种⽅式获得的模型可以应⽤于测试集。

def train_and_pred(train_features, test_features, train_labels, test_data,num_epochs, lr, weight_decay, batch_size):net = get_net()train_ls, _ = train(net, train_features, train_labels, None, None,num_epochs, lr, weight_decay, batch_size)plt.plot(np.arange(1, num_epochs + 1), train_ls)plt.xlabel('epoch')plt.ylabel('log rmse')plt.yscale('log')plt.show()print(f'训练log rmse:{float(train_ls[-1]):f}')# 将⽹络应⽤于测试集。preds = net(test_features).detach().numpy()print(preds)train_and_pred(train_features, test_features, train_labels, test_data,num_epochs, lr, weight_decay, batch_size)

损失变化如下图所示。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Sf40O4mR-1660285359825)(https://p3-/tos-cn-i-k3u1fbpfcp/fa04fd8ac5104feda815527265cc1f83~tplv-k3u1fbpfcp-zoom-1.image)]

最后

今天简单介绍了一个如何用 Pytorch 训练一个简单的房价预测。

如果需要完整代码+数据集

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。