kaggle-房价预测实战

Tamara ·
更新时间:2024-11-13
· 926 次阅读

本次kaggle实战还在进行中

定义比赛用来评价模型的对数均方根误差。给定预测值y^1,…,y^n\hat y_1, \ldots, \hat y_ny^​1​,…,y^​n​和对应的真实标签y1,…,yny_1,\ldots, y_ny1​,…,yn​,它的定义为

1n∑i=1n(log⁡(yi)−log⁡(y^i))2. \sqrt{\frac{1}{n}\sum_{i=1}^n\left(\log(y_i)-\log(\hat y_i)\right)^2}. n1​i=1∑n​(log(yi​)−log(y^​i​))2​.

对数均方根误差的实现如下面的log_rmse(net, features, labels) 函数。

# This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import torch from torch import nn # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import os # for dirname, _, filenames in os.walk('/kaggle/input'): # for filename in filenames: # print(os.path.join(dirname, filename)) # Any results you write to the current directory are saved as output. train_data = pd.read_csv("../input/house-prices-advanced-regression-techniques/train.csv") test_data = pd.read_csv("../input/house-prices-advanced-regression-techniques/test.csv") print(test_data.iloc[0:4, [0, 1, 2, 3, -3, -2, -1]]) print("\n") print(train_data.iloc[0:4, [0, 1, 2, 3, -3, -2, -1]]) # print(train_data.iloc[0]) print(train_data.shape, test_data.shape) 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())) all_features[numeric_features] = all_features[numeric_features].fillna(0) all_features = pd.get_dummies(all_features, dummy_na=True) # print(all_features.shape) n_train = train_data.shape[0] # get data tensor train_features = torch.tensor(all_features[:n_train].values, dtype=torch.float) test_features = torch.tensor(all_features[n_train:].values, dtype=torch.float) train_lables = torch.tensor(train_data.SalePrice.values, dtype=torch.float) # test_lables = torch.tensor(test_data.SalePrice.values, dtype=torch.float) # print(train_features.shape) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(331, 1) self.relu = nn.ReLU(True) def forward(self,input): output = self.fc1(input) output = self.relu(output) return output net = Net() for param in net.parameters(): nn.init.normal_(param, mean=0, std=0.01) loss_fn = nn.MSELoss() def log_rmse(net, features, labels): with torch.no_grad(): # 将小于1的值设成1,使得取对数时数值更稳定 clipped_preds = torch.max(net(features), torch.tensor(1.0)) rmse = torch.sqrt(2 * loss_fn(clipped_preds.log(), labels.log()).mean()) return rmse.item() def train(net, train_data, train_lables, num_epochs, learning_rate, weight_decay, batch_size): dataset = torch.utils.data.TensorDataset(train_features, train_lables) train_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True) optimizer = torch.optim.Adam(params=net.parameters(), lr=learning_rate, weight_decay=weight_decay) net = net.float() for epoch in range(num_epochs): for X, y in dataset: net.train() X = net(X.float()) l = loss_fn(X, y.float()) optimizer.zero_grad() l.backward() optimizer.step() train_ls.append(log_rmse(net, train_features, train_lables)) # if test_labels is not None: # test_ls.append(log_rmse(net, test_features, test_labels)) return train_ls num_epochs = 50 learning_rate = 0.01 weight_decay = 0 batch_size = 64 train_ls = [] train(net, train_data, train_lables, num_epochs, learning_rate, weight_decay, batch_size) print(train_ls[40:]) K折交叉验证

我们在模型选择、欠拟合和过拟合中介绍了KKK折交叉验证。它将被用来选择模型设计并调节超参数。下面实现了一个函数,它返回第i折交叉验证时所需要的训练和验证数据。

def get_k_fold_data(k, i, X, y): # 返回第i折交叉验证时所需要的训练和验证数据 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), dim=0) y_train = torch.cat((y_train, y_part), dim=0) return X_train, y_train, X_valid, y_valid

在KKK折交叉验证中我们训练KKK次并返回训练和验证的平均误差

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(X_train.shape[1]) 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.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'rmse', range(1, num_epochs + 1), valid_ls, ['train', 'valid']) print('fold %d, train rmse %f, valid rmse %f' % (i, train_ls[-1], valid_ls[-1])) return train_l_sum / k, valid_l_sum / k 模型选择

我们使用一组未经调优的超参数并计算交叉验证误差。可以改动这些超参数来尽可能减小平均测试误差。
有时候你会发现一组参数的训练误差可以达到很低,但是在KKK折交叉验证上的误差可能反而较高。这种现象很可能是由过拟合造成的。因此,当训练误差降低时,我们要观察KKK折交叉验证上的误差是否也相应降低。

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('%d-fold validation: avg train rmse %f, avg valid rmse %f' % (k, train_l, valid_l)) 预测并在Kaggle中提交结果

下面定义预测函数。在预测之前,我们会使用完整的训练数据集来重新训练模型,并将预测结果存成提交所需要的格式。

def train_and_pred(train_features, test_features, train_labels, test_data, num_epochs, lr, weight_decay, batch_size): net = get_net(train_features.shape[1]) train_ls, _ = train(net, train_features, train_labels, None, None, num_epochs, lr, weight_decay, batch_size) d2l.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'rmse') print('train rmse %f' % train_ls[-1]) preds = net(test_features).detach().numpy() 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) # sample_submission_data = pd.read_csv("../input/house-prices-advanced-regression-techniques/sample_submission.csv")
作者:qq_2649825643



实战 kaggle 房价

需要 登录 后方可回复, 如果你还没有账号请 注册新账号