{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\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))\nimport time\n\n# You can write up to 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\nsubmission = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class LeNet(nn.Module):\n    def __init__(self):\n        super(LeNet, self).__init__()\n        self.conv = nn.Sequential(\n            nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5),\n            nn.ReLU(),\n            nn.MaxPool2d(2,2),\n            nn.Conv2d(6, 16, 5),\n            nn.ReLU(),\n            nn.MaxPool2d(2,2)\n        )\n        self.fc = nn.Sequential(\n            nn.Linear(in_features=16*4*4, out_features=120),\n            nn.ReLU(),\n            nn.Linear(120, 84),\n            nn.Sigmoid(),\n            nn.Linear(84,10)\n        )\n    def forward(self, img):\n        feature =- self.conv(img)\n        output = self.fc(feature.view(img.shape[0], -1))\n        return output\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"net = LeNet()\nprint(net)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"transform = transforms.ToTensor()\n\nx_train, x_val, y_train, y_val = train_test_split(\n    train.values[:,1:], train.values[:,0], test_size=0.2)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 128\n\ntrain_dataset = torch.utils.data.TensorDataset(torch.from_numpy(x_train.reshape(-1,1, 28,28).astype(np.float32)/255),\n                                               torch.from_numpy(y_train))\n\nval_dataset = torch.utils.data.TensorDataset(torch.from_numpy(x_val.reshape(-1,1, 28,28).astype(np.float32)/255),\n                                               torch.from_numpy(y_val))\n\ntest_dataset = torch.utils.data.TensorDataset(torch.from_numpy(test.values[:,:].reshape(-1,1, 28,28).astype(np.float32)/255))\n\n# data loader\ntrain_loader = torch.utils.data.DataLoader(train_dataset, batch_size = batch_size, shuffle = True)\nval_loader = torch.utils.data.DataLoader(val_dataset, batch_size = batch_size, shuffle = False)\ntest_loader = torch.utils.data.DataLoader(test_dataset, batch_size = batch_size, shuffle = False)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr, n_epochs = 0.001, 30\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(net.parameters(), lr=lr)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_epochs = 30\nfor epoch in range(n_epochs):\n    start = time.time()\n    train_loss = 0.0\n    for data, target in train_loader:\n        optimizer.zero_grad()\n        output = net(data)\n        loss = criterion(output, target)\n        loss.backward()\n        optimizer.step()\n        train_loss += loss.item()*data.size(0)\n    \n    train_loss = train_loss/len(train_loader.dataset)\n    \n    print(f\"Epoch: {epoch}, train loss: {train_loss}, elapsed {(time.time() - start)}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_loss = 0.0\nclass_correct = list(0. for i in range(10))\nclass_total = list(0. for i in range(10))\n\nnet.eval() # prep net for evaluation\n\nfor data, target in val_loader:\n    # forward pass: compute predicted outputs by passing inputs to the net\n    output = net(data)\n    # calculate the loss\n    loss = criterion(output, target)\n    # update val loss \n    val_loss += loss.item()*data.size(0)\n    # convert output probabilities to predicted class\n    _, pred = torch.max(output, 1)\n    # compare predictions to true label\n    correct = np.squeeze(pred.eq(target.data.view_as(pred)))\n    # calculate val accuracy for each object class\n    for i in range(len(target)):\n        label = target.data[i]\n        class_correct[label] += correct[i].item()\n        class_total[label] += 1\n\n# calculate and print avg val loss\nval_loss = val_loss/len(val_loader.sampler)\nprint('val Loss: {:.6f}\\n'.format(val_loss))\n\nfor i in range(10):\n    if class_total[i] > 0:\n        print('val Accuracy of %5s: %2d%% (%2d/%2d)' % (\n            str(i), 100 * class_correct[i] / class_total[i],\n            np.sum(class_correct[i]), np.sum(class_total[i])))\n    else:\n        print('val Accuracy of %5s: N/A (no training examples)' % (classes[i]))\n\nprint('\\nval Accuracy (Overall): %2d%% (%2d/%2d)' % (\n    100. * np.sum(class_correct) / np.sum(class_total),\n    np.sum(class_correct), np.sum(class_total)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"net.eval() # prep net for evaluation\n\npreds = []\n\nfor data in test_loader:\n    # forward pass: compute predicted outputs by passing inputs to the net\n    output = net(data[0])\n    # calculate the loss\n    _, pred = torch.max(output, 1)\n    preds.extend(pred.tolist())\n    # compare predictions to true label\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['Label'] = preds\nsubmission.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}