{"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":"2024-03-31T10:40:49.760156Z","iopub.execute_input":"2024-03-31T10:40:49.761215Z","iopub.status.idle":"2024-03-31T10:40:52.129863Z","shell.execute_reply.started":"2024-03-31T10:40:49.761112Z","shell.execute_reply":"2024-03-31T10:40:52.129149Z"},"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":"2024-03-31T10:40:52.131375Z","iopub.execute_input":"2024-03-31T10:40:52.131841Z","iopub.status.idle":"2024-03-31T10:40:52.144589Z","shell.execute_reply.started":"2024-03-31T10:40:52.131812Z","shell.execute_reply":"2024-03-31T10:40:52.143748Z"},"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":"2024-03-31T10:40:52.145556Z","iopub.execute_input":"2024-03-31T10:40:52.145928Z","iopub.status.idle":"2024-03-31T10:40:52.150873Z","shell.execute_reply.started":"2024-03-31T10:40:52.145900Z","shell.execute_reply":"2024-03-31T10:40:52.150074Z"},"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":"2024-03-31T10:40:52.151771Z","iopub.execute_input":"2024-03-31T10:40:52.152058Z","iopub.status.idle":"2024-03-31T10:40:55.637521Z","shell.execute_reply.started":"2024-03-31T10:40:52.152031Z","shell.execute_reply":"2024-03-31T10:40:55.636718Z"},"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":"2024-03-31T10:40:55.640071Z","iopub.execute_input":"2024-03-31T10:40:55.640755Z","iopub.status.idle":"2024-03-31T10:40:55.645369Z","shell.execute_reply.started":"2024-03-31T10:40:55.640712Z","shell.execute_reply":"2024-03-31T10:40:55.644588Z"},"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":"2024-03-31T10:40:55.646495Z","iopub.execute_input":"2024-03-31T10:40:55.646783Z","iopub.status.idle":"2024-03-31T10:41:20.103585Z","shell.execute_reply.started":"2024-03-31T10:40:55.646756Z","shell.execute_reply":"2024-03-31T10:41:20.102870Z"},"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":"2024-03-31T10:41:20.104862Z","iopub.execute_input":"2024-03-31T10:41:20.105201Z","iopub.status.idle":"2024-03-31T10:41:20.110216Z","shell.execute_reply.started":"2024-03-31T10:41:20.105171Z","shell.execute_reply":"2024-03-31T10:41:20.109392Z"},"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":"2024-03-31T10:41:20.111204Z","iopub.execute_input":"2024-03-31T10:41:20.111492Z","iopub.status.idle":"2024-03-31T10:41:20.316998Z","shell.execute_reply.started":"2024-03-31T10:41:20.111465Z","shell.execute_reply":"2024-03-31T10:41:20.316150Z"},"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":"2024-03-31T10:41:20.318052Z","iopub.execute_input":"2024-03-31T10:41:20.318335Z","iopub.status.idle":"2024-03-31T10:41:24.093467Z","shell.execute_reply.started":"2024-03-31T10:41:20.318302Z","shell.execute_reply":"2024-03-31T10:41:24.092288Z"},"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":"2024-03-31T10:41:24.094906Z","iopub.execute_input":"2024-03-31T10:41:24.095330Z","iopub.status.idle":"2024-03-31T10:41:24.156870Z","shell.execute_reply.started":"2024-03-31T10:41:24.095292Z","shell.execute_reply":"2024-03-31T10:41:24.155918Z"},"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":"2024-03-31T10:41:24.158209Z","iopub.execute_input":"2024-03-31T10:41:24.158609Z","iopub.status.idle":"2024-03-31T10:41:24.169332Z","shell.execute_reply.started":"2024-03-31T10:41:24.158570Z","shell.execute_reply":"2024-03-31T10:41:24.168539Z"},"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":"2024-03-31T10:41:24.170332Z","iopub.execute_input":"2024-03-31T10:41:24.170657Z","iopub.status.idle":"2024-03-31T10:41:28.022786Z","shell.execute_reply.started":"2024-03-31T10:41:24.170629Z","shell.execute_reply":"2024-03-31T10:41:28.022020Z"},"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":"2024-03-31T10:41:28.023847Z","iopub.execute_input":"2024-03-31T10:41:28.024153Z","iopub.status.idle":"2024-03-31T10:41:28.032237Z","shell.execute_reply.started":"2024-03-31T10:41:28.024125Z","shell.execute_reply":"2024-03-31T10:41:28.031284Z"},"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":"2024-03-31T10:41:28.036431Z","iopub.execute_input":"2024-03-31T10:41:28.036784Z","iopub.status.idle":"2024-03-31T10:41:28.066249Z","shell.execute_reply.started":"2024-03-31T10:41:28.036753Z","shell.execute_reply":"2024-03-31T10:41:28.065318Z"},"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":"2024-03-31T10:41:28.067389Z","iopub.execute_input":"2024-03-31T10:41:28.067700Z","iopub.status.idle":"2024-03-31T10:41:28.080514Z","shell.execute_reply.started":"2024-03-31T10:41:28.067665Z","shell.execute_reply":"2024-03-31T10:41:28.079824Z"},"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":"2024-03-31T10:41:28.081538Z","iopub.execute_input":"2024-03-31T10:41:28.081851Z","iopub.status.idle":"2024-03-31T10:41:32.333430Z","shell.execute_reply.started":"2024-03-31T10:41:28.081824Z","shell.execute_reply":"2024-03-31T10:41:32.332677Z"},"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":"2024-03-31T10:41:32.334474Z","iopub.execute_input":"2024-03-31T10:41:32.334793Z","iopub.status.idle":"2024-03-31T10:58:31.119551Z","shell.execute_reply.started":"2024-03-31T10:41:32.334763Z","shell.execute_reply":"2024-03-31T10:58:31.118474Z"},"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":"2024-03-31T10:58:31.120923Z","iopub.execute_input":"2024-03-31T10:58:31.121277Z","iopub.status.idle":"2024-03-31T10:58:31.330072Z","shell.execute_reply.started":"2024-03-31T10:58:31.121244Z","shell.execute_reply":"2024-03-31T10:58:31.329298Z"},"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":"2024-03-31T10:58:31.331297Z","iopub.execute_input":"2024-03-31T10:58:31.331650Z","iopub.status.idle":"2024-03-31T10:58:31.542122Z","shell.execute_reply.started":"2024-03-31T10:58:31.331621Z","shell.execute_reply":"2024-03-31T10:58:31.541373Z"},"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":"2024-03-31T10:58:31.543043Z","iopub.execute_input":"2024-03-31T10:58:31.543307Z","iopub.status.idle":"2024-03-31T10:58:31.745649Z","shell.execute_reply.started":"2024-03-31T10:58:31.543280Z","shell.execute_reply":"2024-03-31T10:58:31.744803Z"},"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":"2024-03-31T10:58:31.746706Z","iopub.execute_input":"2024-03-31T10:58:31.747022Z","iopub.status.idle":"2024-03-31T10:58:31.932413Z","shell.execute_reply.started":"2024-03-31T10:58:31.746995Z","shell.execute_reply":"2024-03-31T10:58:31.931450Z"},"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":"2024-03-31T10:58:31.933790Z","iopub.execute_input":"2024-03-31T10:58:31.934611Z","iopub.status.idle":"2024-03-31T10:58:32.581494Z","shell.execute_reply.started":"2024-03-31T10:58:31.934565Z","shell.execute_reply":"2024-03-31T10:58:32.580652Z"},"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":"2024-03-31T10:58:32.582755Z","iopub.execute_input":"2024-03-31T10:58:32.583583Z","iopub.status.idle":"2024-03-31T10:58:33.984815Z","shell.execute_reply.started":"2024-03-31T10:58:32.583540Z","shell.execute_reply":"2024-03-31T10:58:33.984017Z"},"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":"2024-03-31T10:58:33.985911Z","iopub.execute_input":"2024-03-31T10:58:33.986211Z","iopub.status.idle":"2024-03-31T10:58:34.038820Z","shell.execute_reply.started":"2024-03-31T10:58:33.986184Z","shell.execute_reply":"2024-03-31T10:58:34.037754Z"},"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":"2024-03-31T10:58:34.040410Z","iopub.execute_input":"2024-03-31T10:58:34.041031Z","iopub.status.idle":"2024-03-31T10:58:34.047946Z","shell.execute_reply.started":"2024-03-31T10:58:34.040987Z","shell.execute_reply":"2024-03-31T10:58:34.047034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_true,y_pred = true_pred(test_loader,model)","metadata":{"execution":{"iopub.status.busy":"2024-03-31T10:58:34.049406Z","iopub.execute_input":"2024-03-31T10:58:34.050178Z","iopub.status.idle":"2024-03-31T10:59:11.134423Z","shell.execute_reply.started":"2024-03-31T10:58:34.050140Z","shell.execute_reply":"2024-03-31T10:59:11.132827Z"},"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":"2024-03-31T10:59:11.136362Z","iopub.execute_input":"2024-03-31T10:59:11.136745Z","iopub.status.idle":"2024-03-31T10:59:11.147994Z","shell.execute_reply.started":"2024-03-31T10:59:11.136712Z","shell.execute_reply":"2024-03-31T10:59:11.147255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.heatmap(m)","metadata":{"execution":{"iopub.status.busy":"2024-03-31T10:59:11.149130Z","iopub.execute_input":"2024-03-31T10:59:11.149463Z","iopub.status.idle":"2024-03-31T10:59:11.450365Z","shell.execute_reply.started":"2024-03-31T10:59:11.149435Z","shell.execute_reply":"2024-03-31T10:59:11.449564Z"},"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":"2024-03-31T10:59:11.451612Z","iopub.execute_input":"2024-03-31T10:59:11.452239Z","iopub.status.idle":"2024-03-31T10:59:11.456684Z","shell.execute_reply.started":"2024-03-31T10:59:11.452198Z","shell.execute_reply":"2024-03-31T10:59:11.455814Z"},"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":"2024-03-31T10:59:11.457771Z","iopub.execute_input":"2024-03-31T10:59:11.458136Z","iopub.status.idle":"2024-03-31T11:10:40.345370Z","shell.execute_reply.started":"2024-03-31T10:59:11.458108Z","shell.execute_reply":"2024-03-31T11:10:40.344492Z"},"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":"2024-03-31T11:10:40.346391Z","iopub.execute_input":"2024-03-31T11:10:40.346674Z","iopub.status.idle":"2024-03-31T11:10:40.351902Z","shell.execute_reply.started":"2024-03-31T11:10:40.346647Z","shell.execute_reply":"2024-03-31T11:10:40.351093Z"},"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":"2024-03-31T11:10:40.352954Z","iopub.execute_input":"2024-03-31T11:10:40.353285Z","iopub.status.idle":"2024-03-31T11:10:42.799163Z","shell.execute_reply.started":"2024-03-31T11:10:40.353257Z","shell.execute_reply":"2024-03-31T11:10:42.798208Z"},"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":"2024-03-31T11:10:42.800311Z","iopub.execute_input":"2024-03-31T11:10:42.800622Z","iopub.status.idle":"2024-03-31T11:10:42.812187Z","shell.execute_reply.started":"2024-03-31T11:10:42.800595Z","shell.execute_reply":"2024-03-31T11:10:42.811333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x,y = next(iter(loader))","metadata":{"execution":{"iopub.status.busy":"2024-03-31T11:10:42.813089Z","iopub.execute_input":"2024-03-31T11:10:42.813360Z","iopub.status.idle":"2024-03-31T11:10:43.353937Z","shell.execute_reply.started":"2024-03-31T11:10:42.813334Z","shell.execute_reply":"2024-03-31T11:10:43.352944Z"},"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":"2024-03-31T11:10:43.355363Z","iopub.execute_input":"2024-03-31T11:10:43.355700Z","iopub.status.idle":"2024-03-31T11:10:44.063767Z","shell.execute_reply.started":"2024-03-31T11:10:43.355668Z","shell.execute_reply":"2024-03-31T11:10:44.062924Z"},"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":"2024-03-31T11:10:44.064869Z","iopub.execute_input":"2024-03-31T11:10:44.065168Z","iopub.status.idle":"2024-03-31T11:10:44.260848Z","shell.execute_reply.started":"2024-03-31T11:10:44.065141Z","shell.execute_reply":"2024-03-31T11:10:44.259985Z"},"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":"2024-03-31T11:10:44.262054Z","iopub.execute_input":"2024-03-31T11:10:44.262382Z","iopub.status.idle":"2024-03-31T11:20:53.194534Z","shell.execute_reply.started":"2024-03-31T11:10:44.262353Z","shell.execute_reply":"2024-03-31T11:20:53.193454Z"},"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":"2024-03-31T11:20:53.196103Z","iopub.execute_input":"2024-03-31T11:20:53.196528Z","iopub.status.idle":"2024-03-31T11:20:57.769870Z","shell.execute_reply.started":"2024-03-31T11:20:53.196483Z","shell.execute_reply":"2024-03-31T11:20:57.769018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.rmdir(\"/kaggle/working/test\")","metadata":{"execution":{"iopub.status.busy":"2024-03-31T11:20:57.771083Z","iopub.execute_input":"2024-03-31T11:20:57.771397Z","iopub.status.idle":"2024-03-31T11:20:57.814358Z","shell.execute_reply.started":"2024-03-31T11:20:57.771368Z","shell.execute_reply":"2024-03-31T11:20:57.813551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"/kaggle/working/submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-03-31T11:20:57.815398Z","iopub.execute_input":"2024-03-31T11:20:57.815686Z","iopub.status.idle":"2024-03-31T11:20:59.419402Z","shell.execute_reply.started":"2024-03-31T11:20:57.815659Z","shell.execute_reply":"2024-03-31T11:20:59.418681Z"},"trusted":true},"execution_count":null,"outputs":[]}]}