{"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":"markdown","source":"# Imports","metadata":{}},{"cell_type":"code","source":"import os\nimport shutil\nimport time\nfrom tqdm import tqdm\nimport random\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport PIL.Image\nfrom IPython.display import Image\nfrom sklearn.metrics import confusion_matrix\n\nimport torch\nimport torch.nn as nn\nimport torchvision\nfrom torchvision import models,transforms,datasets","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:20.762316Z","iopub.execute_input":"2022-09-11T09:00:20.762827Z","iopub.status.idle":"2022-09-11T09:00:23.925753Z","shell.execute_reply.started":"2022-09-11T09:00:20.762744Z","shell.execute_reply":"2022-09-11T09:00:23.924242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualizing and preparing data","metadata":{}},{"cell_type":"code","source":"path_train = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/train\"\nclasses = [c for c in os.listdir(path_train) if not c.startswith(\".\")]\nclasses.sort()\nprint(classes)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:23.929773Z","iopub.execute_input":"2022-09-11T09:00:23.930332Z","iopub.status.idle":"2022-09-11T09:00:23.951275Z","shell.execute_reply.started":"2022-09-11T09:00:23.930288Z","shell.execute_reply":"2022-09-11T09:00:23.950345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_dict = {0 : \"safe driving\",\n              1 : \"texting - right\",\n              2 : \"talking on the phone - right\",\n              3 : \"texting - left\",\n              4 : \"talking on the phone - left\",\n              5 : \"operating the radio\",\n              6 : \"drinking\",\n              7 : \"reaching behind\",\n              8 : \"hair and makeup\",\n              9 : \"talking to passenger\"}","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:23.952644Z","iopub.execute_input":"2022-09-11T09:00:23.953105Z","iopub.status.idle":"2022-09-11T09:00:23.959271Z","shell.execute_reply.started":"2022-09-11T09:00:23.953065Z","shell.execute_reply":"2022-09-11T09:00:23.957686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"d = {\"img\" : [], \"class\" : []}\nfor c in classes:\n    imgs = [img for img in os.listdir(os.path.join(path_train,c)) if not img.startswith(\".\")]\n    for img in imgs:\n        d[\"img\"].append(img)\n        d[\"class\"].append(c)\ndf = pd.DataFrame(d)\nax = sns.countplot(data=df,x=\"class\")\nax.set(title=\"Classes distribution\")\nprint(\"Total number of training data :\",len(df))","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:23.961571Z","iopub.execute_input":"2022-09-11T09:00:23.962130Z","iopub.status.idle":"2022-09-11T09:00:26.976261Z","shell.execute_reply.started":"2022-09-11T09:00:23.962094Z","shell.execute_reply":"2022-09-11T09:00:26.975207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = transforms.Compose([transforms.Resize((400, 400)),\n                                 transforms.RandomRotation(10),\n                                 transforms.ToTensor()])","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:26.980539Z","iopub.execute_input":"2022-09-11T09:00:26.980958Z","iopub.status.idle":"2022-09-11T09:00:26.990029Z","shell.execute_reply.started":"2022-09-11T09:00:26.980922Z","shell.execute_reply":"2022-09-11T09:00:26.989057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = datasets.ImageFolder(root = path_train, transform = transform)\n\ntotal_len = len(data)\ntraining_len = int(0.8*total_len)\ntesting_len = total_len - training_len\n\ntraining_data,testing_data = torch.utils.data.random_split(data,(training_len,testing_len))","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:26.995491Z","iopub.execute_input":"2022-09-11T09:00:26.995840Z","iopub.status.idle":"2022-09-11T09:00:44.083790Z","shell.execute_reply.started":"2022-09-11T09:00:26.995807Z","shell.execute_reply":"2022-09-11T09:00:44.082984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_loader = torch.utils.data.DataLoader(dataset=training_data,\n                                           batch_size=64,\n                                           shuffle=True,\n                                           drop_last=False)\ntest_loader = torch.utils.data.DataLoader(dataset=testing_data,\n                                          batch_size=64,\n                                          shuffle=False,\n                                          drop_last=False)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:44.085139Z","iopub.execute_input":"2022-09-11T09:00:44.085569Z","iopub.status.idle":"2022-09-11T09:00:44.091281Z","shell.execute_reply.started":"2022-09-11T09:00:44.085526Z","shell.execute_reply":"2022-09-11T09:00:44.090196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img,c = data[0]\nprint(img.shape)\nprint(\"Label:\", classes[c], f\"({class_dict[c]})\")\nplt.imshow(img.permute(1,2,0))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:44.092503Z","iopub.execute_input":"2022-09-11T09:00:44.093233Z","iopub.status.idle":"2022-09-11T09:00:44.355824Z","shell.execute_reply.started":"2022-09-11T09:00:44.093194Z","shell.execute_reply":"2022-09-11T09:00:44.355063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loader,labels = next(iter(train_loader))\nprint(loader.shape)\nprint(labels.view(8,8))\nplt.figure(figsize=(16,16))\nplt.imshow(torchvision.utils.make_grid(loader,nrow=8).permute((1,2,0)))\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:44.356787Z","iopub.execute_input":"2022-09-11T09:00:44.357134Z","iopub.status.idle":"2022-09-11T09:00:48.146868Z","shell.execute_reply.started":"2022-09-11T09:00:44.357107Z","shell.execute_reply":"2022-09-11T09:00:48.145909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating and training the model","metadata":{}},{"cell_type":"code","source":"device = torch.device(\"cuda:0\")\nprint(device)\nprint(torch.cuda.get_device_name(device))","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:48.149424Z","iopub.execute_input":"2022-09-11T09:00:48.149992Z","iopub.status.idle":"2022-09-11T09:00:48.220406Z","shell.execute_reply.started":"2022-09-11T09:00:48.149957Z","shell.execute_reply":"2022-09-11T09:00:48.219367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The model works better with 'normalized' data.","metadata":{}},{"cell_type":"code","source":"transform = transforms.Compose([transforms.Resize((400, 400)),\n                           transforms.RandomRotation(10),\n                           transforms.ToTensor(),\n                           transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n                          ])","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:48.222147Z","iopub.execute_input":"2022-09-11T09:00:48.222849Z","iopub.status.idle":"2022-09-11T09:00:48.232422Z","shell.execute_reply.started":"2022-09-11T09:00:48.222812Z","shell.execute_reply":"2022-09-11T09:00:48.231644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = datasets.ImageFolder(root = path_train, transform = transform)\n\ntotal_len = len(data)\ntraining_len = int(0.8*total_len)\ntesting_len = total_len - training_len\n\ntraining_data,testing_data = torch.utils.data.random_split(data,(training_len,testing_len))","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:48.235274Z","iopub.execute_input":"2022-09-11T09:00:48.235544Z","iopub.status.idle":"2022-09-11T09:00:51.514817Z","shell.execute_reply.started":"2022-09-11T09:00:48.235520Z","shell.execute_reply":"2022-09-11T09:00:51.513989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_loader = torch.utils.data.DataLoader(dataset=training_data,\n                                           batch_size=32,\n                                           shuffle=True,\n                                           drop_last=False,\n                                           num_workers=2)\ntest_loader = torch.utils.data.DataLoader(dataset=testing_data,\n                                          batch_size=32,\n                                          shuffle=False,\n                                          drop_last=False,\n                                          num_workers=2)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:51.516859Z","iopub.execute_input":"2022-09-11T09:00:51.517462Z","iopub.status.idle":"2022-09-11T09:00:51.526102Z","shell.execute_reply.started":"2022-09-11T09:00:51.517426Z","shell.execute_reply":"2022-09-11T09:00:51.525292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def train_model(model, criterion, optimizer, scheduler, n_epochs = 5):\n    \n    losses = []\n    accuracies = []\n    test_accuracies = []\n    # set the model to train mode initially\n    model.train()\n    for epoch in tqdm(range(n_epochs)):\n        since = time.time()\n        running_loss = 0.0\n        running_correct = 0.0\n        for data in train_loader:\n\n            # get the inputs and assign them to cuda\n            inputs, labels = data\n            inputs = inputs.to(device)\n            labels = labels.to(device)\n            optimizer.zero_grad()\n            \n            # forward + backward + optimize\n            outputs = model(inputs)\n            _, predicted = torch.max(outputs.data, 1)\n            loss = criterion(outputs, labels)\n            loss.backward()\n            optimizer.step()\n            \n            # calculate the loss/acc later\n            running_loss += loss.item()\n            running_correct += (labels==predicted).sum().item()\n\n        epoch_duration = time.time()-since\n        epoch_loss = running_loss/len(train_loader)\n        epoch_acc = 100/32*running_correct/len(train_loader)\n\n        print(\"Epoch %s, duration: %d s, loss: %.4f, acc: %.4f\" % (epoch+1, epoch_duration, epoch_loss, epoch_acc))\n        \n        losses.append(epoch_loss)\n        accuracies.append(epoch_acc)\n        \n        # switch the model to eval mode to evaluate on test data\n        model.eval()\n        test_acc = eval_model(model)\n        test_accuracies.append(test_acc)\n        \n        # re-set the model to train mode after validating\n        model.train()\n        scheduler.step(test_acc)\n        since = time.time()\n    print('Finished Training')\n    return model, losses, accuracies, test_accuracies","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:51.527535Z","iopub.execute_input":"2022-09-11T09:00:51.528096Z","iopub.status.idle":"2022-09-11T09:00:51.543386Z","shell.execute_reply.started":"2022-09-11T09:00:51.528060Z","shell.execute_reply":"2022-09-11T09:00:51.542398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def eval_model(model):\n    correct = 0.0\n    total = 0.0\n    with torch.no_grad():\n        for i, data in enumerate(test_loader, 0):\n            images, labels = data\n            images = images.to(device)\n            labels = labels.to(device)\n            \n            outputs = model_ft(images)\n            _, predicted = torch.max(outputs.data, 1)\n            \n            total += labels.size(0)\n            correct += (predicted == labels).sum().item()\n\n    test_acc = 100.0 * correct / total\n    print('Accuracy of the network on the test images: %d %%' % (\n        test_acc))\n    return test_acc","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:51.545371Z","iopub.execute_input":"2022-09-11T09:00:51.546114Z","iopub.status.idle":"2022-09-11T09:00:51.556028Z","shell.execute_reply.started":"2022-09-11T09:00:51.546074Z","shell.execute_reply":"2022-09-11T09:00:51.555142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_ft = models.resnet50(pretrained=True)\nnum_ftrs = model_ft.fc.in_features\n\nmodel_ft.fc = nn.Linear(num_ftrs, 10) #No. of classes = 10\nmodel_ft = model_ft.to(device)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model_ft.parameters(), lr=0.01, momentum=0.9)\nlrscheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', patience=3, threshold = 0.9)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:00:51.557206Z","iopub.execute_input":"2022-09-11T09:00:51.557618Z","iopub.status.idle":"2022-09-11T09:01:05.560291Z","shell.execute_reply.started":"2022-09-11T09:00:51.557581Z","shell.execute_reply":"2022-09-11T09:01:05.559447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# takes around 5-6 minutes per epoch with GPU\nmodel_ft, training_losses, training_accs, test_accs = train_model(model_ft, criterion, optimizer, lrscheduler, n_epochs=3)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:01:05.561698Z","iopub.execute_input":"2022-09-11T09:01:05.562056Z","iopub.status.idle":"2022-09-11T09:20:13.101189Z","shell.execute_reply.started":"2022-09-11T09:01:05.562020Z","shell.execute_reply":"2022-09-11T09:20:13.100031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.title('Training losses')\nplt.plot(training_losses)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:13.102768Z","iopub.execute_input":"2022-09-11T09:20:13.103519Z","iopub.status.idle":"2022-09-11T09:20:13.297872Z","shell.execute_reply.started":"2022-09-11T09:20:13.103475Z","shell.execute_reply":"2022-09-11T09:20:13.297014Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.title('Training Accuracy')\nplt.plot(training_accs)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:13.299327Z","iopub.execute_input":"2022-09-11T09:20:13.299686Z","iopub.status.idle":"2022-09-11T09:20:13.500603Z","shell.execute_reply.started":"2022-09-11T09:20:13.299649Z","shell.execute_reply":"2022-09-11T09:20:13.499858Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.title('Test Accuracy')\nplt.plot(test_accs)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:13.501874Z","iopub.execute_input":"2022-09-11T09:20:13.502382Z","iopub.status.idle":"2022-09-11T09:20:13.689376Z","shell.execute_reply.started":"2022-09-11T09:20:13.502312Z","shell.execute_reply":"2022-09-11T09:20:13.688522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.save(model_ft,\"/kaggle/working/model-best.hd5\")","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:13.690603Z","iopub.execute_input":"2022-09-11T09:20:13.690945Z","iopub.status.idle":"2022-09-11T09:20:13.913661Z","shell.execute_reply.started":"2022-09-11T09:20:13.690911Z","shell.execute_reply":"2022-09-11T09:20:13.912834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.save(model_ft.state_dict(), \"/kaggle/working/model-driver\")","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:13.915123Z","iopub.execute_input":"2022-09-11T09:20:13.915497Z","iopub.status.idle":"2022-09-11T09:20:14.093876Z","shell.execute_reply.started":"2022-09-11T09:20:13.915464Z","shell.execute_reply":"2022-09-11T09:20:14.093049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Testing the model and submitting csv","metadata":{}},{"cell_type":"code","source":"model = models.resnet50()\nnum_ftrs = model.fc.in_features\nmodel.fc = nn.Linear(num_ftrs, 10)\nmodel.load_state_dict(torch.load(\"/kaggle/working/model-driver\"))\nmodel.eval()\nmodel.cuda()","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:14.095285Z","iopub.execute_input":"2022-09-11T09:20:14.095824Z","iopub.status.idle":"2022-09-11T09:20:14.816590Z","shell.execute_reply.started":"2022-09-11T09:20:14.095785Z","shell.execute_reply":"2022-09-11T09:20:14.813699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path_test = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/test\"\nlist_img_test = [img for img in os.listdir(path_test) if not img.startswith(\".\")]\nlist_img_test.sort()","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:14.821097Z","iopub.execute_input":"2022-09-11T09:20:14.821553Z","iopub.status.idle":"2022-09-11T09:20:16.473510Z","shell.execute_reply.started":"2022-09-11T09:20:14.821516Z","shell.execute_reply":"2022-09-11T09:20:16.472662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = random.choice(list_img_test)\nim_path = os.path.join(path_test,file)\ndisplay(Image(filename=im_path))\nwith PIL.Image.open(im_path) as im:\n    im = transform(im)\n    im = im.unsqueeze(0)\n    output = model(im.cuda())\n    proba = nn.Softmax(dim=1)(output)\n    proba = [round(float(elem),4) for elem in proba[0]]\n    print(proba)\n    print(\"Predicted class:\",class_dict[proba.index(max(proba))])\n    print(\"Confidence:\",max(proba))\n   ","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.475301Z","iopub.execute_input":"2022-09-11T09:20:16.475893Z","iopub.status.idle":"2022-09-11T09:20:16.535487Z","shell.execute_reply.started":"2022-09-11T09:20:16.475851Z","shell.execute_reply":"2022-09-11T09:20:16.534643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = random.choice(list_img_test)\nim_path = os.path.join(path_test,file)\ndisplay(Image(filename=im_path))\nwith PIL.Image.open(im_path) as im:\n    im = transform(im)\n    im = im.unsqueeze(0)\n    output = model(im.cuda())\n    proba = nn.Softmax(dim=1)(output)\n    proba = [round(float(elem),4) for elem in proba[0]]\n    print(proba)\n    print(\"Predicted class:\",class_dict[proba.index(max(proba))])\n    print(\"Confidence:\",max(proba))\n   ","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.536351Z","iopub.execute_input":"2022-09-11T09:20:16.536643Z","iopub.status.idle":"2022-09-11T09:20:16.579935Z","shell.execute_reply.started":"2022-09-11T09:20:16.536615Z","shell.execute_reply":"2022-09-11T09:20:16.579135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = random.choice(list_img_test)\nim_path = os.path.join(path_test,file)\ndisplay(Image(filename=im_path))\nwith PIL.Image.open(im_path) as im:\n    im = transform(im)\n    im = im.unsqueeze(0)\n    output = model(im.cuda())\n    proba = nn.Softmax(dim=1)(output)\n    proba = [round(float(elem),4) for elem in proba[0]]\n    print(proba)\n    print(\"Predicted class:\",class_dict[proba.index(max(proba))])\n    print(\"Confidence:\",max(proba))\n ","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.581423Z","iopub.execute_input":"2022-09-11T09:20:16.582046Z","iopub.status.idle":"2022-09-11T09:20:16.625311Z","shell.execute_reply.started":"2022-09-11T09:20:16.582008Z","shell.execute_reply":"2022-09-11T09:20:16.624471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = random.choice(list_img_test)\nim_path = os.path.join(path_test,file)\ndisplay(Image(filename=im_path))\nwith PIL.Image.open(im_path) as im:\n    im = transform(im)\n    im = im.unsqueeze(0)\n    output = model(im.cuda())\n    proba = nn.Softmax(dim=1)(output)\n    proba = [round(float(elem),4) for elem in proba[0]]\n    print(proba)\n    print(\"Predicted class:\",class_dict[proba.index(max(proba))])\n    print(\"Confidence:\",max(proba))\n  ","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.629684Z","iopub.execute_input":"2022-09-11T09:20:16.630383Z","iopub.status.idle":"2022-09-11T09:20:16.679526Z","shell.execute_reply.started":"2022-09-11T09:20:16.630355Z","shell.execute_reply":"2022-09-11T09:20:16.678644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = random.choice(list_img_test)\nim_path = os.path.join(path_test,file)\ndisplay(Image(filename=im_path))\nwith PIL.Image.open(im_path) as im:\n    im = transform(im)\n    im = im.unsqueeze(0)\n    output = model(im.cuda())\n    proba = nn.Softmax(dim=1)(output)\n    proba = [round(float(elem),4) for elem in proba[0]]\n    print(proba)\n    print(\"Predicted class:\",class_dict[proba.index(max(proba))])\n    print(\"Confidence:\",max(proba))\n  ","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.681401Z","iopub.execute_input":"2022-09-11T09:20:16.681842Z","iopub.status.idle":"2022-09-11T09:20:16.730377Z","shell.execute_reply.started":"2022-09-11T09:20:16.681805Z","shell.execute_reply":"2022-09-11T09:20:16.729540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = random.choice(list_img_test)\nim_path = os.path.join(path_test,file)\ndisplay(Image(filename=im_path))\nwith PIL.Image.open(im_path) as im:\n    im = transform(im)\n    im = im.unsqueeze(0)\n    output = model(im.cuda())\n    proba = nn.Softmax(dim=1)(output)\n    proba = [round(float(elem),4) for elem in proba[0]]\n    print(proba)\n    print(\"Predicted class:\",class_dict[proba.index(max(proba))])\n    print(\"Confidence:\",max(proba))\n  ","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.731769Z","iopub.execute_input":"2022-09-11T09:20:16.732392Z","iopub.status.idle":"2022-09-11T09:20:16.779531Z","shell.execute_reply.started":"2022-09-11T09:20:16.732349Z","shell.execute_reply":"2022-09-11T09:20:16.778697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = random.choice(list_img_test)\nim_path = os.path.join(path_test,file)\ndisplay(Image(filename=im_path))\nwith PIL.Image.open(im_path) as im:\n    im = transform(im)\n    im = im.unsqueeze(0)\n    output = model(im.cuda())\n    proba = nn.Softmax(dim=1)(output)\n    proba = [round(float(elem),4) for elem in proba[0]]\n    print(proba)\n    print(\"Predicted class:\",class_dict[proba.index(max(proba))])\n    print(\"Confidence:\",max(proba))\n   ","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.780682Z","iopub.execute_input":"2022-09-11T09:20:16.781261Z","iopub.status.idle":"2022-09-11T09:20:16.826106Z","shell.execute_reply.started":"2022-09-11T09:20:16.781222Z","shell.execute_reply":"2022-09-11T09:20:16.825271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = random.choice(list_img_test)\nim_path = os.path.join(path_test,file)\ndisplay(Image(filename=im_path))\nwith PIL.Image.open(im_path) as im:\n    im = transform(im)\n    im = im.unsqueeze(0)\n    output = model(im.cuda())\n    proba = nn.Softmax(dim=1)(output)\n    proba = [round(float(elem),4) for elem in proba[0]]\n    print(proba)\n    print(\"Predicted class:\",class_dict[proba.index(max(proba))])\n    print(\"Confidence:\",max(proba))\n    proba2 = proba.copy()\n   ","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.827267Z","iopub.execute_input":"2022-09-11T09:20:16.828081Z","iopub.status.idle":"2022-09-11T09:20:16.873555Z","shell.execute_reply.started":"2022-09-11T09:20:16.828044Z","shell.execute_reply":"2022-09-11T09:20:16.872712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = random.choice(list_img_test)\nim_path = os.path.join(path_test,file)\ndisplay(Image(filename=im_path))\nwith PIL.Image.open(im_path) as im:\n    im = transform(im)\n    im = im.unsqueeze(0)\n    output = model(im.cuda())\n    proba = nn.Softmax(dim=1)(output)\n    proba = [round(float(elem),4) for elem in proba[0]]\n    print(proba)\n    print(\"Predicted class:\",class_dict[proba.index(max(proba))])\n    print(\"Confidence:\",max(proba))\n  ","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.874784Z","iopub.execute_input":"2022-09-11T09:20:16.875134Z","iopub.status.idle":"2022-09-11T09:20:16.918499Z","shell.execute_reply.started":"2022-09-11T09:20:16.875099Z","shell.execute_reply":"2022-09-11T09:20:16.917758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def true_pred(test_data,model):\n    y_true = []\n    y_pred = []\n    n = len(test_data)\n    sum = 0\n    with torch.no_grad():\n        for x,y in tqdm(test_data):\n            x = x.to(device)\n            pred = torch.argmax(model(x),dim=1)\n            y_true.extend(list(np.array(y)))\n            y_pred.extend(list(np.array(pred.cpu())))\n    return y_true,y_pred","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.919756Z","iopub.execute_input":"2022-09-11T09:20:16.920483Z","iopub.status.idle":"2022-09-11T09:20:16.927335Z","shell.execute_reply.started":"2022-09-11T09:20:16.920446Z","shell.execute_reply":"2022-09-11T09:20:16.926477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_true,y_pred = true_pred(test_loader,model)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:20:16.928513Z","iopub.execute_input":"2022-09-11T09:20:16.929414Z","iopub.status.idle":"2022-09-11T09:21:15.917395Z","shell.execute_reply.started":"2022-09-11T09:20:16.929378Z","shell.execute_reply":"2022-09-11T09:21:15.915553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"m = confusion_matrix(y_true, y_pred)\nm  = m.astype('float') / m.sum(axis=1)[:, np.newaxis]","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:21:15.919192Z","iopub.execute_input":"2022-09-11T09:21:15.919920Z","iopub.status.idle":"2022-09-11T09:21:15.931095Z","shell.execute_reply.started":"2022-09-11T09:21:15.919871Z","shell.execute_reply":"2022-09-11T09:21:15.930137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.heatmap(m)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:21:15.932743Z","iopub.execute_input":"2022-09-11T09:21:15.933106Z","iopub.status.idle":"2022-09-11T09:21:16.278450Z","shell.execute_reply.started":"2022-09-11T09:21:15.933071Z","shell.execute_reply":"2022-09-11T09:21:16.277657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We need to create a '/test/test' so that we can use `datasets.ImageFolder` and use a loader which is faster than iterating one by one (40 minutes) through all imgs/test files.","metadata":{}},{"cell_type":"code","source":"os.mkdir(\"/kaggle/working/test\")","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:21:16.282367Z","iopub.execute_input":"2022-09-11T09:21:16.284369Z","iopub.status.idle":"2022-09-11T09:21:16.290149Z","shell.execute_reply.started":"2022-09-11T09:21:16.284331Z","shell.execute_reply":"2022-09-11T09:21:16.289504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for img in tqdm(list_img_test):\n    os.mkdir(\"/kaggle/working/test/\"+img[:-4])\n    source = path_test+\"/\"+img\n    destination = \"/kaggle/working/test/\"+img[:-4]+\"/\"+img\n    shutil.copy(source, destination)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:21:16.294229Z","iopub.execute_input":"2022-09-11T09:21:16.296496Z","iopub.status.idle":"2022-09-11T09:34:35.076252Z","shell.execute_reply.started":"2022-09-11T09:21:16.296460Z","shell.execute_reply":"2022-09-11T09:34:35.075415Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform_test = transforms.Compose([transforms.Resize((400, 400)),\n                                     #transforms.RandomRotation(10),\n                                     transforms.ToTensor(),\n                                     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n                               ])","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:34:35.077630Z","iopub.execute_input":"2022-09-11T09:34:35.078190Z","iopub.status.idle":"2022-09-11T09:34:35.083949Z","shell.execute_reply.started":"2022-09-11T09:34:35.078136Z","shell.execute_reply":"2022-09-11T09:34:35.083126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datatest = datasets.ImageFolder(root = \"/kaggle/working/test\",\n                                transform = transform_test)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:34:35.085830Z","iopub.execute_input":"2022-09-11T09:34:35.086316Z","iopub.status.idle":"2022-09-11T09:34:37.517745Z","shell.execute_reply.started":"2022-09-11T09:34:35.086282Z","shell.execute_reply":"2022-09-11T09:34:37.516913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loader = torch.utils.data.DataLoader(dataset=datatest,\n                                     batch_size=16,\n                                     shuffle=False,\n                                     drop_last=False,\n                                     num_workers=2)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:34:37.519116Z","iopub.execute_input":"2022-09-11T09:34:37.519506Z","iopub.status.idle":"2022-09-11T09:34:37.531241Z","shell.execute_reply.started":"2022-09-11T09:34:37.519469Z","shell.execute_reply":"2022-09-11T09:34:37.530222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x,y = next(iter(loader))","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:34:37.532615Z","iopub.execute_input":"2022-09-11T09:34:37.533174Z","iopub.status.idle":"2022-09-11T09:34:38.365898Z","shell.execute_reply.started":"2022-09-11T09:34:37.533124Z","shell.execute_reply":"2022-09-11T09:34:38.364498Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(x.shape)\nprint(y)\nplt.figure(figsize=(16,16))\nplt.imshow(torchvision.utils.make_grid(x,nrow=8).permute((1,2,0)))\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:34:38.367974Z","iopub.execute_input":"2022-09-11T09:34:38.368419Z","iopub.status.idle":"2022-09-11T09:34:39.072846Z","shell.execute_reply.started":"2022-09-11T09:34:38.368377Z","shell.execute_reply":"2022-09-11T09:34:39.072085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/state-farm-distracted-driver-detection/sample_submission.csv\",index_col = 0)","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:34:39.074240Z","iopub.execute_input":"2022-09-11T09:34:39.074733Z","iopub.status.idle":"2022-09-11T09:34:39.220292Z","shell.execute_reply.started":"2022-09-11T09:34:39.074698Z","shell.execute_reply":"2022-09-11T09:34:39.219404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"line = 0\nfor x,y in tqdm(loader,total = len(loader)) :\n    output = model_ft(x.cuda())\n    output = nn.Softmax(dim=1)(output)\n    for i in range(len(output)) :\n        proba = [float(elem) for elem in output[i]]\n        df.iloc[line][:]=proba\n        line += 1","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:34:39.221572Z","iopub.execute_input":"2022-09-11T09:34:39.222080Z","iopub.status.idle":"2022-09-11T09:51:27.916440Z","shell.execute_reply.started":"2022-09-11T09:34:39.222040Z","shell.execute_reply":"2022-09-11T09:51:27.915370Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for img in tqdm(list_img_test):\n    os.remove(\"/kaggle/working/test/\"+img[:-4]+\"/\"+img)\n    os.rmdir(\"/kaggle/working/test/\"+img[:-4])","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:51:27.917814Z","iopub.execute_input":"2022-09-11T09:51:27.918573Z","iopub.status.idle":"2022-09-11T09:51:32.514485Z","shell.execute_reply.started":"2022-09-11T09:51:27.918541Z","shell.execute_reply":"2022-09-11T09:51:32.513668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.rmdir(\"/kaggle/working/test\")","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:51:32.515676Z","iopub.execute_input":"2022-09-11T09:51:32.516562Z","iopub.status.idle":"2022-09-11T09:51:32.576641Z","shell.execute_reply.started":"2022-09-11T09:51:32.516523Z","shell.execute_reply":"2022-09-11T09:51:32.575831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"/kaggle/working/submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-09-11T09:51:32.578035Z","iopub.execute_input":"2022-09-11T09:51:32.578403Z","iopub.status.idle":"2022-09-11T09:51:34.261711Z","shell.execute_reply.started":"2022-09-11T09:51:32.578369Z","shell.execute_reply":"2022-09-11T09:51:34.260876Z"},"trusted":true},"execution_count":null,"outputs":[]}]}