{"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-05-18T10:15:07.580402Z","iopub.execute_input":"2024-05-18T10:15:07.580813Z","iopub.status.idle":"2024-05-18T10:15:10.424549Z","shell.execute_reply.started":"2024-05-18T10:15:07.580732Z","shell.execute_reply":"2024-05-18T10:15:10.423671Z"},"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-05-18T10:15:10.426045Z","iopub.execute_input":"2024-05-18T10:15:10.426727Z","iopub.status.idle":"2024-05-18T10:15:10.437088Z","shell.execute_reply.started":"2024-05-18T10:15:10.426696Z","shell.execute_reply":"2024-05-18T10:15:10.436276Z"},"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-05-18T10:15:10.438134Z","iopub.execute_input":"2024-05-18T10:15:10.438445Z","iopub.status.idle":"2024-05-18T10:15:10.447556Z","shell.execute_reply.started":"2024-05-18T10:15:10.438402Z","shell.execute_reply":"2024-05-18T10:15:10.446801Z"},"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-05-18T10:15:10.449456Z","iopub.execute_input":"2024-05-18T10:15:10.449789Z","iopub.status.idle":"2024-05-18T10:15:11.877063Z","shell.execute_reply.started":"2024-05-18T10:15:10.449749Z","shell.execute_reply":"2024-05-18T10:15:11.876124Z"},"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-05-18T10:15:11.878324Z","iopub.execute_input":"2024-05-18T10:15:11.878680Z","iopub.status.idle":"2024-05-18T10:15:11.884117Z","shell.execute_reply.started":"2024-05-18T10:15:11.878645Z","shell.execute_reply":"2024-05-18T10:15:11.883248Z"},"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-05-18T10:15:11.885172Z","iopub.execute_input":"2024-05-18T10:15:11.885474Z","iopub.status.idle":"2024-05-18T10:15:23.068401Z","shell.execute_reply.started":"2024-05-18T10:15:11.885446Z","shell.execute_reply":"2024-05-18T10:15:23.067671Z"},"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-05-18T10:15:23.069415Z","iopub.execute_input":"2024-05-18T10:15:23.069705Z","iopub.status.idle":"2024-05-18T10:15:23.075126Z","shell.execute_reply.started":"2024-05-18T10:15:23.069679Z","shell.execute_reply":"2024-05-18T10:15:23.074312Z"},"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-05-18T10:15:23.076171Z","iopub.execute_input":"2024-05-18T10:15:23.076490Z","iopub.status.idle":"2024-05-18T10:15:23.288135Z","shell.execute_reply.started":"2024-05-18T10:15:23.076433Z","shell.execute_reply":"2024-05-18T10:15:23.287351Z"},"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-05-18T10:15:23.289084Z","iopub.execute_input":"2024-05-18T10:15:23.289355Z","iopub.status.idle":"2024-05-18T10:15:26.894899Z","shell.execute_reply.started":"2024-05-18T10:15:23.289329Z","shell.execute_reply":"2024-05-18T10:15:26.893880Z"},"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-05-18T10:15:26.898027Z","iopub.execute_input":"2024-05-18T10:15:26.898376Z","iopub.status.idle":"2024-05-18T10:15:26.959822Z","shell.execute_reply.started":"2024-05-18T10:15:26.898344Z","shell.execute_reply":"2024-05-18T10:15:26.958978Z"},"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-05-18T10:15:26.960997Z","iopub.execute_input":"2024-05-18T10:15:26.961312Z","iopub.status.idle":"2024-05-18T10:15:26.971892Z","shell.execute_reply.started":"2024-05-18T10:15:26.961283Z","shell.execute_reply":"2024-05-18T10:15:26.971137Z"},"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-05-18T10:15:26.972903Z","iopub.execute_input":"2024-05-18T10:15:26.973171Z","iopub.status.idle":"2024-05-18T10:15:31.652127Z","shell.execute_reply.started":"2024-05-18T10:15:26.973147Z","shell.execute_reply":"2024-05-18T10:15:31.651372Z"},"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-05-18T10:15:31.653196Z","iopub.execute_input":"2024-05-18T10:15:31.653514Z","iopub.status.idle":"2024-05-18T10:15:31.661022Z","shell.execute_reply.started":"2024-05-18T10:15:31.653486Z","shell.execute_reply":"2024-05-18T10:15:31.660137Z"},"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-05-18T10:15:31.662160Z","iopub.execute_input":"2024-05-18T10:15:31.662573Z","iopub.status.idle":"2024-05-18T10:15:31.676171Z","shell.execute_reply.started":"2024-05-18T10:15:31.662508Z","shell.execute_reply":"2024-05-18T10:15:31.675470Z"},"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-05-18T10:15:31.677151Z","iopub.execute_input":"2024-05-18T10:15:31.677435Z","iopub.status.idle":"2024-05-18T10:15:31.690588Z","shell.execute_reply.started":"2024-05-18T10:15:31.677408Z","shell.execute_reply":"2024-05-18T10:15:31.689926Z"},"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)\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-05-18T10:15:31.691465Z","iopub.execute_input":"2024-05-18T10:15:31.691745Z","iopub.status.idle":"2024-05-18T10:15:35.527091Z","shell.execute_reply.started":"2024-05-18T10:15:31.691718Z","shell.execute_reply":"2024-05-18T10:15:35.526346Z"},"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-05-18T10:15:35.528386Z","iopub.execute_input":"2024-05-18T10:15:35.528710Z","iopub.status.idle":"2024-05-18T10:32:32.417738Z","shell.execute_reply.started":"2024-05-18T10:15:35.528680Z","shell.execute_reply":"2024-05-18T10:32:32.416699Z"},"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-05-18T10:32:32.419163Z","iopub.execute_input":"2024-05-18T10:32:32.419510Z","iopub.status.idle":"2024-05-18T10:32:32.619215Z","shell.execute_reply.started":"2024-05-18T10:32:32.419475Z","shell.execute_reply":"2024-05-18T10:32:32.618416Z"},"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-05-18T10:32:32.620290Z","iopub.execute_input":"2024-05-18T10:32:32.620599Z","iopub.status.idle":"2024-05-18T10:32:32.825694Z","shell.execute_reply.started":"2024-05-18T10:32:32.620571Z","shell.execute_reply":"2024-05-18T10:32:32.824895Z"},"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-05-18T10:32:32.826991Z","iopub.execute_input":"2024-05-18T10:32:32.827458Z","iopub.status.idle":"2024-05-18T10:32:33.028148Z","shell.execute_reply.started":"2024-05-18T10:32:32.827419Z","shell.execute_reply":"2024-05-18T10:32:33.027300Z"},"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-05-18T10:32:33.029249Z","iopub.execute_input":"2024-05-18T10:32:33.029561Z","iopub.status.idle":"2024-05-18T10:32:33.210892Z","shell.execute_reply.started":"2024-05-18T10:32:33.029533Z","shell.execute_reply":"2024-05-18T10:32:33.209991Z"},"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-05-18T10:32:33.212051Z","iopub.execute_input":"2024-05-18T10:32:33.212368Z","iopub.status.idle":"2024-05-18T10:32:33.835424Z","shell.execute_reply.started":"2024-05-18T10:32:33.212338Z","shell.execute_reply":"2024-05-18T10:32:33.834414Z"},"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-05-18T10:32:33.836744Z","iopub.execute_input":"2024-05-18T10:32:33.837547Z","iopub.status.idle":"2024-05-18T10:32:37.272868Z","shell.execute_reply.started":"2024-05-18T10:32:33.837507Z","shell.execute_reply":"2024-05-18T10:32:37.271965Z"},"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-05-18T10:32:37.274050Z","iopub.execute_input":"2024-05-18T10:32:37.274362Z","iopub.status.idle":"2024-05-18T10:32:37.327939Z","shell.execute_reply.started":"2024-05-18T10:32:37.274335Z","shell.execute_reply":"2024-05-18T10:32:37.327146Z"},"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-05-18T10:32:37.329008Z","iopub.execute_input":"2024-05-18T10:32:37.329325Z","iopub.status.idle":"2024-05-18T10:32:37.335399Z","shell.execute_reply.started":"2024-05-18T10:32:37.329298Z","shell.execute_reply":"2024-05-18T10:32:37.334696Z"},"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-05-18T10:32:37.336301Z","iopub.execute_input":"2024-05-18T10:32:37.336567Z","iopub.status.idle":"2024-05-18T10:33:13.344592Z","shell.execute_reply.started":"2024-05-18T10:32:37.336542Z","shell.execute_reply":"2024-05-18T10:33:13.343616Z"},"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-05-18T10:33:13.346051Z","iopub.execute_input":"2024-05-18T10:33:13.346380Z","iopub.status.idle":"2024-05-18T10:33:13.356770Z","shell.execute_reply.started":"2024-05-18T10:33:13.346347Z","shell.execute_reply":"2024-05-18T10:33:13.356047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.heatmap(m)","metadata":{"execution":{"iopub.status.busy":"2024-05-18T10:33:13.361492Z","iopub.execute_input":"2024-05-18T10:33:13.362200Z","iopub.status.idle":"2024-05-18T10:33:13.653178Z","shell.execute_reply.started":"2024-05-18T10:33:13.362157Z","shell.execute_reply":"2024-05-18T10:33:13.652377Z"},"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-05-18T10:33:13.654356Z","iopub.execute_input":"2024-05-18T10:33:13.655020Z","iopub.status.idle":"2024-05-18T10:33:13.659107Z","shell.execute_reply.started":"2024-05-18T10:33:13.654981Z","shell.execute_reply":"2024-05-18T10:33:13.658269Z"},"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-05-18T10:33:13.660141Z","iopub.execute_input":"2024-05-18T10:33:13.660403Z","iopub.status.idle":"2024-05-18T10:47:39.508330Z","shell.execute_reply.started":"2024-05-18T10:33:13.660377Z","shell.execute_reply":"2024-05-18T10:47:39.507284Z"},"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-05-18T10:47:39.509764Z","iopub.execute_input":"2024-05-18T10:47:39.510233Z","iopub.status.idle":"2024-05-18T10:47:39.517280Z","shell.execute_reply.started":"2024-05-18T10:47:39.510188Z","shell.execute_reply":"2024-05-18T10:47:39.516386Z"},"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-05-18T10:47:39.518351Z","iopub.execute_input":"2024-05-18T10:47:39.518703Z","iopub.status.idle":"2024-05-18T10:47:42.014911Z","shell.execute_reply.started":"2024-05-18T10:47:39.518670Z","shell.execute_reply":"2024-05-18T10:47:42.014065Z"},"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-05-18T10:47:42.015956Z","iopub.execute_input":"2024-05-18T10:47:42.016236Z","iopub.status.idle":"2024-05-18T10:47:42.027484Z","shell.execute_reply.started":"2024-05-18T10:47:42.016210Z","shell.execute_reply":"2024-05-18T10:47:42.026679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x,y = next(iter(loader))","metadata":{"execution":{"iopub.status.busy":"2024-05-18T10:47:42.028641Z","iopub.execute_input":"2024-05-18T10:47:42.029002Z","iopub.status.idle":"2024-05-18T10:47:42.558414Z","shell.execute_reply.started":"2024-05-18T10:47:42.028967Z","shell.execute_reply":"2024-05-18T10:47:42.557404Z"},"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-05-18T10:47:42.559926Z","iopub.execute_input":"2024-05-18T10:47:42.560246Z","iopub.status.idle":"2024-05-18T10:47:43.243076Z","shell.execute_reply.started":"2024-05-18T10:47:42.560215Z","shell.execute_reply":"2024-05-18T10:47:43.242217Z"},"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-05-18T10:47:43.244313Z","iopub.execute_input":"2024-05-18T10:47:43.244681Z","iopub.status.idle":"2024-05-18T10:47:43.496931Z","shell.execute_reply.started":"2024-05-18T10:47:43.244647Z","shell.execute_reply":"2024-05-18T10:47:43.496194Z"},"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-05-18T10:47:43.498129Z","iopub.execute_input":"2024-05-18T10:47:43.498455Z","iopub.status.idle":"2024-05-18T10:57:50.331938Z","shell.execute_reply.started":"2024-05-18T10:47:43.498425Z","shell.execute_reply":"2024-05-18T10:57:50.330983Z"},"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-05-18T10:57:50.333686Z","iopub.execute_input":"2024-05-18T10:57:50.334547Z","iopub.status.idle":"2024-05-18T10:57:54.903835Z","shell.execute_reply.started":"2024-05-18T10:57:50.334499Z","shell.execute_reply":"2024-05-18T10:57:54.902974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.rmdir(\"/kaggle/working/test\")","metadata":{"execution":{"iopub.status.busy":"2024-05-18T10:57:54.904931Z","iopub.execute_input":"2024-05-18T10:57:54.905241Z","iopub.status.idle":"2024-05-18T10:57:54.948371Z","shell.execute_reply.started":"2024-05-18T10:57:54.905212Z","shell.execute_reply":"2024-05-18T10:57:54.947485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"/kaggle/working/submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-05-18T10:57:54.949454Z","iopub.execute_input":"2024-05-18T10:57:54.949790Z","iopub.status.idle":"2024-05-18T10:57:56.599278Z","shell.execute_reply.started":"2024-05-18T10:57:54.949761Z","shell.execute_reply":"2024-05-18T10:57:56.598566Z"},"trusted":true},"execution_count":null,"outputs":[]}]}