文章目录
实战Kaggle比赛:预测房价1 - 下载和缓存数据集2 - 访问和读取数据集3 - 数据预处理4 - 训练5 - K折交叉验证6 - 模型选择7 - 提交你的Kaggle预测实战Kaggle比赛:预测房价
1 - 下载和缓存数据集
import hashlibimport osimport tarfileimport zipfileimport requests#@saveDATA_HUB = dict()DATA_URL = 'http://d2l-data.s3-/'
DATA_HUB:字典,可将数据集名称的字符串映射到数据集相关的二元组上 该二元组包含数据集的url和验证文件完整性的sha-l密钥 DATA_URL:类似的数据集都托管在地址该站点上
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:breaksha1.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
download:该函数用来下载数据集,缓存在本地目录(默认在…/data)中,并返回下载文件的名称 若缓存目录以存在该数据集文件,并且其sha-l与存储在DATA-HUB中的相匹配,我们将使用缓存的文件,避免重复下载
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.extractall(base_dir)return os.path.join(base_dir, folder) if folder else data_dir
download_extract:下载并解压缩一个zip/tar文件
def download_all(): #@save"""下载DATA_HUB中的所有⽂件"""for name in DATA_HUB:download(name)
download_all:将本书中使用的所有数据集从DATA_HUB下载到缓存目录中
2 - 访问和读取数据集
%matplotlib inlineimport numpy as npimport pandas as pdimport torchfrom torch import nnfrom d2l import torch as d2l
DATA_HUB['kaggle_house_train'] = ( #@saveDATA_URL + 'kaggle_house_pred_train.csv','585e9cc93e70b39160e7921475f9bcd7d31219ce')DATA_HUB['kaggle_house_test'] = ( #@saveDATA_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'))
正在从http://d2l-data.s3-/kaggle_house_pred_train.csv下载.\data\kaggle_house_pred_train.csv...正在从http://d2l-data.s3-/kaggle_house_pred_test.csv下载.\data\kaggle_house_pred_test.csv...
print(train_data.shape)print(test_data.shape)
(1460, 81)(1459, 80)
查看前四个和最后两个特征,以及相应标签(房价)
print(train_data.iloc[0:4, [0, 1, 2, 3, -3, -2, -1]])
Id MSSubClass MSZoning LotFrontage SaleType SaleCondition SalePrice0 160 RL 65.0 WD Normal2085001 220 RL 80.0 WD Normal1815002 360 RL 68.0 WD Normal2235003 470 RL 60.0 WD Abnorml140000
在每个样本中,第一个特征是ID,这有助于模型识别每个模型样本,虽然这很方便,但不携带任何预测信息,因此在将数据提供给模型之前,可将其从数据集中删除
all_features = pd.concat((train_data.iloc[:, 1:-1], test_data.iloc[:, 1:]))
3 - 数据预处理
# 若⽆法获得测试数据,则可根据训练数据计算均值和标准差numeric_features = all_features.dtypes[all_features.dtypes != 'object'].indexall_features[numeric_features] = all_features[numeric_features].apply(lambda x: (x - x.mean()) / (x.std()))# 在标准化数据之后,所有均值消失,因此我们可以将缺失值设置为0all_features[numeric_features] = all_features[numeric_features].fillna(0)
接下来处理离散值。诸如“MSZoning”之类的特征。我们用独热编码替代,方法与前面将多类别标签转换为向量的方式相同。例如,“MSZoning”包含值“RL”和“Rm”,创建两个新的指⽰器特征“MSZoning_RL”和“MSZoning_RM”,其值为0或1。根据独热编码,如果“MSZoning”的原始值为“RL”,则:“MSZoning_RL”为1,“MSZoning_RM”为0。pandas软件包会⾃动为我们实现这⼀点
# “Dummy_na=True”将“na”(缺失值)视为有效的特征值,并为其创建指⽰符特征all_features = pd.get_dummies(all_features, dummy_na=True)all_features.shape
(2919, 331)
可以看到,此转换将特征值的总数量从79个增加到331个。最后通过values属性,我们可以从pandas格式中提取NumPy格式,并将其转换为张量用于训练
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)
4 - 训练
首先,训练一个带有损失平方的线性模型。显然线性模型很难让我们在竞赛中获胜,但线性模型提供了一个健全性检查,以查看数据中是否存在有意义的信息。若我们在这里不能做的比随机猜测更好,那么我们很可能存在数据处理错误。若一切顺利,线性模型将作为基线(baseline)模型,让我们直观地知道好的模型有超出简单的模型多少
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):# 为了在取对数时进⼀步稳定该值,将⼩于1的值设置为1clipped_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)# 这⾥使⽤的是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
5 - K折交叉验证
第i个切片作为验证数据,其余部分作为训练数据。注意,这并不是处理数据的最有效方法,若我们的数据集大得多,会有其他解决办法
def get_k_fold_data(k, i, X, y):assert k > 1fold_size = X.shape[0] // kX_train, y_train = None, Nonefor 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_partelif X_train is None:X_train, y_train = X_part, y_partelse: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, 0for 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}, 'f'验证log rmse{float(valid_ls[-1]):f}')return train_l_sum / k, valid_l_sum / k
6 - 模型选择
在本例中,我们选择了一组未调优的超参数,找到一组调优的超参数可能需要很长时间,取决于一个人优化了多少变量。当有了足够大的数据集和合理设置的超参数,K折交叉验证往往对多次测试具有相当的稳定性。然而,若我们尝试了不合理的超参数,可能会发现验证效果不再代表真正的误差
k, num_epochs, lr, weight_decay, batch_size = 5, 100, 5, 0, 64train_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}')
折1,训练log rmse0.170594, 验证log rmse0.157266折2,训练log rmse0.162075, 验证log rmse0.190974折3,训练log rmse0.163837, 验证log rmse0.168588折4,训练log rmse0.167399, 验证log rmse0.154469折5,训练log rmse0.162827, 验证log rmse0.1828655-折验证: 平均训练log rmse: 0.165347, 平均验证log rmse: 0.170832
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7JpdBzOV-1662361788799)(https://yingziimage.oss-cn-/img/09051508974.svg)]
注意,有时一组超参数的训练误差可能非常低,但K折交叉验证的误差要高得多,这表面模型过拟合了。在整个训练过程中,你将希望监控训练误差和验证误差这两个数字。较少的过拟合可能表明现有数据可以⽀撑⼀个更强⼤的模型,较⼤的过拟合可能意味着我们可以通过正则化技术来获益
7 - 提交你的Kaggle预测
既然我们知道应该选择什么样的超参数,我们不妨使⽤所有数据对其进⾏训练(⽽不是仅使⽤交叉验证中使⽤的1 − 1/K的数据)。然后,我们通过这种⽅式获得的模型可以应⽤于测试集。将预测保存在CSV⽂件中可以简化将结果上传到Kaggle的过程
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()# 将其重新格式化以导出到Kaggletest_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)
如果测试集上的预测与K倍交叉验证过程中的预测相似,那就是时候把它们上传到Kaggle了。下⾯的代码将⽣成⼀个名为submission.csv的⽂件
train_and_pred(train_features, test_features, train_labels, test_data,num_epochs, lr, weight_decay, batch_size)
训练log rmse:0.162455
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3fyIW1p1-1662361788799)(https://yingziimage.oss-cn-/img/09051508859.svg)]