{"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 in \n\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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PATH = '/kaggle/input/digit-recognizer/'","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import torch \nimport torchvision.transforms as transforms\nimport torch.utils.data\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_image(pixels, ax=plt):\n    ax.imshow(pixels.reshape(28, 28), cmap='gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(PATH + 'train.csv')\ntest_df = pd.read_csv(PATH + 'test.csv')\ncombined_df = train_df.append(test_df, sort=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, X_val, y_train, y_val = train_test_split(train_df.drop('label', axis=1), train_df['label'], test_size=0.2, random_state=17)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.values.reshape(len(X_train), 28, 28)\nX_val = X_val.values.reshape(len(X_val), 28, 28)\n\nX_train = X_train / 255\nX_val = X_val / 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ds = torch.utils.data.TensorDataset(torch.tensor(X_train, dtype=torch.float32), torch.tensor(y_train.values, dtype=torch.float32))\ntest_ds = torch.utils.data.TensorDataset(torch.tensor(X_val, dtype=torch.float32), torch.tensor(y_val.values, dtype=torch.float32))\n\ntrain_loader = torch.utils.data.DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=2)\ntest_loader = torch.utils.data.DataLoader(test_ds, batch_size=64, shuffle=False, num_workers=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axs = plt.subplots(1, 5, figsize=(20, 12))\ni = 0\nfor n in np.random.choice(len(train_df), 5):\n    show_image(np.array(train_df.drop('label', axis=1).iloc[n]), ax=axs[i])\n    axs[i].axis('off')\n    i += 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"fig = plt.figure(figsize=(10, 6))\ndigits_frequency = train_df['label'].value_counts()\nsns.barplot(list(range(0, 10)), digits_frequency)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch.nn as nn\nimport torch.nn.functional as F\n\nclass CNN(nn.Module):\n    def __init__(self):\n        super(CNN, self).__init__()\n        self.conv1 = nn.Conv2d(1, 6, 5)\n        self.pool = nn.MaxPool2d(2, 2)\n        self.conv2 = nn.Conv2d(6, 16, 5)\n        self.fc1 = nn.Linear(16 * 4 * 4, 120)\n        self.fc2 = nn.Linear(120, 84)\n        self.fc3 = nn.Linear(84, 10)\n        \n    def forward(self, x):\n        x = self.pool(F.relu(self.conv1(x)))\n        x = self.pool(F.relu(self.conv2(x)))\n        x = x.view(-1, 16 * 4 * 4)\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = self.fc3(x)\n        \n        return x\n\ncnn = CNN()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch.optim as optim\nfrom torch.autograd import Variable\n\ncritertion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(cnn.parameters(), lr=0.001, momentum=0.9)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for epoch in range(15):  # loop over the dataset multiple times\n    \n    running_loss = 0.0\n    for i, (images, labels) in enumerate(train_loader, 0):\n        inputs = Variable(images.view(64, 1, 28, 28))\n        labels = Variable(torch.tensor(list(map(int, labels))))\n\n        # zero the parameter gradients\n        optimizer.zero_grad()\n\n        # forward + backward + optimize\n        outputs = cnn(inputs)\n        loss = critertion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n\n        # print statistics\n        running_loss += loss.item()\n        if i % 100 == 99:    # print every 100 mini-batches\n            print('[%d, %5d] loss: %.3f' %\n                  (epoch + 1, i + 1, running_loss / 100))\n            running_loss = 0.0\n\nprint('Finished Training')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, f1_score\n\npred = cnn(torch.tensor(X_val, dtype=torch.float32).view(len(X_val), 1, 28, 28))\npred = torch.max(pred.data, 1)[1]\n\nprint('Confusion mastrix:\\n', confusion_matrix(y_val, pred))\nprint('F1 score: ', f1_score(y_val, pred, average='macro'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test = test_df\nX_test = X_test.values.reshape(len(X_test), 28, 28)\nX_test = X_test / 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = cnn(torch.tensor(X_test, dtype=torch.float32).view(len(X_test), 1, 28, 28))\nsub = pd.DataFrame({\n                'ImageId': range(1, len(sub.data) + 1),\n                'Label': torch.max(sub.data, 1)[1].numpy()\n            }, columns=['ImageId', 'Label'])\nprint(sub.head())\nsub.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":1}