一 下载数据集
此数据集由Bart de Cock于2011年收集,涵盖了2006‐2010年期间 亚利桑那州 埃姆斯市的房价。
下载地址:
import hashlib
import os
import tarfile
import zipfile
import requests
#@save
DATA_HUB = dict()
DATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/'
下面的download函数用来下载数据集,将数据集缓存在本地目录(默认情况下为../data)中,并返回下载文 件的名称。
def download(name, cache_dir=os.path.join('..', 'data')): #@save
assert name in DATA_HUB, f'{name} 不存在于{DATA_HUB}'
url, shal_hash = DATA_HUB[name]
os.makedirs(cache_dir, exist_ok=True)
fname = os.path.join(cache_dir, url.split('/')[-1])
if os.path.exists(fname):
shal = hashlib.sha1()
with open(fname, 'rb') as f:
while True:
data = f.read(1048576)
if not data:
break
shal.update(data)
if shal.hexdigest() == shal_hash:
return fname
print(f'正在从{url}下载{fname}...')
r = requests.get(url, stream=True, verify=True)
with open(fname, 'wb') as f:
f.write(r.content)
return fname
我们还需实现两个实用函数:一个将下载并解压缩一个zip或tar文件,另一个是将本书中使用的所有数据集 从DATA_HUB下载到缓存目录中。
def download_extract(name, folder=None): #@save
fname = download(name)
base_dir = os.path.dirname(fname)
data_dir, ext = os.path.splitext(fname)
if ext == '.zip':
fp = zipfile.ZipFile(fname, 'r')
elif ext in ('.tar', '.gz'):
fp = tarfile.open(fname, 'r')
else:
assert False
fp.extractall(base_dir)
return os.path.join(base_dir, folder) if folder else data_dir
def download_all():
for name in DATA_HUB:
download(name)
二 加载数据集
竞赛数据分为训练集和测试集。每条记录都包括房屋的属性值和属性,如街道类型、施工年份、屋顶类 型、地下室状况等。这些特征由各种数据类型组成。例如,建筑年份由整数表示,屋顶类型由离散类别表示, 其他特征由浮点数表示。
%matplotlib inline
import numpy as np
import pandas as pd
import torch
from torch import nn
from d2l import torch as d2l
DATA_HUB['kaggle_house_train'] = ( #@save
DATA_URL + 'kaggle_house_pred_train.csv',
'585e9cc93e70b39160e7921475f9bcd7d31219ce')
DATA_HUB['kaggle_house_test'] = ( #@save
DATA_URL + 'kaggle_house_pred_test.csv',
'fa19780a7b011d9b009e8bff8e99922a8ee2eb90')
加载包含训练数据和测试数据 的两个CSV文件。
train_data = pd.read_csv(download('kaggle_house_train'))
test_data = pd.read_csv(download('kaggle_house_test'))
print(train_data.shape)
print(test_data.shape)
# (1460, 81)
# (1459, 80)
我们可以看到,在每个样本中,第一个特征是ID,这有助于模型识别每个训练样本。虽然这很方便,但它不 携带任何用于预测的信息。因此,在将数据提供给模型之前,我们将其从数据集中删除。
all_features = pd.concat((train_data.iloc[:, 1:-1], test_data.iloc[:, 1:]))
all_features.shape
# (2919, 79)
三 数据预处理
在开始建模之前,我们需要对数据进行预处理。首先,我们将所有 缺失的值替换为相应特征的平均值。
numerc_features = all_features.dtypes[all_features.dtypes != 'object'].index
all_features[numerc_features] = all_features[numerc_features].apply(
lambda x: (x - x.mean()) / (x.std()))
all_features[numerc_features] = all_features[numerc_features].fillna(0)
3.1 独热编码
我们处理离散值。这包括诸如“MSZoning”之类的特征。我们用独热编码替换它们,方法与前面 将多类别标签转换为向量的方式相同。
all_features = pd.get_dummies(all_features, dummy_na=True)
all_features.shape
# (2919, 330)
3.2 转换为 tensor
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)
四 训练
我们训练一个带有损失平方的线性模型。
loss = nn.MSELoss()
in_features = train_features.shape[1]
def get_net():
net = nn.Sequential(nn.Linear(in_features, 1))
return net
def log_rmse(net, features, labels):
clipped_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 = d2l.load_array((train_features, train_labels), batch_size)
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
4.1 K折交叉验证
def get_k_fold_data(k, i, x, y):
assert k > 1
fold_size = x.shape[0] // k
x_train, y_train = None, None
for 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_part
elif x_train is None:
x_train, y_train = x_part, y_part
else:
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, 0
for 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]
if i == 0:
d2l.plot(list(range(1, num_epochs + 1)), [train_ls, valid_ls],
xlabel='epoch', ylabel='rmse', xlim=[1, num_epochs],
legend=['train', 'valid'], yscale='log')
print(f'折{i+1},训练log rmse{float(train_ls[-1]):f},log rmse:{float(valid_ls[-1]):f}')
return train_l_sum / k, valid_l_sum / k
4.2 模型选择
k, num_epochs, lr, weight_decay, batch_size = 5, 100, 5, 0, 64
train_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}, 平均rmse:{float(valid_l):f}')
# 折1,训练log rmse0.170501,log rmse:0.157013
# 折2,训练log rmse0.162297,log rmse:0.190953
# 折3,训练log rmse0.164260,log rmse:0.168382
# 折4,训练log rmse0.168306,log rmse:0.155091
# 折5,训练log rmse0.163718,log rmse:0.183309
# 5-折验证:平均训练 log rmse: 0.165816, 平均rmse:0.170950
4.3 执行训练及预测
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)
d2l.plot(np.arange(1, num_epochs + 1), [train_ls], xlabel='epoch',
ylabel='log rmse', xlim=[1, num_epochs], yscale='log')
print(f'训练 log rmse: {float(train_ls[-1]): f}')
preds = net(test_features).detach().numpy()
test_data['ScalePrice'] = pd.Series(preds.reshape(1, -1)[0])
submission = pd.concat([test_data['Id'], test_data['ScalePrice']], axis=1)
submission.to_csv('submission.csv', index=False)
train_and_pred(train_features, test_features, train_labels, test_data,
num_epochs, lr, weight_decay, batch_size)
# 训练 log rmse: 0.162326
小结:
- 真实数据通常混合了不同的数据类型,需要进行预处理。
- 常用的预处理方法:将实值数据重新缩放为零均值和单位方法;用均值替换缺失值。
- 将类别特征转化为指标特征,可以使我们把这个特征当作一个 独热向量 来对待。
- 我们可以使用 K折交叉验证 来选择模型并调整超参数。
- 对数对于相对误差很有用。