当前位置:   article > 正文

kaggle竞赛(房价预测)(Pytorch 06)

kaggle竞赛(房价预测)(Pytorch 06)

一 下载数据集

此数据集由Bart de Cock于2011年收集,涵盖了2006‐2010年期间 亚利桑那州 埃姆斯市的房价。

下载地址:

  1. import hashlib
  2. import os
  3. import tarfile
  4. import zipfile
  5. import requests
  6. #@save
  7. DATA_HUB = dict()
  8. DATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/'

下面的download函数用来下载数据集,将数据集缓存在本地目录(默认情况下为../data)中,并返回下载文 件的名称。

  1. def download(name, cache_dir=os.path.join('..', 'data')): #@save
  2. assert name in DATA_HUB, f'{name} 不存在于{DATA_HUB}'
  3. url, shal_hash = DATA_HUB[name]
  4. os.makedirs(cache_dir, exist_ok=True)
  5. fname = os.path.join(cache_dir, url.split('/')[-1])
  6. if os.path.exists(fname):
  7. shal = hashlib.sha1()
  8. with open(fname, 'rb') as f:
  9. while True:
  10. data = f.read(1048576)
  11. if not data:
  12. break
  13. shal.update(data)
  14. if shal.hexdigest() == shal_hash:
  15. return fname
  16. print(f'正在从{url}下载{fname}...')
  17. r = requests.get(url, stream=True, verify=True)
  18. with open(fname, 'wb') as f:
  19. f.write(r.content)
  20. return fname

我们还需实现两个实用函数:一个将下载并解压缩一个zip或tar文件,另一个是将本书中使用的所有数据集 从DATA_HUB下载到缓存目录中。

  1. def download_extract(name, folder=None): #@save
  2. fname = download(name)
  3. base_dir = os.path.dirname(fname)
  4. data_dir, ext = os.path.splitext(fname)
  5. if ext == '.zip':
  6. fp = zipfile.ZipFile(fname, 'r')
  7. elif ext in ('.tar', '.gz'):
  8. fp = tarfile.open(fname, 'r')
  9. else:
  10. assert False
  11. fp.extractall(base_dir)
  12. return os.path.join(base_dir, folder) if folder else data_dir
  13. def download_all():
  14. for name in DATA_HUB:
  15. download(name)

 

二 加载数据集

竞赛数据分为训练集和测试集。每条记录都包括房屋的属性值和属性,如街道类型、施工年份、屋顶类 型、地下室状况等。这些特征由各种数据类型组成。例如,建筑年份由整数表示,屋顶类型由离散类别表示, 其他特征由浮点数表示。

  1. %matplotlib inline
  2. import numpy as np
  3. import pandas as pd
  4. import torch
  5. from torch import nn
  6. from d2l import torch as d2l
  1. DATA_HUB['kaggle_house_train'] = ( #@save
  2. DATA_URL + 'kaggle_house_pred_train.csv',
  3. '585e9cc93e70b39160e7921475f9bcd7d31219ce')
  4. DATA_HUB['kaggle_house_test'] = ( #@save
  5. DATA_URL + 'kaggle_house_pred_test.csv',
  6. 'fa19780a7b011d9b009e8bff8e99922a8ee2eb90')

加载包含训练数据和测试数据 的两个CSV文件。

  1. train_data = pd.read_csv(download('kaggle_house_train'))
  2. test_data = pd.read_csv(download('kaggle_house_test'))
  3. print(train_data.shape)
  4. print(test_data.shape)
  5. # (1460, 81)
  6. # (1459, 80)

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

  1. all_features = pd.concat((train_data.iloc[:, 1:-1], test_data.iloc[:, 1:]))
  2. all_features.shape
  3. # (2919, 79)

三 数据预处理

在开始建模之前,我们需要对数据进行预处理。首先,我们将所有 缺失的值替换为相应特征的平均值。

  1. numerc_features = all_features.dtypes[all_features.dtypes != 'object'].index
  2. all_features[numerc_features] = all_features[numerc_features].apply(
  3. lambda x: (x - x.mean()) / (x.std()))
  4. all_features[numerc_features] = all_features[numerc_features].fillna(0)

3.1 独热编码

我们处理离散值。这包括诸如“MSZoning”之类的特征。我们用独热编码替换它们,方法与前面 将多类别标签转换为向量的方式相同。

  1. all_features = pd.get_dummies(all_features, dummy_na=True)
  2. all_features.shape
  3. # (2919, 330)

3.2 转换为 tensor

  1. n_train = train_data.shape[0]
  2. train_features = torch.tensor(all_features[:n_train].values, dtype=torch.float32)
  3. test_features = torch.tensor(all_features[n_train:].values, dtype=torch.float32)
  4. train_labels = torch.tensor(train_data.SalePrice.values.reshape(-1, 1), dtype=torch.float32)

四 训练

我们训练一个带有损失平方的线性模型。

  1. loss = nn.MSELoss()
  2. in_features = train_features.shape[1]
  3. def get_net():
  4. net = nn.Sequential(nn.Linear(in_features, 1))
  5. return net
  1. def log_rmse(net, features, labels):
  2. clipped_preds = torch.clamp(net(features), 1, float('inf'))
  3. rmse = torch.sqrt(loss(torch.log(clipped_preds), torch.log(labels)))
  4. return rmse.item()

