{"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 torch, torchvision\nfrom torchvision import datasets, transforms\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom torch.autograd import Variable\nimport numpy as np\nimport shap\nimport matplotlib.pyplot as plt","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-05-28T10:37:47.282196Z","iopub.execute_input":"2022-05-28T10:37:47.282598Z","iopub.status.idle":"2022-05-28T10:37:47.288673Z","shell.execute_reply.started":"2022-05-28T10:37:47.282539Z","shell.execute_reply":"2022-05-28T10:37:47.287767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tr = pd.read_csv(\"../input/digit-recognizer/train.csv\",dtype = np.float32)","metadata":{"execution":{"iopub.status.busy":"2022-05-28T10:40:26.286442Z","iopub.execute_input":"2022-05-28T10:40:26.286758Z","iopub.status.idle":"2022-05-28T10:40:28.391342Z","shell.execute_reply.started":"2022-05-28T10:40:26.286705Z","shell.execute_reply":"2022-05-28T10:40:28.390486Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tr","metadata":{"execution":{"iopub.status.busy":"2022-05-28T10:58:01.538496Z","iopub.execute_input":"2022-05-28T10:58:01.538829Z","iopub.status.idle":"2022-05-28T10:58:01.571642Z","shell.execute_reply.started":"2022-05-28T10:58:01.538774Z","shell.execute_reply":"2022-05-28T10:58:01.571065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_num(n):\n    plt.imshow(np.array([tr.iloc[n,1:]]).reshape(28, 28), cmap='gray')","metadata":{"execution":{"iopub.status.busy":"2022-05-28T10:46:01.421890Z","iopub.execute_input":"2022-05-28T10:46:01.422209Z","iopub.status.idle":"2022-05-28T10:46:01.427303Z","shell.execute_reply.started":"2022-05-28T10:46:01.422154Z","shell.execute_reply":"2022-05-28T10:46:01.425984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_num(0)","metadata":{"execution":{"iopub.status.busy":"2022-05-28T10:47:11.113296Z","iopub.execute_input":"2022-05-28T10:47:11.113651Z","iopub.status.idle":"2022-05-28T10:47:11.567816Z","shell.execute_reply.started":"2022-05-28T10:47:11.113579Z","shell.execute_reply":"2022-05-28T10:47:11.566915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_num(1)","metadata":{"execution":{"iopub.status.busy":"2022-05-28T10:47:18.988340Z","iopub.execute_input":"2022-05-28T10:47:18.988866Z","iopub.status.idle":"2022-05-28T10:47:19.122373Z","shell.execute_reply.started":"2022-05-28T10:47:18.988594Z","shell.execute_reply":"2022-05-28T10:47:19.121694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_num(3)","metadata":{"execution":{"iopub.status.busy":"2022-05-28T10:47:29.122090Z","iopub.execute_input":"2022-05-28T10:47:29.122485Z","iopub.status.idle":"2022-05-28T10:47:29.258405Z","shell.execute_reply.started":"2022-05-28T10:47:29.122443Z","shell.execute_reply":"2022-05-28T10:47:29.257331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(\"../input/digit-recognizer/train.csv\",dtype = np.float32)\n\n\ntarget = train.label.values\ntrain = train.loc[:,train.columns != \"label\"].values/255 \n\nX_train, X_test, y_train, y_test = train_test_split(train, target, test_size = 0.2, random_state = 42) \n\nX_train = torch.from_numpy(X_train)\ny_train = torch.from_numpy(y_train).type(torch.LongTensor)\n\nX_test = torch.from_numpy(X_test)\ny_test = torch.from_numpy(y_test).type(torch.LongTensor)\n\nbatch_size = 128\nnum_epochs = 100\n\ntrain = torch.utils.data.TensorDataset(X_train, y_train)\ntest = torch.utils.data.TensorDataset(X_test, y_test)\n\ntrain_loader = torch.utils.data.DataLoader(train, batch_size = batch_size, shuffle = False)\ntest_loader = torch.utils.data.DataLoader(test, batch_size = batch_size, shuffle = False)\n","metadata":{"execution":{"iopub.status.busy":"2022-05-28T09:57:07.596667Z","iopub.execute_input":"2022-05-28T09:57:07.596922Z","iopub.status.idle":"2022-05-28T09:57:10.820528Z","shell.execute_reply.started":"2022-05-28T09:57:07.596876Z","shell.execute_reply":"2022-05-28T09:57:10.819538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### CNN Model Class & Train","metadata":{}},{"cell_type":"code","source":"class CNNModel(nn.Module):\n    def __init__(self):\n        super(CNNModel, self).__init__()\n        self.cnn1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=0)\n        self.relu1 = nn.ReLU()\n        self.maxpool1 = nn.MaxPool2d(kernel_size=2)\n        self.cnn2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=0)\n        self.relu2 = nn.ReLU()\n        self.maxpool2 = nn.MaxPool2d(kernel_size=2)\n        self.fc1 = nn.Linear(32 * 4 * 4, 10) \n    \n    def forward(self, x):\n        out = self.cnn1(x)\n        out = self.relu1(out)\n        out = self.maxpool1(out)\n        out = self.cnn2(out)\n        out = self.relu2(out)\n        out = self.maxpool2(out)\n        out = out.view(out.size(0), -1)\n        out = self.fc1(out)\n        return out\n    \nmodel = CNNModel()\n\nerror = nn.CrossEntropyLoss()\n\nlearning_rate = 0.1\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n\ncount = 0\nloss_list = []\niteration_list = []\naccuracy_list = []\n\nfor epoch in range(num_epochs):\n    for i, (images, labels) in enumerate(train_loader):\n\n        train = Variable(images.view(-1, 1, 28, 28))\n        labels = Variable(labels)\n        \n        optimizer.zero_grad()\n        outputs = model(train)\n        loss = error(outputs, labels)\n        loss.backward()\n        optimizer.step()\n        \n        count += 1\n        \n        if count % 50 == 0:\n            correct = 0\n            total = 0\n            \n            for images, labels in test_loader:\n                test = Variable(images.view(-1, 1, 28, 28))\n                outputs = model(test)\n                predicted = torch.max(outputs.data, 1)[1]\n                total += len(labels)\n                correct += (predicted == labels).sum()\n            \n            accuracy = 100.0 * correct.item() / total\n            loss_list.append(loss.data.item())\n            iteration_list.append(count)\n            accuracy_list.append(accuracy)\n            if count % 500 == 0:\n                print('Iteration: {}  Loss: {}  Accuracy: {} %'.format(count, loss.data.item(), accuracy))","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2022-05-28T09:57:10.822300Z","iopub.execute_input":"2022-05-28T09:57:10.822593Z","iopub.status.idle":"2022-05-28T10:13:07.121440Z","shell.execute_reply.started":"2022-05-28T09:57:10.822529Z","shell.execute_reply":"2022-05-28T10:13:07.120673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Interpretation","metadata":{}},{"cell_type":"code","source":"batch = next(iter(test_loader))\nimages, _ = batch\nimages = images.view(-1, 1, 28, 28)\n\nbackground = images[:100]\ntest_images= images[100:110]\n\ne = shap.DeepExplainer(model, images)\nshap_values = e.shap_values(test_images)","metadata":{"execution":{"iopub.status.busy":"2022-05-28T10:13:07.122632Z","iopub.execute_input":"2022-05-28T10:13:07.122887Z","iopub.status.idle":"2022-05-28T10:13:19.100704Z","shell.execute_reply.started":"2022-05-28T10:13:07.122835Z","shell.execute_reply":"2022-05-28T10:13:19.100042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shap_numpy = [np.swapaxes(np.swapaxes(s, 1, -1), 1, 2) for s in shap_values]\ntest_numpy = np.swapaxes(np.swapaxes(test_images.numpy(), 1, -1), 1, 2)\n\nshap.image_plot(shap_numpy, -test_numpy)","metadata":{"execution":{"iopub.status.busy":"2022-05-28T10:13:19.101862Z","iopub.execute_input":"2022-05-28T10:13:19.102187Z","iopub.status.idle":"2022-05-28T10:13:23.588220Z","shell.execute_reply.started":"2022-05-28T10:13:19.102154Z","shell.execute_reply":"2022-05-28T10:13:23.587687Z"},"trusted":true},"execution_count":null,"outputs":[]}]}