{"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":"markdown","source":"这个方法完全仿照课上PPT的做法。","metadata":{}},{"cell_type":"markdown","source":"## 导入数据","metadata":{}},{"cell_type":"code","source":"pip install -U d2l","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:11.098862Z","iopub.execute_input":"2021-06-11T01:55:11.09937Z","iopub.status.idle":"2021-06-11T01:55:19.411646Z","shell.execute_reply.started":"2021-06-11T01:55:11.099339Z","shell.execute_reply":"2021-06-11T01:55:19.410164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport torch\nfrom torch import nn\nfrom d2l import torch as d2l\n\ntrain_data = pd.read_csv(\"../input/california-house-prices/train.csv\")\ntest_data = pd.read_csv(\"../input/california-house-prices/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:19.413911Z","iopub.execute_input":"2021-06-11T01:55:19.414326Z","iopub.status.idle":"2021-06-11T01:55:20.547035Z","shell.execute_reply.started":"2021-06-11T01:55:19.414278Z","shell.execute_reply":"2021-06-11T01:55:20.545914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train_data.shape)\nprint(test_data.shape)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:20.550082Z","iopub.execute_input":"2021-06-11T01:55:20.55056Z","iopub.status.idle":"2021-06-11T01:55:20.557236Z","shell.execute_reply.started":"2021-06-11T01:55:20.550502Z","shell.execute_reply":"2021-06-11T01:55:20.556055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"其中*trian_data*比*test_data*多了一列，这一列就是我们要预测的房价。","metadata":{}},{"cell_type":"code","source":"[i for i in train_data.columns if i not in test_data.columns]","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:20.559318Z","iopub.execute_input":"2021-06-11T01:55:20.560102Z","iopub.status.idle":"2021-06-11T01:55:20.57257Z","shell.execute_reply.started":"2021-06-11T01:55:20.560057Z","shell.execute_reply":"2021-06-11T01:55:20.571129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"从上面可以看出，我们要预测的房价列名为```Sold Price```","metadata":{}},{"cell_type":"markdown","source":"## 数据预处理","metadata":{}},{"cell_type":"markdown","source":"### 特征选择","metadata":{}},{"cell_type":"markdown","source":"因为kaggle上内存有限，需要选择好哪些特征再进行下一步操作，以免超限。","metadata":{}},{"cell_type":"markdown","source":"为了让训练集和测试集一起完成数据预处理，还需要```cancat```。","metadata":{}},{"cell_type":"markdown","source":"我们先需要看一下train_data和test_data有哪些特征：","metadata":{}},{"cell_type":"code","source":"train_data.columns","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:20.574482Z","iopub.execute_input":"2021-06-11T01:55:20.574995Z","iopub.status.idle":"2021-06-11T01:55:20.5862Z","shell.execute_reply.started":"2021-06-11T01:55:20.574949Z","shell.execute_reply":"2021-06-11T01:55:20.584808Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data.columns","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:20.587771Z","iopub.execute_input":"2021-06-11T01:55:20.588561Z","iopub.status.idle":"2021-06-11T01:55:20.599145Z","shell.execute_reply.started":"2021-06-11T01:55:20.588479Z","shell.execute_reply":"2021-06-11T01:55:20.597542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"train_data中```Sold Price```需要剔除，因为是标签。\ntrain_data和test_data中的```Id```需要剔除，因为和结果无关。","metadata":{}},{"cell_type":"markdown","source":"除此之外，因为都是加州的房子，需要剔除```State```;```Summary```是文本数据，分析有限就直接剔除，同理```Address```：每个房子的地址都不同，如果进行独热编码负担太大，分析也有限，所以也剔除。","metadata":{}},{"cell_type":"code","source":"all_features = pd.concat((train_data.iloc[:, 4:-1], test_data.iloc[:, 3:-1]))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:20.600846Z","iopub.execute_input":"2021-06-11T01:55:20.601412Z","iopub.status.idle":"2021-06-11T01:55:20.685363Z","shell.execute_reply.started":"2021-06-11T01:55:20.601338Z","shell.execute_reply":"2021-06-11T01:55:20.684204Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_features.shape","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:20.689286Z","iopub.execute_input":"2021-06-11T01:55:20.689737Z","iopub.status.idle":"2021-06-11T01:55:20.696757Z","shell.execute_reply.started":"2021-06-11T01:55:20.689694Z","shell.execute_reply":"2021-06-11T01:55:20.695219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 处理缺失数据","metadata":{}},{"cell_type":"markdown","source":"先看一下有哪些列有缺失值：","metadata":{}},{"cell_type":"code","source":"missing_values_count = all_features.isnull().sum()\n\n# look at the # of missing points in the first ten columns\nmissing_values_count.loc[missing_values_count>0]","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:20.699863Z","iopub.execute_input":"2021-06-11T01:55:20.700803Z","iopub.status.idle":"2021-06-11T01:55:20.835133Z","shell.execute_reply.started":"2021-06-11T01:55:20.700716Z","shell.execute_reply":"2021-06-11T01:55:20.833623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"所以数据集中缺失值占数据总数的......?","metadata":{}},{"cell_type":"code","source":"total_cells = np.product(all_features.shape)\ntotal_missing = missing_values_count.sum()\n\n# percent of data that is missing\npercent_missing = (total_missing/total_cells) * 100\nprint(percent_missing)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:20.837091Z","iopub.execute_input":"2021-06-11T01:55:20.837631Z","iopub.status.idle":"2021-06-11T01:55:20.845084Z","shell.execute_reply.started":"2021-06-11T01:55:20.837586Z","shell.execute_reply":"2021-06-11T01:55:20.843735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_features = all_features.fillna(method='bfill', axis=0).fillna(0)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:20.847209Z","iopub.execute_input":"2021-06-11T01:55:20.848189Z","iopub.status.idle":"2021-06-11T01:55:21.154573Z","shell.execute_reply.started":"2021-06-11T01:55:20.848141Z","shell.execute_reply":"2021-06-11T01:55:21.153323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"来验证一下，NA是否都去除了：","metadata":{}},{"cell_type":"code","source":"missing_values_count = all_features.isnull().sum()\n\n# look at the # of missing points in the first ten columns\nmissing_values_count.loc[missing_values_count>0]","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.156445Z","iopub.execute_input":"2021-06-11T01:55:21.156968Z","iopub.status.idle":"2021-06-11T01:55:21.294005Z","shell.execute_reply.started":"2021-06-11T01:55:21.156918Z","shell.execute_reply":"2021-06-11T01:55:21.292589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 处理日期数据","metadata":{}},{"cell_type":"code","source":"all_features.columns","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.296028Z","iopub.execute_input":"2021-06-11T01:55:21.296524Z","iopub.status.idle":"2021-06-11T01:55:21.304614Z","shell.execute_reply.started":"2021-06-11T01:55:21.296443Z","shell.execute_reply":"2021-06-11T01:55:21.303185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(all_features['Listed On'].head())\nprint(all_features['Last Sold On'].head())","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.306533Z","iopub.execute_input":"2021-06-11T01:55:21.307088Z","iopub.status.idle":"2021-06-11T01:55:21.321534Z","shell.execute_reply.started":"2021-06-11T01:55:21.307043Z","shell.execute_reply":"2021-06-11T01:55:21.320062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_features['Listed On'] = pd.to_datetime(all_features['Listed On'], format=\"%Y-%m-%d\")","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.323221Z","iopub.execute_input":"2021-06-11T01:55:21.32392Z","iopub.status.idle":"2021-06-11T01:55:21.35149Z","shell.execute_reply.started":"2021-06-11T01:55:21.323877Z","shell.execute_reply":"2021-06-11T01:55:21.350513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_features['Last Sold On'] = pd.to_datetime(all_features['Last Sold On'], format=\"%Y-%m-%d\")","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.353091Z","iopub.execute_input":"2021-06-11T01:55:21.353578Z","iopub.status.idle":"2021-06-11T01:55:21.384489Z","shell.execute_reply.started":"2021-06-11T01:55:21.35353Z","shell.execute_reply":"2021-06-11T01:55:21.383386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"验证一下dtype：","metadata":{}},{"cell_type":"code","source":"print(all_features['Listed On'].head())\nprint(all_features['Last Sold On'].head())","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.38603Z","iopub.execute_input":"2021-06-11T01:55:21.386487Z","iopub.status.idle":"2021-06-11T01:55:21.396513Z","shell.execute_reply.started":"2021-06-11T01:55:21.386423Z","shell.execute_reply":"2021-06-11T01:55:21.395067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 标准化","metadata":{}},{"cell_type":"markdown","source":"看一下现在all_features中的数据有哪些类型：","metadata":{}},{"cell_type":"code","source":"all_features.dtypes.unique()","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.39839Z","iopub.execute_input":"2021-06-11T01:55:21.399407Z","iopub.status.idle":"2021-06-11T01:55:21.409848Z","shell.execute_reply.started":"2021-06-11T01:55:21.399347Z","shell.execute_reply":"2021-06-11T01:55:21.408026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"numeric_features = all_features.dtypes[all_features.dtypes == 'float64'].index\nall_features[numeric_features] = all_features[numeric_features].apply(\n    lambda x: (x - x.mean()) / (x.std()))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.411703Z","iopub.execute_input":"2021-06-11T01:55:21.412369Z","iopub.status.idle":"2021-06-11T01:55:21.489739Z","shell.execute_reply.started":"2021-06-11T01:55:21.412313Z","shell.execute_reply":"2021-06-11T01:55:21.488636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###  独热编码\n\n查看一下all_features中类型为object的特征有哪些：","metadata":{}},{"cell_type":"code","source":"all_features.dtypes[all_features.dtypes=='object']","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.491332Z","iopub.execute_input":"2021-06-11T01:55:21.49191Z","iopub.status.idle":"2021-06-11T01:55:21.502193Z","shell.execute_reply.started":"2021-06-11T01:55:21.491858Z","shell.execute_reply":"2021-06-11T01:55:21.500735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"为了提高独热编码时的质量，我们看一下这些object类型中是否存在数据不一致的情况：","metadata":{}},{"cell_type":"code","source":"print(len(all_features['Type'].unique()))\nprint(len(all_features['Heating'].unique()))\nprint(len(all_features['Cooling'].unique()))\nprint(len(all_features['Parking'].unique()))\nprint(len(all_features['Bedrooms'].unique()))\nprint(len(all_features['Region'].unique()))\nprint(len(all_features['Elementary School'].unique()))\nprint(len(all_features['Middle School'].unique()))\nprint(len(all_features['High School'].unique()))\nprint(len(all_features['Flooring'].unique()))\nprint(len(all_features['Heating features'].unique()))\nprint(len(all_features['Cooling features'].unique()))\nprint(len(all_features['Appliances included'].unique()))\nprint(len(all_features['Laundry features'].unique()))\nprint(len(all_features['Parking features'].unique()))\nprint(len(all_features['City'].unique()))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.504195Z","iopub.execute_input":"2021-06-11T01:55:21.504917Z","iopub.status.idle":"2021-06-11T01:55:21.651488Z","shell.execute_reply.started":"2021-06-11T01:55:21.504871Z","shell.execute_reply":"2021-06-11T01:55:21.65001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"从上面各个长度可以看出，特征包含的类别数太多，我们来看一下是什么情况：","metadata":{}},{"cell_type":"code","source":"all_features['Appliances included']","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.653227Z","iopub.execute_input":"2021-06-11T01:55:21.653686Z","iopub.status.idle":"2021-06-11T01:55:21.662229Z","shell.execute_reply.started":"2021-06-11T01:55:21.653642Z","shell.execute_reply":"2021-06-11T01:55:21.661003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"除了```Appliances included```以外，其他数量很大的类别也都是用逗号分隔的多类别文本数据。因为现在我的水平有限，不太知道这种数据怎么编码，所以决定把它们都剔除掉：","metadata":{}},{"cell_type":"code","source":"features = list(numeric_features)\nfeatures.append('Type')   # 加上类别数相对较少的Type\nprint(features)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.667796Z","iopub.execute_input":"2021-06-11T01:55:21.668688Z","iopub.status.idle":"2021-06-11T01:55:21.675551Z","shell.execute_reply.started":"2021-06-11T01:55:21.66849Z","shell.execute_reply":"2021-06-11T01:55:21.674329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_features = all_features[features]","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.677863Z","iopub.execute_input":"2021-06-11T01:55:21.678696Z","iopub.status.idle":"2021-06-11T01:55:21.69121Z","shell.execute_reply.started":"2021-06-11T01:55:21.678653Z","shell.execute_reply":"2021-06-11T01:55:21.690014Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_features.shape","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.692826Z","iopub.execute_input":"2021-06-11T01:55:21.693182Z","iopub.status.idle":"2021-06-11T01:55:21.706934Z","shell.execute_reply.started":"2021-06-11T01:55:21.693153Z","shell.execute_reply":"2021-06-11T01:55:21.705487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"进行编码：","metadata":{}},{"cell_type":"code","source":"all_features = pd.get_dummies(all_features, dummy_na=True)\nall_features.shape","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.708937Z","iopub.execute_input":"2021-06-11T01:55:21.709471Z","iopub.status.idle":"2021-06-11T01:55:21.783315Z","shell.execute_reply.started":"2021-06-11T01:55:21.709406Z","shell.execute_reply":"2021-06-11T01:55:21.78181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 转为张量","metadata":{}},{"cell_type":"code","source":"n_train = train_data.shape[0]\ntrain_features = torch.tensor(all_features[:n_train].values, dtype=torch.float32)\ntest_features = torch.tensor(all_features[n_train:].values, dtype=torch.float32)\ntrain_labels = torch.tensor(train_data['Sold Price'].values.reshape(-1,1), dtype=torch.float32)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.785394Z","iopub.execute_input":"2021-06-11T01:55:21.785944Z","iopub.status.idle":"2021-06-11T01:55:21.870956Z","shell.execute_reply.started":"2021-06-11T01:55:21.785896Z","shell.execute_reply":"2021-06-11T01:55:21.869784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 训练","metadata":{}},{"cell_type":"code","source":"loss = nn.MSELoss()\nin_features = train_features.shape[1]\n\ndef get_net():\n    net = nn.Sequential(nn.Linear(in_features,256), nn.ReLU(), nn.Linear(256,1))  \n    #net = nn.Sequential(nn.Linear(in_features, 1))\n    return net","metadata":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.872694Z","iopub.execute_input":"2021-06-11T01:55:21.873459Z","iopub.status.idle":"2021-06-11T01:55:21.881121Z","shell.execute_reply.started":"2021-06-11T01:55:21.8734Z","shell.execute_reply":"2021-06-11T01:55:21.879536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 选取loss函数：\n\n因为不同区域的房价绝对数值相差很大，我们更关心相对误差：$\\frac{y - \\hat{y}}{y}$，所以我们定义loss为：\n\n$$\\sqrt{\\frac{1}{n}\\sum_{i=1}^n\\left(\\log y_i -\\log \\hat{y}_i\\right)^2}.$$","metadata":{}},{"cell_type":"code","source":"def log_rmse(net, features, labels):\n    # 为了在取对数时进一步稳定该值，将小于1的值设置为1\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":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.883064Z","iopub.execute_input":"2021-06-11T01:55:21.883653Z","iopub.status.idle":"2021-06-11T01:55:21.89322Z","shell.execute_reply.started":"2021-06-11T01:55:21.883484Z","shell.execute_reply":"2021-06-11T01:55:21.89221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 训练函数","metadata":{}},{"cell_type":"code","source":"def train(net, train_features, train_labels, test_features, test_labels,\n          num_epochs, learning_rate, weight_decay, batch_size):\n    train_ls, test_ls = [], []   # train_loss和test_loss\n    train_iter = d2l.load_array((train_features, train_labels), batch_size)\n    # 这里使用的是Adam优化算法，对初始学习率没有那么敏感\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":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.895214Z","iopub.execute_input":"2021-06-11T01:55:21.895768Z","iopub.status.idle":"2021-06-11T01:55:21.910112Z","shell.execute_reply.started":"2021-06-11T01:55:21.895724Z","shell.execute_reply":"2021-06-11T01:55:21.909026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### k折交叉验证","metadata":{}},{"cell_type":"code","source":"def 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":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.911919Z","iopub.execute_input":"2021-06-11T01:55:21.912516Z","iopub.status.idle":"2021-06-11T01:55:21.923024Z","shell.execute_reply.started":"2021-06-11T01:55:21.912327Z","shell.execute_reply":"2021-06-11T01:55:21.92157Z"},"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        if i == 0:\n            d2l.plot(list(range(1, num_epochs + 1)), [train_ls, valid_ls],\n                     xlabel='epoch', ylabel='rmse', xlim=[1, num_epochs],\n                     legend=['train', 'valid'], yscale='log')\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":{"execution":{"iopub.status.busy":"2021-06-11T01:55:21.924719Z","iopub.execute_input":"2021-06-11T01:55:21.925179Z","iopub.status.idle":"2021-06-11T01:55:21.938322Z","shell.execute_reply.started":"2021-06-11T01:55:21.925136Z","shell.execute_reply":"2021-06-11T01:55:21.937139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 模型选择","metadata":{}},{"cell_type":"code","source":"k, num_epochs, lr, weight_decay, batch_size = 5, 100, 0.1, 0.1, 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":{"execution":{"iopub.status.busy":"2021-06-11T02:03:10.312001Z","iopub.execute_input":"2021-06-11T02:03:10.312369Z","iopub.status.idle":"2021-06-11T02:03:45.737295Z","shell.execute_reply.started":"2021-06-11T02:03:10.312337Z","shell.execute_reply":"2021-06-11T02:03:45.733882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"在模型选择的过程中发现，有的参数会使loss随着epoch增加波动过大，而不是稳定下降。这种情况很可能是因为batch_size不够大，模型不稳定，可以增大batch_size来缓解。","metadata":{}},{"cell_type":"markdown","source":"## 预测","metadata":{}},{"cell_type":"code","source":"def 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.plot(np.arange(1, num_epochs + 1), [train_ls], xlabel='epoch',\n             ylabel='log rmse', xlim=[1, num_epochs], yscale='log')\n    print(f'train log rmse {float(train_ls[-1]):f}')\n    # 将网络应用于测试集。\n    preds = net(test_features).detach().numpy()\n    # 将其重新格式化以导出到Kaggle\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)","metadata":{"execution":{"iopub.status.busy":"2021-06-10T08:44:22.128686Z","iopub.execute_input":"2021-06-10T08:44:22.129004Z","iopub.status.idle":"2021-06-10T08:44:22.136943Z","shell.execute_reply.started":"2021-06-10T08:44:22.128976Z","shell.execute_reply":"2021-06-10T08:44:22.13592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_and_pred(train_features, test_features, train_labels, test_data,\n               num_epochs, lr, weight_decay, batch_size)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T00:48:53.711734Z","iopub.execute_input":"2021-06-11T00:48:53.712224Z","iopub.status.idle":"2021-06-11T00:48:53.743148Z","shell.execute_reply.started":"2021-06-11T00:48:53.712177Z","shell.execute_reply":"2021-06-11T00:48:53.740054Z"},"trusted":true},"execution_count":null,"outputs":[]}]}