这篇文章是我在学习李沐《动手学深度学习》pytorch版“Kaggle房价预测”的笔记。
以下内容是我在学习过程编写并成功运行的代码:
import torch
import numpy as np
import pandas as pd
from torch import nn
import matplotlib.pyplot as plt
from d2l import torch as d2l
train_file = "kaggle_house_train"
test_file = "kaggle_house_test"
# 1.读取数据
train_data = pd.read_csv(d2l.download(train_file))
test_data = pd.read_csv(d2l.download(test_file))
# print(train_data.shape)
# print(test_data.shape)
# print(train_data.iloc[0:4, [0, 1, 2, 3, -3, -2, -1]])
# 按照索引取数据,取前四条0-4,取前四列和后三列
# 2.将训练集和测试集的数据进行连接
all_features = pd.concat((train_data.iloc[:, 1:-1], test_data.iloc[:, 1:])) # .iloc是pandas库中的一个索引器,用于通过整数位置选择数据。
"""
用于在给定轴上将多个DataFrame或Series对象连接在一起。它可以用于合并、拼接和连接数据。
result = pd.concat([obj1, obj2, obj3, ...], axis=0, ignore_index=False)
obj1, obj2, obj3, ...:要连接的DataFrame或Series对象的序列,可以传入列表或元组。
axis:指定连接的轴,axis=0表示沿着行方向连接,axis=1表示沿着列方向连接。
ignore_index:指定是否忽略连接后的索引,如果为True,则将重新生成新的连续整数索引;如果为False,则保留原始索引。
"""
# print(all_features.shape)
# print(all_features.head())
# print(all_features.iloc[0:4, -1])
# 3.处理数据,对数据进行归一化,对缺失值赋予均值。对离散数据转换为one-hot编码
numeric_features = all_features.dtypes[all_features.dtypes != "object"].index # 把不是object类型的全提出来,object一般是字符串
# .dtypes返回数据类型
# print(all_features.dtypes)
# 所有的索引
# print(numeric_features)
# 对数值进行标准化数据
all_features[numeric_features] = all_features[numeric_features].apply(
lambda x: (x - x.mean()) / (x.std())
)
# 对NaN填充为0
all_features[numeric_features] = all_features[numeric_features].fillna(0)
# 离散型转换为one-hot编码,pandas的get_dummies函数将数据集中的所有特征进行独热编码
all_features = pd.get_dummies(all_features, dummy_na=True)
# print(all_features.head())
# print(all_features.shape)
# 4.首先把数据展缓成pytorch格式,然后在编写的其他方法
n_train = train_data.shape[0] # 0表示行,就是训练集的数据有多少条
train_features = torch.tensor(
all_features[:n_train].values, dtype=torch.float32
)
# n_train 是训练集数据的数量,它等于 train_data 的行数。
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
)
# train_data.SalePrice选择了train_data中的SalePrice列,该列包含了训练集样本的目标变量,即房价。
# .reshape(-1, 1)的作用是将该数组重新塑形为一列,其中 -1 表示根据数据自动推断行数,而1表示列数为1。
# print(train_data.SalePrice.values.reshape(-1, 1).shape)
# 5.训练,均方误差损失函数
loss = nn.MSELoss()
in_features = train_features.shape[1] # 训练数据的特征数量
# print(in_features)
# 定义网络
def get_net():
net = nn.Sequential(nn.Linear(in_features, 1))
return net
def log_rmse(net, features, labels): # 该函数的作用是计算神经网络模型在给定特征数据和标签数据下的均方根误差的对数值,并返回该值。
# 稳定数据,将小于1的数据设置为1
clipped_preds = torch.clamp(net(features), 1, float('inf'))
# 对神经网络在输入features下的预测结果进行限制,使得预测结果不超过1和int类型的最大值
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 = [], []
# 这段代码的作用是将训练数据集中的特征和标签转换为一个迭代器对象,每次迭代返回一个批次的数据。
# d2l.load_array是一个工具函数,用于将数据转换为迭代器对象.train_iter是一个可以迭代的对象,
# 每次迭代返回一个形状为(batch_size, feature_dim)的特征张量和一个形状为(batch_size,)的标签张量。
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):
# X和y是每个batch的输入和标签
for X, y in train_iter:
optimizer.zero_grad()
l = loss(net(X), y)
l.backward()
optimizer.step()
"""
在PyTorch中,优化器的更新步骤就是通过调用`step()`方法来实现的。具体来说,`step()`方法会根据优化器的
具体实现方式,对模型的参数进行更新。例如,在使用随机梯度下降优化器时,`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折交叉验证 valid
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
def K_fold(K, X_train, y_train, num_epochs, learning_rate, weight_decay, batch_size):
train_l_sun, 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_sun += 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}, 'f'验证log rmse{float(valid_ls[-1]):f}')
return train_l_sun / K, valid_l_sum / K
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}')
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()
# 将其重新格式化以导出到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)
train_and_pred(train_features, test_features, train_labels, test_data,
num_epochs, lr, weight_decay, batch_size)
plt.show()