{"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":"# Imports","metadata":{}},{"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)\nfrom sklearn.model_selection import train_test_split\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":"2023-05-04T22:49:05.378502Z","iopub.execute_input":"2023-05-04T22:49:05.378963Z","iopub.status.idle":"2023-05-04T22:49:06.053250Z","shell.execute_reply.started":"2023-05-04T22:49:05.378926Z","shell.execute_reply":"2023-05-04T22:49:06.052238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom torch import nn\nfrom torch.utils.data import Dataset, DataLoader\n!pip install lightning\nimport lightning.pytorch as pl\n\ndevice = torch.device(\"cpu\")","metadata":{"execution":{"iopub.status.busy":"2023-05-04T22:49:06.055366Z","iopub.execute_input":"2023-05-04T22:49:06.056100Z","iopub.status.idle":"2023-05-04T22:49:36.466852Z","shell.execute_reply.started":"2023-05-04T22:49:06.056061Z","shell.execute_reply":"2023-05-04T22:49:36.465836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Base and Deep Models with PyTorch","metadata":{}},{"cell_type":"code","source":"class MNISTDataset(Dataset):\n    def __init__(self, input_path):\n        self.data = pd.read_csv(input_path)\n        self.x = self.data.drop('label', axis=1).values\n        self.y = self.data['label'].values\n        \n    def __len__(self):\n        return len(self.data)\n    \n    def __getitem__(self, index):\n        return torch.tensor(self.x[index], dtype=torch.float32), torch.tensor(self.y[index])","metadata":{"execution":{"iopub.status.busy":"2023-05-04T22:49:36.471604Z","iopub.execute_input":"2023-05-04T22:49:36.474280Z","iopub.status.idle":"2023-05-04T22:49:36.483063Z","shell.execute_reply.started":"2023-05-04T22:49:36.474245Z","shell.execute_reply":"2023-05-04T22:49:36.482133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class BaseModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.model = nn.Sequential(\n            nn.Linear(784, 64),\n            nn.ReLU(),\n            nn.Linear(64, 10),\n        )\n    \n    def forward(self, x):\n        return self.model(x)\n    \n    \nclass DeepModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.model = nn.Sequential(\n            nn.Linear(784, 128),\n            nn.ReLU(),\n            nn.Linear(128, 64),\n            nn.ReLU(),\n            nn.Linear(64, 32),\n            nn.ReLU(),\n            nn.Linear(32, 16),\n            nn.ReLU(),\n            nn.Linear(16, 10)\n        )\n        \n    def forward(self, x):\n        return self.model(x)","metadata":{"execution":{"iopub.status.busy":"2023-05-04T22:49:36.489376Z","iopub.execute_input":"2023-05-04T22:49:36.492245Z","iopub.status.idle":"2023-05-04T22:49:36.501991Z","shell.execute_reply.started":"2023-05-04T22:49:36.492213Z","shell.execute_reply":"2023-05-04T22:49:36.500967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SAMPLE = \"/kaggle/input/digit-recognizer/sample_submission.csv\"\nTRAIN = \"/kaggle/input/digit-recognizer/train.csv\"\nTEST = \"/kaggle/input/digit-recognizer/test.csv\"\nWORKING = \"/kaggle/working\"\nVAL_OUT = WORKING + \"/val.csv\"\nTRAIN_OUT = WORKING + \"/train.csv\"\n\ntrain_df = pd.read_csv(TRAIN)\ntrain_df, val_df = train_test_split(train_df, test_size=0.2, random_state=42)\n\nval_df.to_csv(VAL_OUT, index=False)\ntrain_df.to_csv(TRAIN_OUT, index=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-04T22:49:36.506551Z","iopub.execute_input":"2023-05-04T22:49:36.507149Z","iopub.status.idle":"2023-05-04T22:49:45.802692Z","shell.execute_reply.started":"2023-05-04T22:49:36.507118Z","shell.execute_reply":"2023-05-04T22:49:45.801727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = MNISTDataset(TRAIN_OUT)\nval_dataset = MNISTDataset(VAL_OUT)\ntrain_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=4)\nval_loader = DataLoader(val_dataset, batch_size=32, shuffle=False, num_workers=4)","metadata":{"execution":{"iopub.status.busy":"2023-05-04T22:49:45.804137Z","iopub.execute_input":"2023-05-04T22:49:45.804499Z","iopub.status.idle":"2023-05-04T22:49:47.713486Z","shell.execute_reply.started":"2023-05-04T22:49:45.804469Z","shell.execute_reply":"2023-05-04T22:49:47.712481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Lightning AI","metadata":{}},{"cell_type":"code","source":"class LightningWrapper(pl.LightningModule):\n    def __init__(self, model):\n        super().__init__()\n        self.model = model\n        \n    def training_step(self, batch, batch_idx):\n        x, y = batch\n        y_hat = self.model(x)\n        loss = nn.functional.cross_entropy(y_hat, y)\n        acc = (y_hat.argmax(dim=1) == y).float().mean()\n        self.log('train_loss', loss)\n        self.log('train_acc', acc)\n        return loss\n    \n    def validation_step(self, batch, batch_idx):\n        x, y = batch\n        y_hat = self.model(x)\n        loss = nn.functional.cross_entropy(y_hat, y)\n        acc = (y_hat.argmax(dim=1) == y).float().mean()\n        self.log('val_loss', loss)\n        self.log('val_acc', acc)\n    \n    def configure_optimizers(self):\n        optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)\n        return optimizer","metadata":{"execution":{"iopub.status.busy":"2023-05-04T22:49:47.720297Z","iopub.execute_input":"2023-05-04T22:49:47.723521Z","iopub.status.idle":"2023-05-04T22:49:47.732097Z","shell.execute_reply.started":"2023-05-04T22:49:47.723495Z","shell.execute_reply":"2023-05-04T22:49:47.731184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainer = pl.Trainer(max_epochs=5)\ntrainer.fit(model=LightningWrapper(BaseModel()), train_dataloaders=train_loader, val_dataloaders=val_loader)","metadata":{"execution":{"iopub.status.busy":"2023-05-04T22:49:47.733625Z","iopub.execute_input":"2023-05-04T22:49:47.733962Z","iopub.status.idle":"2023-05-04T22:51:10.038478Z","shell.execute_reply.started":"2023-05-04T22:49:47.733931Z","shell.execute_reply":"2023-05-04T22:51:10.037275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainer = pl.Trainer(max_epochs=5)\ntrainer.fit(model=LightningWrapper(DeepModel()), train_dataloaders=train_loader, val_dataloaders=val_loader)","metadata":{"execution":{"iopub.status.busy":"2023-05-04T22:51:10.040564Z","iopub.execute_input":"2023-05-04T22:51:10.040938Z","iopub.status.idle":"2023-05-04T22:52:30.039822Z","shell.execute_reply.started":"2023-05-04T22:51:10.040900Z","shell.execute_reply":"2023-05-04T22:52:30.038553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%load_ext tensorboard\n%tensorboard --logdir=/kaggle/working/lightning_logs/","metadata":{"execution":{"iopub.status.busy":"2023-05-04T22:52:30.044547Z","iopub.execute_input":"2023-05-04T22:52:30.044880Z","iopub.status.idle":"2023-05-04T22:52:36.081338Z","shell.execute_reply.started":"2023-05-04T22:52:30.044850Z","shell.execute_reply":"2023-05-04T22:52:36.080410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}