{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":5048,"databundleVersionId":868335,"sourceType":"competition"}],"dockerImageVersionId":30198,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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":"2023-12-23T13:14:07.254253Z","iopub.execute_input":"2023-12-23T13:14:07.255029Z","iopub.status.idle":"2023-12-23T13:14:10.278573Z","shell.execute_reply.started":"2023-12-23T13:14:07.254860Z","shell.execute_reply":"2023-12-23T13:14:10.277788Z"},"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":"2023-12-23T13:14:10.280178Z","iopub.execute_input":"2023-12-23T13:14:10.280678Z","iopub.status.idle":"2023-12-23T13:14:10.290472Z","shell.execute_reply.started":"2023-12-23T13:14:10.280647Z","shell.execute_reply":"2023-12-23T13:14:10.289663Z"},"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":"2023-12-23T13:14:10.291585Z","iopub.execute_input":"2023-12-23T13:14:10.291871Z","iopub.status.idle":"2023-12-23T13:14:10.297977Z","shell.execute_reply.started":"2023-12-23T13:14:10.291845Z","shell.execute_reply":"2023-12-23T13:14:10.297241Z"},"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":"2023-12-23T13:14:10.298930Z","iopub.execute_input":"2023-12-23T13:14:10.299279Z","iopub.status.idle":"2023-12-23T13:14:13.096584Z","shell.execute_reply.started":"2023-12-23T13:14:10.299224Z","shell.execute_reply":"2023-12-23T13:14:13.095741Z"},"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":"2023-12-23T13:14:13.099138Z","iopub.execute_input":"2023-12-23T13:14:13.100009Z","iopub.status.idle":"2023-12-23T13:14:13.104729Z","shell.execute_reply.started":"2023-12-23T13:14:13.099950Z","shell.execute_reply":"2023-12-23T13:14:13.103904Z"},"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":"2023-12-23T13:14:13.105857Z","iopub.execute_input":"2023-12-23T13:14:13.106249Z","iopub.status.idle":"2023-12-23T13:14:33.415692Z","shell.execute_reply.started":"2023-12-23T13:14:13.106212Z","shell.execute_reply":"2023-12-23T13:14:33.414802Z"},"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":"2023-12-23T13:14:33.416878Z","iopub.execute_input":"2023-12-23T13:14:33.417294Z","iopub.status.idle":"2023-12-23T13:14:33.422852Z","shell.execute_reply.started":"2023-12-23T13:14:33.417254Z","shell.execute_reply":"2023-12-23T13:14:33.421780Z"},"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":"2023-12-23T13:14:33.423743Z","iopub.execute_input":"2023-12-23T13:14:33.424031Z","iopub.status.idle":"2023-12-23T13:14:33.646438Z","shell.execute_reply.started":"2023-12-23T13:14:33.424004Z","shell.execute_reply":"2023-12-23T13:14:33.645567Z"},"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":"2023-12-23T13:14:33.647637Z","iopub.execute_input":"2023-12-23T13:14:33.648032Z","iopub.status.idle":"2023-12-23T13:14:37.402705Z","shell.execute_reply.started":"2023-12-23T13:14:33.647986Z","shell.execute_reply":"2023-12-23T13:14:37.401489Z"},"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":"2023-12-23T13:14:37.403936Z","iopub.execute_input":"2023-12-23T13:14:37.404666Z","iopub.status.idle":"2023-12-23T13:14:37.481223Z","shell.execute_reply.started":"2023-12-23T13:14:37.404635Z","shell.execute_reply":"2023-12-23T13:14:37.480391Z"},"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":"2023-12-23T13:14:37.482678Z","iopub.execute_input":"2023-12-23T13:14:37.483279Z","iopub.status.idle":"2023-12-23T13:14:37.501843Z","shell.execute_reply.started":"2023-12-23T13:14:37.483242Z","shell.execute_reply":"2023-12-23T13:14:37.501046Z"},"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":"2023-12-23T13:14:37.503308Z","iopub.execute_input":"2023-12-23T13:14:37.503905Z","iopub.status.idle":"2023-12-23T13:14:41.864531Z","shell.execute_reply.started":"2023-12-23T13:14:37.503868Z","shell.execute_reply":"2023-12-23T13:14:41.863743Z"},"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":"2023-12-23T13:14:41.865664Z","iopub.execute_input":"2023-12-23T13:14:41.866026Z","iopub.status.idle":"2023-12-23T13:14:41.874237Z","shell.execute_reply.started":"2023-12-23T13:14:41.865987Z","shell.execute_reply":"2023-12-23T13:14:41.873294Z"},"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":"2023-12-23T13:14:41.878044Z","iopub.execute_input":"2023-12-23T13:14:41.878457Z","iopub.status.idle":"2023-12-23T13:14:41.894731Z","shell.execute_reply.started":"2023-12-23T13:14:41.878423Z","shell.execute_reply":"2023-12-23T13:14:41.893876Z"},"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":"2023-12-23T13:14:41.895802Z","iopub.execute_input":"2023-12-23T13:14:41.896175Z","iopub.status.idle":"2023-12-23T13:14:41.909677Z","shell.execute_reply.started":"2023-12-23T13:14:41.896143Z","shell.execute_reply":"2023-12-23T13:14:41.908727Z"},"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":"2023-12-23T13:14:41.911113Z","iopub.execute_input":"2023-12-23T13:14:41.911498Z","iopub.status.idle":"2023-12-23T13:14:46.304402Z","shell.execute_reply.started":"2023-12-23T13:14:41.911466Z","shell.execute_reply":"2023-12-23T13:14:46.303465Z"},"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":"2023-12-23T13:14:46.305792Z","iopub.execute_input":"2023-12-23T13:14:46.306464Z","iopub.status.idle":"2023-12-23T13:31:57.654610Z","shell.execute_reply.started":"2023-12-23T13:14:46.306422Z","shell.execute_reply":"2023-12-23T13:31:57.653151Z"},"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":"2023-12-23T13:31:57.656264Z","iopub.execute_input":"2023-12-23T13:31:57.656623Z","iopub.status.idle":"2023-12-23T13:31:57.873733Z","shell.execute_reply.started":"2023-12-23T13:31:57.656587Z","shell.execute_reply":"2023-12-23T13:31:57.872946Z"},"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":"2023-12-23T13:31:57.875009Z","iopub.execute_input":"2023-12-23T13:31:57.875486Z","iopub.status.idle":"2023-12-23T13:31:58.095014Z","shell.execute_reply.started":"2023-12-23T13:31:57.875439Z","shell.execute_reply":"2023-12-23T13:31:58.094194Z"},"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":"2023-12-23T13:31:58.096233Z","iopub.execute_input":"2023-12-23T13:31:58.096657Z","iopub.status.idle":"2023-12-23T13:31:58.253704Z","shell.execute_reply.started":"2023-12-23T13:31:58.096614Z","shell.execute_reply":"2023-12-23T13:31:58.252743Z"},"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":"2023-12-23T13:31:58.255640Z","iopub.execute_input":"2023-12-23T13:31:58.256053Z","iopub.status.idle":"2023-12-23T13:31:58.438052Z","shell.execute_reply.started":"2023-12-23T13:31:58.256014Z","shell.execute_reply":"2023-12-23T13:31:58.437067Z"},"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":"2023-12-23T13:31:58.439398Z","iopub.execute_input":"2023-12-23T13:31:58.439740Z","iopub.status.idle":"2023-12-23T13:31:59.105364Z","shell.execute_reply.started":"2023-12-23T13:31:58.439710Z","shell.execute_reply":"2023-12-23T13:31:59.104529Z"},"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":"2023-12-23T13:31:59.106398Z","iopub.execute_input":"2023-12-23T13:31:59.106699Z","iopub.status.idle":"2023-12-23T13:32:02.410558Z","shell.execute_reply.started":"2023-12-23T13:31:59.106673Z","shell.execute_reply":"2023-12-23T13:32:02.409655Z"},"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    proba2[proba2.index(max(proba2))] = 0.\n    print(\"2nd answer:\",class_dict[proba2.index(max(proba2))])\n    print(\"Confidence:\",max(proba2))","metadata":{"execution":{"iopub.status.busy":"2023-12-23T13:32:02.411819Z","iopub.execute_input":"2023-12-23T13:32:02.412252Z","iopub.status.idle":"2023-12-23T13:32:02.477879Z","shell.execute_reply.started":"2023-12-23T13:32:02.412209Z","shell.execute_reply":"2023-12-23T13:32:02.477040Z"},"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":"2023-12-23T13:32:02.479282Z","iopub.execute_input":"2023-12-23T13:32:02.480113Z","iopub.status.idle":"2023-12-23T13:32:02.486871Z","shell.execute_reply.started":"2023-12-23T13:32:02.480070Z","shell.execute_reply":"2023-12-23T13:32:02.485918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_true,y_pred = true_pred(test_loader,model)","metadata":{"execution":{"iopub.status.busy":"2023-12-23T13:32:02.488261Z","iopub.execute_input":"2023-12-23T13:32:02.488742Z","iopub.status.idle":"2023-12-23T13:32:40.102230Z","shell.execute_reply.started":"2023-12-23T13:32:02.488704Z","shell.execute_reply":"2023-12-23T13:32:40.101122Z"},"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":"2023-12-23T13:32:40.103639Z","iopub.execute_input":"2023-12-23T13:32:40.103951Z","iopub.status.idle":"2023-12-23T13:32:40.114556Z","shell.execute_reply.started":"2023-12-23T13:32:40.103922Z","shell.execute_reply":"2023-12-23T13:32:40.113791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.heatmap(m)","metadata":{"execution":{"iopub.status.busy":"2023-12-23T13:32:40.115652Z","iopub.execute_input":"2023-12-23T13:32:40.116026Z","iopub.status.idle":"2023-12-23T13:32:40.431548Z","shell.execute_reply.started":"2023-12-23T13:32:40.115984Z","shell.execute_reply":"2023-12-23T13:32:40.430718Z"},"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":"2023-12-23T13:32:40.432743Z","iopub.execute_input":"2023-12-23T13:32:40.433190Z","iopub.status.idle":"2023-12-23T13:32:40.437781Z","shell.execute_reply.started":"2023-12-23T13:32:40.433144Z","shell.execute_reply":"2023-12-23T13:32:40.437013Z"},"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":"2023-12-23T13:32:40.438824Z","iopub.execute_input":"2023-12-23T13:32:40.439144Z","iopub.status.idle":"2023-12-23T13:45:11.443677Z","shell.execute_reply.started":"2023-12-23T13:32:40.439115Z","shell.execute_reply":"2023-12-23T13:45:11.442745Z"},"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":"2023-12-23T13:45:11.444886Z","iopub.execute_input":"2023-12-23T13:45:11.445245Z","iopub.status.idle":"2023-12-23T13:45:11.450643Z","shell.execute_reply.started":"2023-12-23T13:45:11.445213Z","shell.execute_reply":"2023-12-23T13:45:11.449802Z"},"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":"2023-12-23T13:45:11.451705Z","iopub.execute_input":"2023-12-23T13:45:11.452036Z","iopub.status.idle":"2023-12-23T13:45:13.968171Z","shell.execute_reply.started":"2023-12-23T13:45:11.452002Z","shell.execute_reply":"2023-12-23T13:45:13.967341Z"},"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":"2023-12-23T13:45:13.969333Z","iopub.execute_input":"2023-12-23T13:45:13.969689Z","iopub.status.idle":"2023-12-23T13:45:13.982821Z","shell.execute_reply.started":"2023-12-23T13:45:13.969658Z","shell.execute_reply":"2023-12-23T13:45:13.981781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x,y = next(iter(loader))","metadata":{"execution":{"iopub.status.busy":"2023-12-23T13:45:13.984030Z","iopub.execute_input":"2023-12-23T13:45:13.984360Z","iopub.status.idle":"2023-12-23T13:45:14.603001Z","shell.execute_reply.started":"2023-12-23T13:45:13.984333Z","shell.execute_reply":"2023-12-23T13:45:14.601906Z"},"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":"2023-12-23T13:45:14.604523Z","iopub.execute_input":"2023-12-23T13:45:14.604831Z","iopub.status.idle":"2023-12-23T13:45:15.340830Z","shell.execute_reply.started":"2023-12-23T13:45:14.604801Z","shell.execute_reply":"2023-12-23T13:45:15.339940Z"},"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":"2023-12-23T13:45:15.342148Z","iopub.execute_input":"2023-12-23T13:45:15.343062Z","iopub.status.idle":"2023-12-23T13:45:15.532604Z","shell.execute_reply.started":"2023-12-23T13:45:15.343018Z","shell.execute_reply":"2023-12-23T13:45:15.531868Z"},"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":"2023-12-23T13:45:15.533841Z","iopub.execute_input":"2023-12-23T13:45:15.534250Z","iopub.status.idle":"2023-12-23T13:55:43.269100Z","shell.execute_reply.started":"2023-12-23T13:45:15.534211Z","shell.execute_reply":"2023-12-23T13:55:43.268036Z"},"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":"2023-12-23T13:55:43.270601Z","iopub.execute_input":"2023-12-23T13:55:43.270956Z","iopub.status.idle":"2023-12-23T13:55:48.002110Z","shell.execute_reply.started":"2023-12-23T13:55:43.270923Z","shell.execute_reply":"2023-12-23T13:55:48.001154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.rmdir(\"/kaggle/working/test\")","metadata":{"execution":{"iopub.status.busy":"2023-12-23T13:55:48.003367Z","iopub.execute_input":"2023-12-23T13:55:48.003709Z","iopub.status.idle":"2023-12-23T13:55:48.054585Z","shell.execute_reply.started":"2023-12-23T13:55:48.003679Z","shell.execute_reply":"2023-12-23T13:55:48.053912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"/kaggle/working/submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-12-23T13:55:48.055765Z","iopub.execute_input":"2023-12-23T13:55:48.056211Z","iopub.status.idle":"2023-12-23T13:55:49.769818Z","shell.execute_reply.started":"2023-12-23T13:55:48.056173Z","shell.execute_reply":"2023-12-23T13:55:49.768975Z"},"trusted":true},"execution_count":null,"outputs":[]}]}