{"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\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"trainpd = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntestpd = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(trainpd.shape)\nprint(testpd.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images = torch.Tensor(trainpd.drop(columns='label').to_numpy()).reshape(-1,1,28,28)\ntrain_labels = torch.LongTensor(trainpd['label'])\ntest_images = torch.Tensor(testpd.to_numpy()).reshape(-1,1,28,28)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_images.shape)\nprint(train_labels.shape)\nprint(test_images.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(train_images[2589].squeeze(), cmap='gray')\nprint('label:',train_labels[2589].item())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = torch.utils.data.TensorDataset(train_images, train_labels)\n# train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class Network(nn.Module):\n    def __init__(self):\n        super(Network, self).__init__()\n        self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)\n        self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5)\n\n        self.fc1 = nn.Linear(in_features=4*4*12, out_features=120)\n        self.fc2 = nn.Linear(in_features=120, out_features=60)\n        self.out = nn.Linear(in_features=60, out_features=10)\n\n    def forward(self, t):\n\n        t = self.conv1(t)\n        t = F.relu(t)\n        t = F.max_pool2d(t, kernel_size=2)\n\n        t = self.conv2(t)\n        t = F.relu(t)\n        t = F.max_pool2d(t, kernel_size=2)\n\n        t = t.reshape(-1, 4*4*12)\n        # t.flatten(start_dim=1)\n        t = self.fc1(t)\n        t = F.relu(t)\n\n        t = self.fc2(t)\n        t = F.relu(t)\n\n        t = self.out(t)\n\n        return t","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def weights_init(layer):\n    classname = layer.__class__.__name__\n    if classname.find('Conv') != -1:\n        nn.init.kaiming_normal_(layer.weight.data, nonlinearity='relu')  # He-initialization\n        # ref : https://pytorch.org/docs/stable/nn.init.html#torch.nn.init.kaiming_normal_\n        \n# Reference : https://discuss.pytorch.org/t/weight-initilzation/157","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"network = Network()\nnetwork.apply(weights_init)\nnetwork","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size=100\nlr=0.002\niterations=50\nloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size)\noptimizer = optim.Adam(network.parameters(), lr=lr)\n\ntotal_loss = []\ntotal_correct = []\n\nfor epoch in range(iterations):\n\n    epoch_loss = 0\n    epoch_correct = 0\n    for i, batch in enumerate(loader):\n        batch_loss = 0\n        batch_correct = 0\n        \n        images, labels = batch\n\n        preds = network(images)\n        loss = F.cross_entropy(preds, labels)\n\n        optimizer.zero_grad()\n\n        loss.backward()\n        optimizer.step()\n\n        batch_loss = loss.item()\n        batch_correct = preds.argmax(dim=1).eq(labels).sum().item()\n        \n        epoch_loss += batch_loss\n        epoch_correct += batch_correct\n\n        total_loss.append(batch_loss)\n        total_correct.append(batch_correct)\n        \n        if not (i+1)%21:\n            print('Epoch: {}, Batch: {:>3}, Loss: {:.5f}, Accuracy: {:.2f}%'.format(epoch + 1, i+1, \n                                                                    batch_loss,\n                                                                    batch_correct/len(labels)*100))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"figure, axes = plt.subplots(figsize = (21,21))\n\naxes.plot(total_loss[21:], label = 'Total Cost')\naxes.plot([tc/100 for tc in total_correct[21:]], label = 'Total Correct')\naxes.set_xlabel('No. of Iterations', fontsize=21)\naxes.set_title('Learning Curves', fontsize=42)\naxes.legend(fontsize=21)\naxes.grid()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_preds = network(train_images)\ntotal_correct = total_preds.argmax(dim=1).eq(train_labels).sum().item()\ntotal_correct","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_correct / len(train_images) *100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_preds = network(test_images)\nLabel = test_preds.argmax(dim = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"testdf = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')\ntestdf['Label'] = Label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"testdf.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"testdf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"testdf.to_csv(\"testdf.csv\", index=None)","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}