与前面的部分不同,我们的训练函数将借助Adam优化器。Adam优化 器的主要吸引力在于它对初始学习率不那么敏感。

  1. def train(net, train_features, train_labels, test_features, test_labels,
  2. num_epochs, learning_rate, weight_decay, batch_size):
  3. train_ls, test_ls = [], []
  4. train_iter = d2l.load_array((train_features, train_labels), batch_size)
  5. optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate,
  6. weight_decay=weight_decay)
  7. for epoch in range(num_epochs):
  8. for x, y in train_iter:
  9. optimizer.zero_grad()
  10. l = loss(net(x), y)
  11. l.backward()
  12. optimizer.step()
  13. train_ls.append(log_rmse(net, train_features, train_labels))
  14. if test_labels is not None:
  15. test_ls.append(log_rmse(net, test_features, test_labels))
  16. return train_ls, test_ls

4.1 K折交叉验证

  1. def get_k_fold_data(k, i, x, y):
  2. assert k > 1
  3. fold_size = x.shape[0] // k
  4. x_train, y_train = None, None
  5. for j in range(k):
  6. idx = slice(j * fold_size, (j + 1) * fold_size)
  7. x_part, y_part = x[idx, :], y[idx]
  8. if j == i:
  9. x_valid, y_valid = x_part, y_part
  10. elif x_train is None:
  11. x_train, y_train = x_part, y_part
  12. else:
  13. x_train = torch.cat([x_train, x_part], 0)
  14. y_train = torch.cat([y_train, y_part], 0)
  15. return x_train, y_train, x_valid, y_valid

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

  1. def k_fold(k, x_train, y_train, num_epochs, learning_rate, weight_decay, batch_size):
  2. train_l_sum, valid_l_sum = 0, 0
  3. for i in range(k):
  4. data = get_k_fold_data(k, i, x_train, y_train)
  5. net = get_net()
  6. train_ls, valid_ls = train(net, *data, num_epochs, learning_rate,
  7. weight_decay, batch_size)
  8. train_l_sum += train_ls[-1]
  9. valid_l_sum += valid_ls[-1]
  10. if i == 0:
  11. d2l.plot(list(range(1, num_epochs + 1)), [train_ls, valid_ls],
  12. xlabel='epoch', ylabel='rmse', xlim=[1, num_epochs],
  13. legend=['train', 'valid'], yscale='log')
  14. print(f'折{i+1},训练log rmse{float(train_ls[-1]):f},log rmse:{float(valid_ls[-1]):f}')
  15. return train_l_sum / k, valid_l_sum / k

4.2 模型选择

  1. k, num_epochs, lr, weight_decay, batch_size = 5, 100, 5, 0, 64
  2. train_l, valid_l = k_fold(k, train_features, train_labels, num_epochs, lr,
  3. weight_decay, batch_size)
  4. print(f'{k}-折验证:平均训练 log rmse: {float(train_l): f}, 平均rmse:{float(valid_l):f}')
  5. # 折1,训练log rmse0.170501,log rmse:0.157013
  6. # 折2,训练log rmse0.162297,log rmse:0.190953
  7. # 折3,训练log rmse0.164260,log rmse:0.168382
  8. # 折4,训练log rmse0.168306,log rmse:0.155091
  9. # 折5,训练log rmse0.163718,log rmse:0.183309
  10. # 5-折验证:平均训练 log rmse: 0.165816, 平均rmse:0.170950

4.3 执行训练及预测

  1. def train_and_pred(train_features, test_features, train_labels, test_data,
  2. num_epochs, lr, weight_decay, batch_size):
  3. net = get_net()
  4. train_ls, _ = train(net, train_features, train_labels, None, None,
  5. num_epochs, lr, weight_decay, batch_size)
  6. d2l.plot(np.arange(1, num_epochs + 1), [train_ls], xlabel='epoch',
  7. ylabel='log rmse', xlim=[1, num_epochs], yscale='log')
  8. print(f'训练 log rmse: {float(train_ls[-1]): f}')
  9. preds = net(test_features).detach().numpy()
  10. test_data['ScalePrice'] = pd.Series(preds.reshape(1, -1)[0])
  11. submission = pd.concat([test_data['Id'], test_data['ScalePrice']], axis=1)
  12. submission.to_csv('submission.csv', index=False)
  1. train_and_pred(train_features, test_features, train_labels, test_data,
  2. num_epochs, lr, weight_decay, batch_size)
  3. # 训练 log rmse: 0.162326

小结:

  • 真实数据通常混合了不同的数据类型,需要进行预处理
  • 常用的预处理方法:将实值数据重新缩放为零均值和单位方法;用均值替换缺失值
  • 将类别特征转化为指标特征,可以使我们把这个特征当作一个 独热向量 来对待。
  • 我们可以使用 K折交叉验证 来选择模型并调整超参数。
  • 对数对于相对误差很有用。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/345022
推荐阅读
相关标签
  

闽ICP备14008679号