{"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":"# 参考与前言\n\n1. 课程链接：[跟李沐学AI的个人空间_哔哩哔哩_bilibili](https://space.bilibili.com/1567748478/channel/seriesdetail?sid=358497)\n2. 课程主页：[https://zh-v2.d2l.ai/chapter_multilayer-perceptrons/kaggle-house-price.html](https://zh-v2.d2l.ai/chapter_multilayer-perceptrons/kaggle-house-price.html)\n3. 相关代码参考：[https://www.kaggle.com/alexandreazhang/using-dl-to-predict-housing-prices/notebook](https://www.kaggle.com/alexandreazhang/using-dl-to-predict-housing-prices/notebook)\n\n本部分主要用于记录自己做第一次作业的一些感受 主要是emmm 也是第一次看这么仔细，虽然最后还是不如沐神的十行代码 hhhh 但是还是总结一下较好，本来是想弄一弄懂注意力那个算法是咋个计算方式 还有最近看的GRU那几个点，但是沐神太吸引人了 hhh 所以就实战了一下 基本上也算是做了一天左右 emmm 发布于：https://blog.csdn.net/qq_39537898/article/details/122096996\n\n首先遇到的问题：\n1. one hot后太多feature了\n2. learning_rate 一开始直接成0了\n3. 后面有遇到梯度爆炸情况，虽然有weight_decay 但是emm 好像哪里不太对\n\n放张图感受一下 内心一起爆炸\n\n<center>\n<img src=\"https://img-blog.csdnimg.cn/bf9aa20098d44ff2aa687f5f6f1f5567.png\" width=\"100%\">\n</center>\n\n提醒用了wandb 非常好用的一个好东西，这是最后比较好的结果，大概几分钟就训完了，大概就是上面那个爆炸前 因为我设了中间保存模型的点，大概是350处的模型进行评估的：\n\n![在这里插入图片描述](https://img-blog.csdnimg.cn/4ae15ef99ff1487abd70e962d6a2d487.png)\n\n# 1. 模型\n\n## MLP简单版\n\n```python\nimport torch\nimport pandas as pd\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom tqdm import tqdm\nimport numpy as np\nfrom torch.utils import data\nimport wandb\n\nclass MLP(nn.Module):\n    def __init__(self, in_features):\n        super().__init__()\n        self.layer1 = nn.Linear(in_features,256)\n        self.layer2 = nn.Linear(256,64)\n        self.out = nn.Linear(64,1)\n        \n    def forward(self, X):\n        X = F.relu(self.layer1(X))\n        X = F.relu(self.layer2(X))\n        return self.out(X)\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n```\n\n注意因为我大概看了我的in_features 最后470多 512不太合适 所以就256了\n\n其他就是forward里面加relu，说实话我最近才意识到 原来激活函数是非线性化的，而relu是其中一个计算开销最小的激活函数。恕我之前都是 直接用就完事了 resnet yyds 😂\n\n## Loss选取\n\n和ppt选的一样 但是自己看的时候以kaggle上面说的rmse来看的哈\n\n```python\ncriterion = nn.MSELoss()\ndef load_array(data_arrays, batch_size, is_train=True):  #@save\n    \"\"\"Construct a PyTorch data iterator.\"\"\"\n    dataset = data.TensorDataset(*data_arrays)\n    return data.DataLoader(dataset, batch_size, shuffle=is_train)\n\ndef log_rmse(net, features, labels):\n    # 为了在取对数时进一步稳定该值，将小于1的值设置为1\n    clipped_preds = torch.clamp(net(features), 1, float('inf'))\n    rmse = torch.sqrt(criterion(torch.log(clipped_preds),\n                           torch.log(labels)))\n    return rmse.item()\n```\n\n# 2. 数据处理\n\n## 导入数据\n\n```python\ntest_data = pd.read_csv('test.csv')\ntrain_data = pd.read_csv('train.csv')\nprint(\"train_data and test_data shape\",train_data.shape,test_data.shape)\n```\n\n这一步没啥好讲的 emmm 就是这样 read_csv一下就行了\n\n## 预处理\n\n```python\n# 去掉冗余数据\nredundant_cols = ['Address', 'Summary', 'City', 'State']\nfor c in redundant_cols:\n    del test_data[c], train_data[c]\n    \n# 数据预处理\nlarge_vel_cols = ['Lot', 'Total interior livable area', 'Tax assessed value', 'Annual tax amount', 'Listed Price', 'Last Sold Price']\nfor c in large_vel_cols:\n    train_data[c] = np.log(train_data[c]+1)\n    test_data[c] = np.log(test_data[c]+1)\n```\n\n预处理是因为有些数字比较大 所以需要取一下log进行数据处理，虽然我并没有对最终的Sold Price进行处理 因为好像试了一下效果不好？\n\n```python\n# 查询数字列 ->缺失数据赋0 -> 归一化\nnumeric_features = all_features.dtypes[all_features.dtypes == 'float64'].index\nall_features = all_features.fillna(method='bfill', axis=0).fillna(0)\nall_features[numeric_features] = all_features[numeric_features].apply(lambda x: (x - x.mean()) / (x.std()))\n```\n\n首先在one-hot之前，我们需要看一下非数字的object都有哪些并且他们大概有多少个不同的类别：\n\n```python\nfor in_object in all_features.dtypes[all_features.dtypes=='object'].index:\n    print(in_object.ljust(20),len(all_features[in_object].unique()))\n```\n\n输出为：\n\n```bash\nType                 174\nHeating              2660\nCooling              911\nParking              9913\nBedrooms             278\nRegion               1259\nElementary School    3568\nMiddle School        809\nHigh School          922\nFlooring             1740\nHeating features     1763\nCooling features     596\nAppliances included  11290\nLaundry features     3031\nParking features     9695\n```\n\n所以呢，我大概就只选了前两个个\n\n```python\nfeatures = list(numeric_features)\n# 加上类别数相对较少的Type\nfeatures.extend(['Type','Bedrooms'])\nall_features = all_features[features]\n```\n\n## one-hot\n\n这样进入one-hot后的feature也不会让内存爆炸了，是的... 我一开始只顾着删除地址和summary，其他我以为都可以one-hot，直到看到参考的链接才发现噢 原来有这么多类型 emmm：\n\n```python\nprint('before one hot code',all_features.shape)\nall_features = pd.get_dummies(all_features,dummy_na=True)\nprint('after one hot code',all_features.shape)\n\nn_train = train_data.shape[0]\ntrain_features = torch.tensor(all_features[:n_train].values, dtype=torch.float)\nprint('train feature shape:', train_features.shape)\ntest_features = torch.tensor(all_features[n_train:].values, dtype=torch.float)\nprint('test feature shape:', test_features.shape)\ntrain_labels = torch.tensor(train_data['Sold Price'].values.reshape(-1, 1), dtype=torch.float)\nprint('train label shape:', train_labels.shape)\n```\n\n输出：\n\n```bash\nbefore one hot code (79065, 19)\nafter one hot code (79065, 470)\ntrain feature shape: torch.Size([47439, 470])\ntest feature shape: torch.Size([31626, 470])\ntrain label shape: torch.Size([47439, 1])\n```\n\n# 3. 训练步骤\n\n## train function\n\n```python\nin_features = train_features.shape[1]\nnet = MLP(in_features).to(device)\n\ndef train(net, train_features, train_labels, test_features, test_labels,\n          num_epochs, learning_rate, weight_decay, batch_size):\n    wandb.watch(net)\n    train_ls, test_ls = [], []\n    train_iter = load_array((train_features, train_labels), batch_size)\n    # 这里使用的是Adam优化算法\n    optimizer = torch.optim.Adam(net.parameters(), lr = learning_rate, weight_decay = weight_decay)\n    for epoch in tqdm(range(num_epochs)):\n        for X, y in train_iter:\n            X, y = X.to(device), y.to(device)\n            optimizer.zero_grad()\n            outputs = net(X)\n            loss = criterion(outputs, y)\n            loss.backward()\n            optimizer.step()\n        record_loss = log_rmse(net.to('cpu'), train_features, train_labels)\n        wandb.log({'loss': record_loss,'epoch': epoch})\n        train_ls.append(record_loss)\n        if (epoch%NUM_SAVE==0 and epoch!=0) or (epoch==num_epochs-1):\n            torch.save(net.state_dict(),'checkpoint_'+str(epoch))\n            print('save checkpoints on:', epoch, 'rmse loss value is:', record_loss)\n        del X, y\n        net.to(device)\n    wandb.finish()\n    return train_ls, test_ls\n\n# 初始化wandb 进行记录\nnum_epochs, lr, weight_decay, batch_size = 500, 0.005, 0.05, 256\nwandb.init(project=\"kaggle_predict\",\n           config={ \"learning_rate\": lr,\n                    \"weight_decay\": weight_decay,\n                    \"batch_size\": batch_size,\n                    \"total_run\": num_epochs,\n                    \"network\": net_list}\n          )\nprint(\"network:\",net)\n```\n\n## train\n\n```python\ntrain_ls, valid_ls = train(net, train_features,train_labels,None,None, num_epochs, lr, weight_decay, batch_size)\n\n# 使用现有训练好的net\nnet.to('cpu')\n# 将网络应用于测试集。\npreds = net(test_features).detach().numpy()\n\n# 将其重新格式化以导出到Kaggle\ntest_data['Sold Price'] = pd.Series(preds.reshape(1, -1)[0])\nsubmission = pd.concat([test_data['Id'], test_data['Sold Price']], axis=1)\nsubmission.to_csv('submission.csv', index=False)\n```\n\n# 4. 结果\n\n<center>\n<img src=\"https://img-blog.csdnimg.cn/bf9aa20098d44ff2aa687f5f6f1f5567.png\" width=\"100%\">\n</center>\n\n正如一开始的图那样，可以看到在400之前 一切都还挺正常，而直接使用 350处的模型文件进行predict，比如这样：就可以大概得到差不多的\n\n```python\n# 读取网络参数应用于测试集\nnet = []\nnet = MLP(test_features.shape[1])\nnet.load_state_dict(torch.load('checkpoint_350'))\nnet.to('cpu')\npreds = net(test_features).detach().numpy()\n# 将其重新格式化以导出到Kaggle\ntest_data['Sold Price'] = pd.Series(preds.reshape(1, -1)[0])\nsubmission = pd.concat([test_data['Id'], test_data['Sold Price']], axis=1)\nsubmission.to_csv('submission.csv', index=False)\n```\n\n提交kaggle submission file后即：\n\n![在这里插入图片描述](https://img-blog.csdnimg.cn/4ae15ef99ff1487abd70e962d6a2d487.png)\n## 碎碎念\n虽然并没有超过... 沐神十行代码的 但是 我觉得是因为沐神用了AutoML 都不用调参，真就啥啥不需要，详情见：[10行代码战胜90%数据科学家？_哔哩哔哩_bilibili](https://www.bilibili.com/video/BV1rh411m7Hb)\n\n不过我感觉差不多就这样了 后面也MLP 也就是再多搞点特征进来，或者融一下transfomer进行解读文本信息等 emmm\n","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}