{"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)\nimport torch, torchvision # Deep learning \nimport matplotlib.pyplot as plt # OG ploting lib\nimport tqdm # When you wonder how long you'll wait \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 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":{},"cell_type":"markdown","source":"Just open the files, do a split and check if it's balance, for more detail, see any other notebooks for this contest or any tutorial online"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"full_data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv', dtype='float')\ntest_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv', dtype='float')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_data = full_data.iloc[:int(len(full_data) * 0.2), :]\ntrain_data = full_data.iloc[int(len(full_data) * 0.2):]\ntrain_data = train_data.reset_index().drop('index', axis='columns')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# I'm not using fancy libraries, if you want automatic nice colors or things like that use seaborn or other, personally I don't care\n\nplt.figure(figsize=(10, 2))\nplt.subplot(1,2,1)\ntrain_data['label'].plot(title=\"train split\", kind='hist', rwidth=0.5)\n\nplt.subplot(1,2,2)\nval_data['label'].plot(title=\"test split\", kind='hist', rwidth=0.5)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"I'm writting my training loop here, since I'll be using it for different model it's better to have it as a function, it's pretty basic, you can check pytorch tutorials for more info."},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def basic_train(model, optim, loss, epochs):\n    best_correct = 0\n    lr = 0\n    for g in optim.param_groups:\n                lr = g['lr']\n    \n    for epoch in tqdm.tqdm(range(epochs)):\n        epoch_loss = []\n        total = 0\n        correct = 0\n        total_1 = 0 \n        correct_1 = 0\n        \n        \n        for label, item in train_dataloader:\n            label = label\n            item = item\n\n            optim.zero_grad()\n\n            pred = model(item)\n            Loss = loss(pred, label)\n            Loss.backward()\n            optim.step()\n\n            epoch_loss.append(Loss)\n\n            _, predicted = torch.max(pred.data, 1)\n            total_1 += label.size(0)\n            correct_1 += (predicted == label).sum().item()\n            \n        # reduce lr on plateau, maybe there is a pytorch function for that\n        if epoch_loss[-1] > epoch_loss[-2]:\n            lr = lr * 0.1\n            for g in optim.param_groups:\n                g['lr'] = lr\n\n        for label, item in val_dataloader:\n            label = label\n            item = item\n            pred = model(item)\n\n            _, predicted = torch.max(pred.data, 1)\n            total += label.size(0)\n            correct += (predicted == label).sum().item()\n\n        print(f'Epoch {epoch}, loss : {Loss}, train_Acc : {correct_1/total_1}, test_Acc = {correct/total}')\n        \n        if correct > best_correct:\n            best_correct = correct\n            best_model = model\n        \n    return best_model\n\n\ndef plot_filters(conv):\n    filters = conv.weight.data.cpu().detach()\n    n = filters.shape[0]\n    \n    nrow = int(n/10) + 1 \n    ncol = 10\n    \n    plt.figure(figsize=(2*ncol,2*nrow))\n    \n    \n    for i in range(n):\n        plt.subplot(nrow,ncol,i+1)\n        plt.imshow(filters[i,0,...])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"I need to subclass the Dataset class of pytorch for mnist (there is already one, but why not make one here)"},{"metadata":{"trusted":true},"cell_type":"code","source":"class mnist_dataset(torch.utils.data.Dataset):\n    def __init__(self, dataframe):\n        super(mnist_dataset, self).__init__()\n        try: \n            self.labels = dataframe['label']\n        except:    \n            self.labels = None\n        \n        # Usually it's better to do the transform before the training\n        # to save on CPU (especially for classification)\n        self.items = dataframe.drop('label',axis='columns')\n        self.items = self.items.to_numpy().reshape(-1,1,28,28)\n        self.items = self.items / 255.        \n        \n    def __len__(self):\n        return self.labels.__len__()\n    \n    def __getitem__(self,idx):\n        idx = idx \n        label = int(self.labels[idx])\n        item = self.items[idx]\n        \n        return label, torch.Tensor(item)\n\ntrain_dataset = mnist_dataset(train_data)\nval_dataset = mnist_dataset(val_data)\n\ntrain_dataset.__len__()\n\nidx = np.random.randint(len(val_dataset))\nlabel, item = train_dataset[idx]\n\nplt.imshow(item[0])\nlabel","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 1024\n\ntrain_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\nval_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size)\n\nit = iter(train_dataloader)\nlabel, item = next(it)\n\nplt.imshow(item[0,0,...])\nlabel","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Ok, so now let's train your basic CNN that you will see in any tutorial for MNIST"},{"metadata":{"trusted":true},"cell_type":"code","source":"class digit_classifier(torch.nn.Module):\n    def __init__(self):\n        super(digit_classifier,self).__init__()   \n        \n        self.act = torch.nn.ReLU(True)\n        \n        self.feature_extractor = torch.nn.Sequential(\n            torch.nn.Conv2d(1, 16, 5),\n            self.act, \n            torch.nn.AvgPool2d(2),\n            torch.nn.Conv2d(16, 48, 5),\n            self.act, \n            torch.nn.AvgPool2d(2),\n            torch.nn.Conv2d(48, 128, 3),\n            self.act,\n        )\n        self.FC = torch.nn.Linear(128*2*2, 10)\n        \n        \n    def forward(self, x):\n        x = self.feature_extractor(x)\n        x = x.view(-1, 128*2*2)\n        x = self.FC(x)\n        \n        return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = digit_classifier()\nlr = 0.01\nepochs = 10\noptim = torch.optim.Adam(model.parameters(), lr)\nloss = torch.nn.CrossEntropyLoss()\n\nmnist_basic = basic_train(model, optim, loss, epochs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Yay, we are part of all the population which is able to follow a tutorial. Now what ?\nWe know how to stack some convolution kernels, but that does not give us any knowledge about what's happening...\n\nLet's check what the filters are","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filters = list(mnist_basic.feature_extractor.children())\nfilters","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_filters(filters[0])\nplot_filters(filters[3])\nplot_filters(filters[5])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"To me it's gibbrish, I don't feel like those filters are actually usefull, but we can see how look the filtered input"},{"metadata":{"trusted":true},"cell_type":"code","source":"def disp_filtered(conv, img):\n    n = conv.weight.data.cpu().detach().shape[0]\n    filtered = torch.nn.ReLU()(conv(img.unsqueeze(0)).detach())\n    \n    nrow = int(n/10) + 1 \n    ncol = 10\n    \n    plt.figure(figsize=(2,2))\n    plt.imshow(img[0,...], cmap='gray')\n    \n    plt.figure(figsize=(2*ncol,2*nrow))\n    \n    \n    for i in range(n):\n        plt.subplot(nrow,ncol,i+1)\n        plt.imshow(filtered[0,i,...], cmap='gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"idx=6\ndisp_filtered(filters[0], item[idx])\n\nidx=20\ndisp_filtered(filters[0], item[idx])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Seems that we learned to \"describe\" the contour of the number with the first convolution, that's nice, maybe, I'm not really sure"},{"metadata":{},"cell_type":"markdown","source":"Now I want to try something else, because why not."},{"metadata":{"trusted":true},"cell_type":"code","source":"class dumb_model_0(torch.nn.Module):\n    def __init__(self):\n        super(dumb_model_0,self).__init__()\n        self.conv = torch.nn.Conv2d(1, 20, 28)\n        self.FC = torch.nn.Linear(20, 10)\n        \n    def forward(self, x):\n        x = self.conv(x)\n        x = x.view(-1, 20)\n        x = self.FC(x)\n        \n        return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = dumb_model_0()\nlr = 0.01\nepochs = 10\noptim = torch.optim.Adam(model.parameters(), lr)\nloss = torch.nn.CrossEntropyLoss()\ndumb_0 = basic_train(model, optim, loss, epochs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_filters(dumb_0.conv)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"It's a bit obscur, but it looks like the filters are searching for shapes, anyway, we're getting 90% accuracy, which is better than using the pixels in a logistic regression."},{"metadata":{},"cell_type":"markdown","source":"Then I want to test two stage model still using large kernel, I'm also increasing the width because it's always good to increase the width when you increase the depth (see efficientnet paper)"},{"metadata":{"trusted":true},"cell_type":"code","source":"class dumb_model_1(torch.nn.Module):\n    def __init__(self):\n        super(dumb_model_1,self).__init__()\n        #self.conv = torch.nn.Conv2d(1, 40, 28)\n        \n        self.conv2 = torch.nn.Sequential(\n            torch.nn.Conv2d(1, 20, 14, 14),\n            torch.nn.ReLU(),\n            torch.nn.Conv2d(20,40,2)\n        )\n        \n        self.FC = torch.nn.Linear(40, 10)\n        \n    def forward(self, x):\n        x2 = self.conv2(x)\n        \n        x = x2\n        \n        x = x.view(-1, 40)\n        x = self.FC(x)\n        \n        return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = dumb_model_1()\nlr = 0.01\nepochs = 10\noptim = torch.optim.Adam(model.parameters(), lr)\nloss = torch.nn.CrossEntropyLoss()\ndumb_0 = basic_train(model, optim, loss, epochs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}