{"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","execution":{"iopub.status.busy":"2022-01-21T03:14:34.386534Z","iopub.execute_input":"2022-01-21T03:14:34.387333Z","iopub.status.idle":"2022-01-21T03:14:34.400084Z","shell.execute_reply.started":"2022-01-21T03:14:34.387272Z","shell.execute_reply":"2022-01-21T03:14:34.398951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom torch.utils.data import TensorDataset, DataLoader\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport pytorch_lightning as ptl","metadata":{"execution":{"iopub.status.busy":"2022-01-21T03:14:34.403773Z","iopub.execute_input":"2022-01-21T03:14:34.404092Z","iopub.status.idle":"2022-01-21T03:14:34.410093Z","shell.execute_reply.started":"2022-01-21T03:14:34.404062Z","shell.execute_reply":"2022-01-21T03:14:34.408781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = torch.tensor(pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\").to_numpy()[:, 1:], dtype=torch.float32).view(-1, 28, 28)\ny_train = torch.tensor(pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")[\"label\"].to_numpy(), dtype=torch.long).view(-1, 1)\ntrain_dataset = TensorDataset(x_train, y_train)\n\nx_test = torch.tensor(pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\").to_numpy(), dtype=torch.float32).view(-1, 28, 28)\ntest_dataset = TensorDataset(x_test)","metadata":{"execution":{"iopub.status.busy":"2022-01-21T03:14:34.411487Z","iopub.execute_input":"2022-01-21T03:14:34.412311Z","iopub.status.idle":"2022-01-21T03:14:42.025755Z","shell.execute_reply.started":"2022-01-21T03:14:34.412267Z","shell.execute_reply":"2022-01-21T03:14:42.024666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DigitNN(ptl.LightningModule):\n    def __init__(self):\n        super().__init__()\n        #self.layers = nn.Sequential(\n        #    nn.Linear(28 * 28, 128), \n        #    nn.ReLU(), \n        #    nn.Linear(128, 10)\n        #)\n        \n        self.cnn = nn.Sequential(\n            nn.Conv2d(1, 256, 3), \n            nn.ReLU(), \n            nn.Conv2d(256, 256, 3),\n            nn.ReLU(),\n            nn.Conv2d(256, 256, 3), \n            nn.ReLU(), \n            nn.Conv2d(256, 32, 3),\n            nn.ReLU(),\n        )\n        \n        self.linear = nn.Sequential(\n            nn.Linear(32 * 20 * 20, 128), \n            nn.ReLU(), \n            nn.Linear(128, 10)\n        )\n\n    def _forward(self, x):\n        #return self.layers(x.view(x.size(0), -1))\n        x = self.cnn(x.unsqueeze(1))\n        #print(x.shape)\n        return self.linear(x.view(x.shape[0], -1))\n        \n    def forward(self, x):\n        #print(len(x))\n        return self._forward(x[0]).argmax()\n\n    def training_step(self, batch, batch_idx):\n        # training_step defines the train loop. It is independent of forward\n        #print(len(batch))\n        x, y = batch\n        y_hat = self._forward(x)\n        #print(y)\n        #print(y_hat)\n        loss = F.cross_entropy(y_hat, y.squeeze(1))\n        self.log(\"train_loss\", loss)\n        return loss\n\n    def configure_optimizers(self):\n        optimizer = torch.optim.Adam(self.parameters(), lr=1e-5)\n        return optimizer","metadata":{"execution":{"iopub.status.busy":"2022-01-21T03:14:42.027764Z","iopub.execute_input":"2022-01-21T03:14:42.028042Z","iopub.status.idle":"2022-01-21T03:14:42.041039Z","shell.execute_reply.started":"2022-01-21T03:14:42.028001Z","shell.execute_reply":"2022-01-21T03:14:42.039986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = DigitNN()\ntrainer = ptl.Trainer(max_epochs=30, accelerator=\"gpu\", gpus=1)\ntrainer.fit(model, DataLoader(train_dataset, batch_size=64))","metadata":{"execution":{"iopub.status.busy":"2022-01-21T03:14:42.042343Z","iopub.execute_input":"2022-01-21T03:14:42.043376Z","iopub.status.idle":"2022-01-21T03:23:56.588524Z","shell.execute_reply.started":"2022-01-21T03:14:42.04333Z","shell.execute_reply":"2022-01-21T03:23:56.587595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = trainer.predict(model, DataLoader(test_dataset))","metadata":{"execution":{"iopub.status.busy":"2022-01-21T03:23:56.590406Z","iopub.execute_input":"2022-01-21T03:23:56.590839Z","iopub.status.idle":"2022-01-21T03:24:39.171367Z","shell.execute_reply.started":"2022-01-21T03:23:56.590797Z","shell.execute_reply":"2022-01-21T03:24:39.170491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results_df = pd.DataFrame({\"ImageId\":range(1, 1 + len(preds)), \"Label\":[p.item() for p in preds]})\nresults_df.to_csv(\"submission.csv\", index=False)\nprint(results_df)","metadata":{"execution":{"iopub.status.busy":"2022-01-21T03:24:39.172979Z","iopub.execute_input":"2022-01-21T03:24:39.173911Z","iopub.status.idle":"2022-01-21T03:24:39.617375Z","shell.execute_reply.started":"2022-01-21T03:24:39.173859Z","shell.execute_reply":"2022-01-21T03:24:39.615478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.device","metadata":{"execution":{"iopub.status.busy":"2022-01-21T03:24:39.619391Z","iopub.execute_input":"2022-01-21T03:24:39.619642Z","iopub.status.idle":"2022-01-21T03:24:39.627346Z","shell.execute_reply.started":"2022-01-21T03:24:39.61961Z","shell.execute_reply":"2022-01-21T03:24:39.626042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}