{"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":"import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-07-22T18:24:05.986044Z","iopub.execute_input":"2022-07-22T18:24:05.986503Z","iopub.status.idle":"2022-07-22T18:24:05.994178Z","shell.execute_reply.started":"2022-07-22T18:24:05.986469Z","shell.execute_reply":"2022-07-22T18:24:05.993448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom tqdm import tqdm","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:24:06.005370Z","iopub.execute_input":"2022-07-22T18:24:06.005987Z","iopub.status.idle":"2022-07-22T18:24:06.011552Z","shell.execute_reply.started":"2022-07-22T18:24:06.005953Z","shell.execute_reply":"2022-07-22T18:24:06.010739Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_df = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:24:06.021901Z","iopub.execute_input":"2022-07-22T18:24:06.022461Z","iopub.status.idle":"2022-07-22T18:24:10.525334Z","shell.execute_reply.started":"2022-07-22T18:24:06.022428Z","shell.execute_reply":"2022-07-22T18:24:10.524424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.sample(10)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:24:10.527010Z","iopub.execute_input":"2022-07-22T18:24:10.527550Z","iopub.status.idle":"2022-07-22T18:24:10.549494Z","shell.execute_reply.started":"2022-07-22T18:24:10.527517Z","shell.execute_reply":"2022-07-22T18:24:10.548261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = train_df.drop('label', axis=1)\ny = train_df['label']","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:24:10.550985Z","iopub.execute_input":"2022-07-22T18:24:10.551331Z","iopub.status.idle":"2022-07-22T18:24:10.657601Z","shell.execute_reply.started":"2022-07-22T18:24:10.551300Z","shell.execute_reply":"2022-07-22T18:24:10.656117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\nfig, axs = plt.subplots(5, 5, figsize=(10, 10))\n\nfor ax in axs.flatten():\n    idx = random.choice(range(0, len(X)))\n    img = X.iloc[idx].values.reshape((28, 28))\n#     print(img)\n    label = y.iloc[idx]\n    ax.imshow(img, cmap='gray')\n    ax.set_title(label)\n    ax.set_xticks([])\n    ax.set_yticks([])\n\nplt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:24:10.660252Z","iopub.execute_input":"2022-07-22T18:24:10.660607Z","iopub.status.idle":"2022-07-22T18:24:11.815792Z","shell.execute_reply.started":"2022-07-22T18:24:10.660576Z","shell.execute_reply":"2022-07-22T18:24:11.814647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Model(nn.Module):\n    def __init__(self, in_channels=1, num_classes=10):\n        super(Model, self).__init__()\n        self.conv1 = nn.Conv2d(\n            in_channels=in_channels,\n            out_channels=8,\n            kernel_size=(3, 3),\n            stride=(1, 1),\n            padding=(1, 1),\n        )\n        self.pool = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))\n        self.conv2 = nn.Conv2d(\n            in_channels=8,\n            out_channels=16,\n            kernel_size=(3, 3),\n            stride=(1, 1),\n            padding=(1, 1),\n        )\n        self.conv3 = nn.Conv2d(\n            in_channels=16,\n            out_channels=32,\n            kernel_size=(3, 3),\n            stride=(1, 1),\n            padding=(1, 1),\n        )\n        self.conv4 = nn.Conv2d(\n            in_channels=32,\n            out_channels=64,\n            kernel_size=(3, 3),\n            stride=(1, 1),\n            padding=(1, 1),\n        )\n        self.fc1 = nn.Linear(64 * 7 * 7, num_classes)\n        self.dropout = nn.Dropout(p=0.2)\n\n    def forward(self, x):\n        x = F.relu(self.conv1(x))\n        x = self.pool(x)\n        x = F.relu(self.conv2(x))\n        x = self.pool(x)\n        x = F.relu(self.conv3(x))\n#         x = self.dropout(x)\n        x = F.relu(self.conv4(x))\n        x = x.reshape(x.shape[0], -1)\n        x = self.fc1(x)\n        return x","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:24:11.817303Z","iopub.execute_input":"2022-07-22T18:24:11.817679Z","iopub.status.idle":"2022-07-22T18:24:11.831325Z","shell.execute_reply.started":"2022-07-22T18:24:11.817651Z","shell.execute_reply":"2022-07-22T18:24:11.830158Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.max().max(), test_df.max().max()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:24:11.832836Z","iopub.execute_input":"2022-07-22T18:24:11.833903Z","iopub.status.idle":"2022-07-22T18:24:11.953827Z","shell.execute_reply.started":"2022-07-22T18:24:11.833857Z","shell.execute_reply":"2022-07-22T18:24:11.952549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X /= 255.0\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)\ntrain_dataset = TensorDataset(torch.Tensor(X_train.values), torch.Tensor(y_train.values).long())\ntest_dataset = TensorDataset(torch.Tensor(X_test.values), torch.Tensor(y_test.values).long())\ntrain_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)\ntest_loader = DataLoader(test_dataset, batch_size=128, shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:24:11.955269Z","iopub.execute_input":"2022-07-22T18:24:11.956531Z","iopub.status.idle":"2022-07-22T18:24:12.431174Z","shell.execute_reply.started":"2022-07-22T18:24:11.956480Z","shell.execute_reply":"2022-07-22T18:24:12.429977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import copy\n\ntrain_loss = []\ntest_loss = []\ntrain_acc = []\ntest_acc = []\nEPOCHS = 25\n\nbest_model = {\n    'accuracy': -1, \n    'loss': 1e9+10, \n    'model': None\n}\n\nmodel = Model()\nloss_fun = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n\nfor epoch in range(EPOCHS):\n    model.train()\n    batch_loss = []\n    batch_acc = []\n    pbar = tqdm(train_loader, desc=f'Epoch[{epoch+1}/{EPOCHS}] (train)', ascii=True)\n    for X, y in pbar:\n        X = X.view(-1, 1, 28, 28)\n        yHat = model.forward(X)\n        loss = loss_fun(yHat, y)\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        batch_loss.append(loss.item())\n        batch_acc.append(100*torch.mean((torch.argmax(yHat, dim=1) == y).float()).item())\n        pbar.set_postfix_str(f'loss = {np.mean(batch_loss):.3f}, accuracy = {np.mean(batch_acc):.3f}%')\n    train_loss.append(np.mean(batch_loss))\n    train_acc.append(np.mean(batch_acc))\n    \n    model.eval()\n    batch_loss = []\n    batch_acc = []\n    pbar = tqdm(test_loader, desc=f'Epoch[{epoch+1}/{EPOCHS}] (test)', ascii=True)\n    for X, y in pbar:\n        X = X.view(-1, 1, 28, 28)\n        with torch.no_grad():\n            yHat = model.forward(X)\n            loss = loss_fun(yHat, y)\n        batch_loss.append(loss.item())\n        batch_acc.append(100*torch.mean((torch.argmax(yHat, dim=1) == y).float()).item())\n        pbar.set_postfix_str(f'loss = {np.mean(batch_loss):.3f}, accuracy = {np.mean(batch_acc):.3f}%')\n    test_loss.append(np.mean(batch_loss))\n    test_acc.append(np.mean(batch_acc))\n    if test_acc[-1] > best_model['accuracy']:\n        best_model['accuracy'] = test_acc[-1]\n        best_model['loss'] = test_loss[-1]\n        best_model['model'] = copy.deepcopy(model.state_dict())\n        print(f'Best Model updated!')","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:24:12.432566Z","iopub.execute_input":"2022-07-22T18:24:12.432933Z","iopub.status.idle":"2022-07-22T18:28:04.771097Z","shell.execute_reply.started":"2022-07-22T18:24:12.432898Z","shell.execute_reply":"2022-07-22T18:28:04.769980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10, 4))\nplt.subplot(121)\nplt.plot(train_loss, label='train')\nplt.plot(test_loss, label='test')\nplt.legend()\nplt.title('Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\n\nplt.subplot(122)\nplt.plot(train_acc, label='train')\nplt.plot(test_acc, label='test')\nplt.legend()\nplt.title('Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy(%)')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:04.772640Z","iopub.execute_input":"2022-07-22T18:28:04.773703Z","iopub.status.idle":"2022-07-22T18:28:05.112301Z","shell.execute_reply.started":"2022-07-22T18:28:04.773650Z","shell.execute_reply":"2022-07-22T18:28:05.111088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Model()\nmodel.load_state_dict(best_model['model'])","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:05.115982Z","iopub.execute_input":"2022-07-22T18:28:05.116324Z","iopub.status.idle":"2022-07-22T18:28:05.125600Z","shell.execute_reply.started":"2022-07-22T18:28:05.116292Z","shell.execute_reply":"2022-07-22T18:28:05.124451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:05.127244Z","iopub.execute_input":"2022-07-22T18:28:05.127599Z","iopub.status.idle":"2022-07-22T18:28:05.146959Z","shell.execute_reply.started":"2022-07-22T18:28:05.127571Z","shell.execute_reply":"2022-07-22T18:28:05.145806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = torch.Tensor(test_df.values).view(-1, 1, 28, 28)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:05.148651Z","iopub.execute_input":"2022-07-22T18:28:05.149145Z","iopub.status.idle":"2022-07-22T18:28:05.208434Z","shell.execute_reply.started":"2022-07-22T18:28:05.149102Z","shell.execute_reply":"2022-07-22T18:28:05.207563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"outputs = model.forward(X)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:05.211238Z","iopub.execute_input":"2022-07-22T18:28:05.211678Z","iopub.status.idle":"2022-07-22T18:28:10.880657Z","shell.execute_reply.started":"2022-07-22T18:28:05.211634Z","shell.execute_reply":"2022-07-22T18:28:10.879345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"outputs.shape","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:10.882132Z","iopub.execute_input":"2022-07-22T18:28:10.882461Z","iopub.status.idle":"2022-07-22T18:28:10.890026Z","shell.execute_reply.started":"2022-07-22T18:28:10.882432Z","shell.execute_reply":"2022-07-22T18:28:10.888650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = torch.argmax(outputs, axis=1)\npred.shape","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:10.891556Z","iopub.execute_input":"2022-07-22T18:28:10.892751Z","iopub.status.idle":"2022-07-22T18:28:10.915331Z","shell.execute_reply.started":"2022-07-22T18:28:10.892700Z","shell.execute_reply":"2022-07-22T18:28:10.913774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')\nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:10.917043Z","iopub.execute_input":"2022-07-22T18:28:10.917509Z","iopub.status.idle":"2022-07-22T18:28:10.939296Z","shell.execute_reply.started":"2022-07-22T18:28:10.917465Z","shell.execute_reply":"2022-07-22T18:28:10.938264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission['Label'] = pred.numpy()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:10.940822Z","iopub.execute_input":"2022-07-22T18:28:10.941145Z","iopub.status.idle":"2022-07-22T18:28:10.946410Z","shell.execute_reply.started":"2022-07-22T18:28:10.941120Z","shell.execute_reply":"2022-07-22T18:28:10.945559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:10.947640Z","iopub.execute_input":"2022-07-22T18:28:10.948675Z","iopub.status.idle":"2022-07-22T18:28:10.967286Z","shell.execute_reply.started":"2022-07-22T18:28:10.948641Z","shell.execute_reply":"2022-07-22T18:28:10.966382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('./submission_1.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:10.968503Z","iopub.execute_input":"2022-07-22T18:28:10.969265Z","iopub.status.idle":"2022-07-22T18:28:11.024842Z","shell.execute_reply.started":"2022-07-22T18:28:10.969233Z","shell.execute_reply":"2022-07-22T18:28:11.023945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('./submission_1.csv')\nsub","metadata":{"execution":{"iopub.status.busy":"2022-07-22T18:28:11.026331Z","iopub.execute_input":"2022-07-22T18:28:11.026907Z","iopub.status.idle":"2022-07-22T18:28:11.045071Z","shell.execute_reply.started":"2022-07-22T18:28:11.026867Z","shell.execute_reply":"2022-07-22T18:28:11.044056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}