{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"以上代码是新建笔记本时默认生成的\n\n---\n以下代码是我自己写的，基本脉络参考老师的课件`kaggle-house-price.ipynb`，希望给大家提供一个简单的起步(getting started)用以参考","metadata":{}},{"cell_type":"code","source":"# 根据打印出的文件路径，将文件读取进内存\nsample_submission = pd.read_csv('/kaggle/input/california-house-prices/sample_submission.csv')\ntrain_data = pd.read_csv('/kaggle/input/california-house-prices/train.csv')\ntest_data = pd.read_csv('/kaggle/input/california-house-prices/test.csv')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 我们先看一下这三个数据长什么样\nsample_submission.shape, train_data.shape, test_data.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"从数字上我们可以看出以下两点：\n1. 我们要提交的文件只包含两列，第一列是对应了每一个测试集样本的`Id`，第二列是我们所预测的`SalePrice`(如上课所演示的那样)\n1. 上课演示的训练集与测试集的形状分别为`(1460, 81)`和`(1459, 80)`，可以看出比赛用的数据集样本数量更多，但是特征却更少了","metadata":{}},{"cell_type":"code","source":"# 我们先来粗略看一下数据集包含哪些特征，head方法可以查看前五行数据\ntrain_data.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"可以发现`Id`为4的数据缺失了许多特征，像这样的数据应该还会有很多\n\n但是不用慌，老师在上课的时候已经教会我们要如何处理这些缺失的数据\n\n不记得的话可以回去b站看回放哦~","metadata":{}},{"cell_type":"code","source":"# 保险起见，还是看一下测试集长什么样子再进行下一步处理\ntest_data.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"注意到比赛用到的训练集标签(即真实成交价格)与上课时用到的不同，上课时用到的标签在最后一列，而比赛用到的标签在第三列，名称为`Sold Price`\n\n通过搜索，我在[stackoverflow](https://stackoverflow.com/questions/29763620/how-to-select-all-columns-except-one-column-in-pandas)上查到如何去掉某列，那现在我们继续把数据集的特征提取出来吧~","metadata":{}},{"cell_type":"code","source":"# train_data.loc[:, train_data.columns != 'Sold Price'] # 这行代码用于提取除'Sold Price'外的其他列\nall_features = pd.concat((train_data.loc[:, train_data.columns != 'Sold Price'], test_data.iloc[:, 1:]))\nall_features.info() # info方法可以总览数据","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 将所有缺失的值替换为相应特征的平均值。通过将特征重新缩放到零均值和单位方差来标准化数据\nnumeric_features = all_features.dtypes[all_features.dtypes != 'object'].index\nall_features[numeric_features] = all_features[numeric_features].apply(\n    lambda x: (x - x.mean()) / (x.std()))\nall_features[numeric_features] = all_features[numeric_features].fillna(0)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # 处理离散值。我们用一次独热编码替换它们\n# all_features = pd.get_dummies(all_features, dummy_na=True)\n# all_features.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"如果我们直接用老师提供的代码(即上面被注释掉的代码)，那kaggle就会报一个错误：\n\n> Your notebook tried to allocate more memory than is available. It has restarted.\n\n这说明特征分布太过分散了，如果用独热编码就会占用大量内存，导致重启\n\n简单起见，接下来我尝试跳过对字符串的处理，只利用数值特征进行训练","metadata":{}},{"cell_type":"code","source":"all_features = all_features[numeric_features[1:]] # 原本第一列是Id，去掉\nall_features.info()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"可以看出，现在的特征只包含18列了，并且都是数值特征","metadata":{}},{"cell_type":"code","source":"import torch\n\n# 从pandas格式中提取NumPy格式，并将其转换为张量表示\nn_train = train_data.shape[0]\ntrain_features = torch.tensor(all_features[:n_train].values,\n                              dtype=torch.float32)\ntest_features = torch.tensor(all_features[n_train:].values,\n                             dtype=torch.float32)\n# 注意课上数据的标签列为SalePrice，与比赛用的标签列名不同\ntrain_labels = torch.tensor(train_data['Sold Price'].values.reshape(-1, 1),\n                            dtype=torch.float32)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch import nn\n\n# 定义模型与损失函数\nloss = nn.MSELoss()\nin_features = train_features.shape[1]\n\ndef get_net():\n    net = nn.Sequential(nn.Linear(in_features, 1))\n    return net","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 我们更关心相对误差，解决这个问题的一种方法是用价格预测的对数来衡量差异\ndef log_rmse(net, features, labels):\n    clipped_preds = torch.clamp(net(features), 1, float('inf'))\n    rmse = torch.sqrt(loss(torch.log(clipped_preds), torch.log(labels)))\n    return rmse.item()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils import data\n\n# Defined in file: ./chapter_linear-networks/linear-regression-concise.md\ndef load_array(data_arrays, batch_size, is_train=True):\n    \"\"\"构造一个PyTorch数据迭代器。\"\"\"\n    dataset = data.TensorDataset(*data_arrays)\n    return data.DataLoader(dataset, batch_size, shuffle=is_train)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 我们的训练函数将借助Adam优化器\ndef train(net, train_features, train_labels, test_features, test_labels,\n          num_epochs, learning_rate, weight_decay, batch_size):\n    train_ls, test_ls = [], []\n    # 注意kaggle环境中没有安装d2l，故用到的地方需要手动定义\n    train_iter = load_array((train_features, train_labels), batch_size)\n    optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate,\n                                 weight_decay=weight_decay)\n    for epoch in range(num_epochs):\n        for X, y in train_iter:\n            optimizer.zero_grad()\n            l = loss(net(X), y)\n            l.backward()\n            optimizer.step()\n        train_ls.append(log_rmse(net, train_features, train_labels))\n        if test_labels is not None:\n            test_ls.append(log_rmse(net, test_features, test_labels))\n    return train_ls, test_ls","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# K折交叉验证\ndef get_k_fold_data(k, i, X, y):\n    assert k > 1\n    fold_size = X.shape[0] // k\n    X_train, y_train = None, None\n    for j in range(k):\n        idx = slice(j * fold_size, (j + 1) * fold_size)\n        X_part, y_part = X[idx, :], y[idx]\n        if j == i:\n            X_valid, y_valid = X_part, y_part\n        elif X_train is None:\n            X_train, y_train = X_part, y_part\n        else:\n            X_train = torch.cat([X_train, X_part], 0)\n            y_train = torch.cat([y_train, y_part], 0)\n    return X_train, y_train, X_valid, y_valid","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 返回训练和验证误差的平均值\ndef k_fold(k, X_train, y_train, num_epochs, learning_rate, weight_decay,\n           batch_size):\n    train_l_sum, valid_l_sum = 0, 0\n    for i in range(k):\n        data = get_k_fold_data(k, i, X_train, y_train)\n        net = get_net()\n        train_ls, valid_ls = train(net, *data, num_epochs, learning_rate,\n                                   weight_decay, batch_size)\n        train_l_sum += train_ls[-1]\n        valid_l_sum += valid_ls[-1]\n        # 删去利用d2l画图的代码\n        print(f'fold {i + 1}, train log rmse {float(train_ls[-1]):f}, '\n              f'valid log rmse {float(valid_ls[-1]):f}')\n    return train_l_sum / k, valid_l_sum / k","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 模型选择\nk, num_epochs, lr, weight_decay, batch_size = 5, 100, 5, 0, 64\ntrain_l, valid_l = k_fold(k, train_features, train_labels, num_epochs, lr,\n                          weight_decay, batch_size)\nprint(f'{k}-折验证: 平均训练log rmse: {float(train_l):f}, '\n      f'平均验证log rmse: {float(valid_l):f}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"考虑到训练集有47439条数据，做交叉验证的时间会比较长，大约需要5分钟\n\n此处超参数直接照搬课件，故损失值比较大","metadata":{}},{"cell_type":"code","source":"# 最后提交前需要确认比赛所需的格式是否和课上数据集有出入\nsample_submission.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 提交你的Kaggle预测\ndef train_and_pred(train_features, test_feature, train_labels, test_data,\n                   num_epochs, lr, weight_decay, batch_size):\n    net = get_net()\n    train_ls, _ = train(net, train_features, train_labels, None, None,\n                        num_epochs, lr, weight_decay, batch_size)\n    # 删去利用d2l画图的代码\n    print(f'train log rmse {float(train_ls[-1]):f}')\n    preds = net(test_features).detach().numpy()\n    # 不出所料，列名需要做替换\n    test_data['Sold Price'] = pd.Series(preds.reshape(1, -1)[0])\n    submission = pd.concat([test_data['Id'], test_data['Sold Price']], axis=1)\n    submission.to_csv('submission.csv', index=False)\n    # 最后返回一下提交的结果，以便查看\n    return submission\n\nsubmission = train_and_pred(train_features, test_features, train_labels, test_data,\n               num_epochs, lr, weight_decay, batch_size)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 查看一下预测结果，以确保格式与样例一致\nsubmission.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"至此就可以向kaggle提交我们的结果了~\n\n如果这篇笔记本对你有帮助，不妨点个赞以满足我小小的虚荣心，爱你哟~","metadata":{}}]}