在本篇博文中,我们将探索如何使用 PyTorch 和 Pandas 库,构建一个用于 Kaggle 房价预测的模型。我们将详细讨论数据加载、预处理、模型构建、训练、验证及最终预测的全过程。
1、环境设置
我们首先需要导入所需的库,包括用于数据处理的 pandas
和 numpy
,以及用于深度学习的 torch
。
import hashlib
import os
import requests
import numpy as np
import pandas as pd
import torch
from torch import nn
from d2l import torch as d2l
2、数据下载
为了下载数据,我们需要定义一个下载函数,并在其中实现数据缓存机制以避免重复下载。
# 保存DATA_HUB字典以便下载数据
DATA_HUB = dict()
DATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/'
# 保存下载函数
def download(name, cache_dir=os.path.join('..', 'data')):
"""下载一个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.hexdigest() == sha1_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
接下来,我们在 DATA_HUB
中注册 Kaggle 房价预测的训练和测试数据集,并下载这些数据。
# 在DATA_HUB中注册Kaggle房价预测的训练和测试数据集
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')
# 下载并加载数据
train_data = pd.read_csv(download('kaggle_house_train'))
test_data = pd.read_csv(download('kaggle_house_test'))
3、数据预处理
我们首先查看数据集的形状和部分内容。
# 查看数据集的形状和部分内容
print(train_data.shape)
print(test_data.shape)
print(train_data.iloc[0:4, [0, 1, 2, 3, -3, -2, -1]])
然后,我们合并所有特征以进行统一预处理,并标准化数值特征,填充缺失值为0,处理离散数值特征。
# 合并所有特征以进行预处理
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
all_features[numeric_features] = all_features[numeric_features].fillna(0)
# 处理离散数值特征(dummy_na=True包括缺失值)
all_features = pd.get_dummies(all_features, dummy_na=True)
# 确保所有特征都是数值类型
all_features = all_features.astype(np.float32)
将数据转换为 tensor 格式,以便 PyTorch 使用。
# 将数据转换为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)