本文我们将详细介绍数据预处理、模型设计和超参数选择。 通过亲身实践,你将获得一手经验,这些经验将有益开发者的职业成长。
1. 下载和缓存数据集
python
# -*- coding: utf-8 -*-
"""
@File : 4.10.实战Kaggle比赛:预测房价.py
@Time : 2024/12/5 16:40
@Desc :
"""
import hashlib
import os
import tarfile
import zipfile
import requests
# @save
DATA_HUB = dict()
DATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/'
def download(name, cache_dir=os.path.join('..', 'data')): # @save
"""下载一个DATA_HUB中的文件,返回本地文件名"""
assert name in DATA_HUB, f"{name} 不存在于 {DATA_HUB}"
url, sha1_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):
sha1 = hashlib.sha1()
with open(fname, 'rb') as f:
while True:
data = f.read(1048576)
if not data:
break
sha1.update(data)
if sha1_hash == sha1.hexdigest():
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
def download_extract(name, folder=None): # @save
"""下载并解压zip/tar文件"""
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, '只有zip/tar文件可以被解压缩'
fp.extract(base_dir)
return os.path.join(base_dir, folder) if folder else data_dir
def download_all(): # @save
"""下载DATA_HUB中的所有文件"""
for name in DATA_HUB:
download(name)
DATA_HUB['kaggle_house_train'] = (
DATA_URL + 'kaggle_house_pred_train.csv',
'585e9cc93e70b39160e7921475f9bcd7d31219ce'
)
DATA_HUB['kaggle_house_test'] = (
DATA_URL + 'kaggle_house_pred_test.csv',
'fa19780a7b011d9b009e8bff8e99922a8ee2eb90'
)
if __name__ == '__main__':
download_all()
2. Kaggle
Kaggle 是一个全球知名的数据科学和机器学习平台,提供丰富的数据集、代码示例和竞赛资源。用户可以通过参与实际问题的比赛提升技能,与全球数据科学家交流合作。无论是新手还是专家,Kaggle 都是学习、实践和展示数据科学能力的理想选择。
3. 访问和读取数据集
python
import numpy as np
import pandas as pd
import torch
from torch import nn
import d2l
train_data = pd.read_csv(d2l.download('kaggle_house_train'))
test_data = pd.read_csv(d2l.download('kaggle_house_test'))
print(train_data.shape) # (1460, 81)
print(test_data.shape) # (1459, 80)
# 让我们看看前五行前四个和最后两个特征,以及相应标签(房价)。
print(train_data.iloc[0:5, [0, 1, 2, 3, -3, -2, -1]])
"""
Id MSSubClass MSZoning LotFrontage SaleType SaleCondition SalePrice
0 1 60 RL 65.0 WD Normal 208500
1 2 20 RL 80.0 WD Normal 181500
2 3 60 RL 68.0 WD Normal 223500
3 4 70 RL 60.0 WD Abnorml 140000
4 5 60 RL 84.0 WD Normal 250000
"""
# 第一个特征是ID,不携带任何用于预测的信息,在将数据提供给模型之前,我们将其从数据集中删除
all_features = pd.concat((train_data.iloc[:, 1:-1], test_data.iloc[:, 1:]))
print(all_features.shape) # (2919, 79)
4. 数据预处理
在开始建模之前,我们需要对数据进行预处理。 首先,我们将所有缺失的值替换为相应特征的平均值。然后,为了将所有特征放在一个共同的尺度上, 我们通过将特征重新缩放到零均值和单位方差来标准化数据:
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> x ← x − μ σ x \leftarrow \frac{x - \mu}{\sigma} </math>x←σx−μ
其中 <math xmlns="http://www.w3.org/1998/Math/MathML"> μ \mu </math>μ 和 <math xmlns="http://www.w3.org/1998/Math/MathML"> σ \sigma </math>σ 分别表示均值和标准差。
python
# 若无法获得测试数据,则可根据训练数据计算均值和标准差
numeric_features = all_features.dtypes[all_features.dtypes != 'object'].index
all_features[numeric_features] = all_features[numeric_features].apply(
lambda x: (x - x.mean()) / x.std()
)
# 在标准化数据之后,所有均值为0,因此我们可以将缺失值设置为0
all_features[numeric_features] = all_features[numeric_features].fillna(0)
print(all_features.iloc[0:5, [0, 1, 2, 3, -3, -2, -1]])
"""
MSSubClass MSZoning LotFrontage LotArea YrSold SaleType SaleCondition
0 0.067320 RL -0.184443 -0.217841 0.157619 WD Normal
1 -0.873466 RL 0.458096 -0.072032 -0.602858 WD Normal
2 0.067320 RL -0.055935 0.137173 0.157619 WD Normal
3 0.302516 RL -0.398622 -0.078371 -1.363335 WD Abnorml
4 0.067320 RL 0.629439 0.518814 0.157619 WD Normal
"""
我们用独热编码替换它们, 方法与前面将多类别标签转换为向量的方式相同。
python
# "Dummy_na=True"将"na"(缺失值)视为有效的特征值,并为其创建指示符特征
all_features = pd.get_dummies(all_features, dummy_na=True)
print(all_features.shape) # (2919, 330)
# 我们可以 从pandas格式中提取NumPy格式,并将其转换为张量表示用于训练
n_train = train_data.shape[0]
train_features = torch.tensor(all_features[:n_train].values.astype(np.float32), dtype=torch.float32)
test_features = torch.tensor(all_features[n_train:].values.astype(np.float32), dtype=torch.float32)
train_labels = torch.tensor(train_data.SalePrice.values.reshape(-1, 1), dtype=torch.float32)
print(train_features.shape, test_features.shape, train_labels.shape)
# torch.Size([1460, 330]) torch.Size([1459, 330]) torch.Size([1460, 1])
5. 训练
python
loss = nn.MSELoss() # 均方误差损失函数,reduction参数默认是'mean'
in_features = train_features.shape[1]
def get_net():
return nn.Sequential(nn.Linear(in_features, 1))
房价就像股票价格一样,我们关心的是相对数量,而不是绝对数量。 因此,我们更关心相对误差 <math xmlns="http://www.w3.org/1998/Math/MathML"> y − y ^ y \frac{y-\hat{y}}{y} </math>yy−y^, 而不是绝对误差 <math xmlns="http://www.w3.org/1998/Math/MathML"> y − y ^ y-\hat{y} </math>y−y^。解决这个问题的一种方法是用价格预测的对数来衡量差异。
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> 1 n ∑ i = 1 n ( log y i − log y ^ i ) 2 \sqrt{\frac{1}{n}\sum_{i=1}^{n}(\log{y_i}-\log{\hat{y}_i})^2} </math>n1i=1∑n(logyi−logy^i)2
python
def log_rmse(net, features, labels):
# 为了在取对数时进一步稳定该值,将输出值裁剪到1到正无穷之间
clipped_preds = torch.clamp(net(features), 1, float('inf'))
rmse = torch.sqrt(loss(torch.log(clipped_preds), torch.log(labels)))
return rmse.item()
我们的训练函数将借助Adam优化器 (我们将在后面更详细地描述它)。
python
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)
# 这里使用的是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
6. K折交叉验证
我们首先需要定义一个函数,在 <math xmlns="http://www.w3.org/1998/Math/MathML"> K K </math>K 折交叉验证过程中返回第 <math xmlns="http://www.w3.org/1998/Math/MathML"> i i </math>i 折的数据。 具体地说,它选择第 <math xmlns="http://www.w3.org/1998/Math/MathML"> i i </math>i 个切片作为验证数据,其余部分作为训练数据。
python
def get_k_fold_data(k, i, X, y):
assert k > 1
fold_size = X.shape[0] // k
X_train, y_train, X_valid, y_valid = None, None, None, None
for j in range(k):
idx = slice(j * fold_size, j * fold_size + 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
当我们在 <math xmlns="http://www.w3.org/1998/Math/MathML"> K K </math>K 折交叉验证中训练 <math xmlns="http://www.w3.org/1998/Math/MathML"> K K </math>K 次后,返回训练和验证误差的平均值。
python
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="训练轮数",
ylabel="对数均方根误差", xlim=[1, num_epochs], legend=["训练集", "验证集"], yscale='log')
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
7. 模型选择
在本例中,我们选择了一组未调优的超参数,并将其留给读者来改进模型。
python
if __name__ == '__main__':
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}, '
f'平均验证 log rmse: {float(valid_l):f}')
plaintext
1折,训练 log rmse = 0.169811, 验证 log rmse = 0.156870
2折,训练 log rmse = 0.162617, 验证 log rmse = 0.194116
3折,训练 log rmse = 0.163898, 验证 log rmse = 0.168392
4折,训练 log rmse = 0.167716, 验证 log rmse = 0.154894
5折,训练 log rmse = 0.162885, 验证 log rmse = 0.182460
5-折验证: 平均训练 log rmse: 0.165385, 平均验证 log rmse: 0.171346
8. 提交Kaggle预测
我们不妨使用所有数据对其进行训练 (而不是仅使用交叉验证中使用的 <math xmlns="http://www.w3.org/1998/Math/MathML"> 1 − 1 K 1-\frac{1}{K} </math>1−K1 的数据)。 然后,我们通过这种方式获得的模型可以应用于测试集。 将预测保存在CSV文件中可以简化将结果上传到Kaggle的过程。
python
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(list(range(1, num_epochs + 1)), [train_ls], xlabel="训练轮数",
ylabel="log rmse", xlim=[1, num_epochs], yscale='log')
print(f'训练log rmse:{float(train_ls[-1]):f}')
# 将网络应用于测试集
preds = net(test_features).detach().numpy()
# 将其重新格式化以导出到Kaggle
test_data['SalePrice'] = pd.Series(preds.reshape(1, -1)[0])
submission = pd.concat([test_data['Id'], test_data['SalePrice']], axis=1)
submission.to_csv('submission.csv', index=False)
if __name__ == '__main__':
k, num_epochs, lr, weight_decay, batch_size = 5, 100, 5, 0, 64
train_and_pred(train_features, test_features, train_labels, test_data,
num_epochs, lr, weight_decay, batch_size)
plaintext
训练log rmse:0.162367
完整代码
python
import numpy as np
import pandas as pd
import torch
from torch import nn
import d2l
train_data = pd.read_csv(d2l.download('kaggle_house_train'))
test_data = pd.read_csv(d2l.download('kaggle_house_test'))
# 第一个特征是ID,不携带任何用于预测的信息,在将数据提供给模型之前,我们将其从数据集中删除
all_features = pd.concat((train_data.iloc[:, 1:-1], test_data.iloc[:, 1:]))
# 若无法获得测试数据,则可根据训练数据计算均值和标准差
numeric_features = all_features.dtypes[all_features.dtypes != 'object'].index
all_features[numeric_features] = all_features[numeric_features].apply(
lambda x: (x - x.mean()) / x.std()
)
# 在标准化数据之后,所有均值为0,因此我们可以将缺失值设置为0
all_features[numeric_features] = all_features[numeric_features].fillna(0)
# "Dummy_na=True"将"na"(缺失值)视为有效的特征值,并为其创建指示符特征
all_features = pd.get_dummies(all_features, dummy_na=True)
# 我们可以 从pandas格式中提取NumPy格式,并将其转换为张量表示用于训练
n_train = train_data.shape[0]
train_features = torch.tensor(all_features[:n_train].values.astype(np.float32), dtype=torch.float32)
test_features = torch.tensor(all_features[n_train:].values.astype(np.float32), dtype=torch.float32)
train_labels = torch.tensor(train_data.SalePrice.values.reshape(-1, 1), dtype=torch.float32)
loss = nn.MSELoss() # 均方误差损失函数,reduction参数默认是'mean'
in_features = train_features.shape[1]
def get_net():
return nn.Sequential(nn.Linear(in_features, 1))
def log_rmse(net, features, labels):
# 为了在取对数时进一步稳定该值,将输出值裁剪到1到正无穷之间
clipped_preds = torch.clamp(net(features), 1, float('inf'))
rmse = torch.sqrt(loss(torch.log(clipped_preds), torch.log(labels)))
return rmse.item()
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)
# 这里使用的是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
def get_k_fold_data(k, i, X, y):
assert k > 1
fold_size = X.shape[0] // k
X_train, y_train, X_valid, y_valid = None, None, None, None
for j in range(k):
idx = slice(j * fold_size, j * fold_size + 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
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="训练轮数",
ylabel="对数均方根误差", xlim=[1, num_epochs], legend=["训练集", "验证集"], yscale='log')
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
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(list(range(1, num_epochs + 1)), [train_ls], xlabel="训练轮数",
ylabel="log rmse", xlim=[1, num_epochs], yscale='log')
print(f'训练log rmse:{float(train_ls[-1]):f}')
# 将网络应用于测试集
preds = net(test_features).detach().numpy()
# 将其重新格式化以导出到Kaggle
test_data['SalePrice'] = pd.Series(preds.reshape(1, -1)[0])
submission = pd.concat([test_data['Id'], test_data['SalePrice']], axis=1)
submission.to_csv('submission.csv', index=False)
if __name__ == '__main__':
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}, '
# f'平均验证 log rmse: {float(valid_l):f}')
train_and_pred(train_features, test_features, train_labels, test_data,
num_epochs, lr, weight_decay, batch_size)