{"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-12-14T08:47:48.370369Z","iopub.execute_input":"2022-12-14T08:47:48.370702Z","iopub.status.idle":"2022-12-14T08:47:51.839053Z","shell.execute_reply.started":"2022-12-14T08:47:48.370625Z","shell.execute_reply":"2022-12-14T08:47:51.837920Z"},"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-12-14T08:48:43.268882Z","iopub.execute_input":"2022-12-14T08:48:43.269575Z","iopub.status.idle":"2022-12-14T08:48:43.287167Z","shell.execute_reply.started":"2022-12-14T08:48:43.269539Z","shell.execute_reply":"2022-12-14T08:48:43.286191Z"},"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-12-14T08:48:47.414365Z","iopub.execute_input":"2022-12-14T08:48:47.414921Z","iopub.status.idle":"2022-12-14T08:48:47.420664Z","shell.execute_reply.started":"2022-12-14T08:48:47.414878Z","shell.execute_reply":"2022-12-14T08:48:47.419429Z"},"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-12-14T08:48:52.424177Z","iopub.execute_input":"2022-12-14T08:48:52.424544Z","iopub.status.idle":"2022-12-14T08:48:57.464486Z","shell.execute_reply.started":"2022-12-14T08:48:52.424508Z","shell.execute_reply":"2022-12-14T08:48:57.463129Z"},"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-12-14T08:49:05.943388Z","iopub.execute_input":"2022-12-14T08:49:05.944163Z","iopub.status.idle":"2022-12-14T08:49:05.948839Z","shell.execute_reply.started":"2022-12-14T08:49:05.944123Z","shell.execute_reply":"2022-12-14T08:49:05.947806Z"},"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-12-14T08:49:11.076600Z","iopub.execute_input":"2022-12-14T08:49:11.077128Z","iopub.status.idle":"2022-12-14T08:49:37.627502Z","shell.execute_reply.started":"2022-12-14T08:49:11.077084Z","shell.execute_reply":"2022-12-14T08:49:37.626622Z"},"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-12-14T08:49:42.597748Z","iopub.execute_input":"2022-12-14T08:49:42.598404Z","iopub.status.idle":"2022-12-14T08:49:42.604540Z","shell.execute_reply.started":"2022-12-14T08:49:42.598370Z","shell.execute_reply":"2022-12-14T08:49:42.602845Z"},"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-12-14T08:49:46.865709Z","iopub.execute_input":"2022-12-14T08:49:46.866386Z","iopub.status.idle":"2022-12-14T08:49:47.120507Z","shell.execute_reply.started":"2022-12-14T08:49:46.866351Z","shell.execute_reply":"2022-12-14T08:49:47.119760Z"},"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-12-14T08:49:51.103465Z","iopub.execute_input":"2022-12-14T08:49:51.103848Z","iopub.status.idle":"2022-12-14T08:49:55.081433Z","shell.execute_reply.started":"2022-12-14T08:49:51.103816Z","shell.execute_reply":"2022-12-14T08:49:55.080509Z"},"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-12-14T08:50:00.617149Z","iopub.execute_input":"2022-12-14T08:50:00.617531Z","iopub.status.idle":"2022-12-14T08:50:00.688822Z","shell.execute_reply.started":"2022-12-14T08:50:00.617492Z","shell.execute_reply":"2022-12-14T08:50:00.687951Z"},"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-12-14T08:50:05.861165Z","iopub.execute_input":"2022-12-14T08:50:05.861529Z","iopub.status.idle":"2022-12-14T08:50:05.866711Z","shell.execute_reply.started":"2022-12-14T08:50:05.861495Z","shell.execute_reply":"2022-12-14T08:50:05.865942Z"},"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-12-14T08:50:09.184472Z","iopub.execute_input":"2022-12-14T08:50:09.184862Z","iopub.status.idle":"2022-12-14T08:50:12.447890Z","shell.execute_reply.started":"2022-12-14T08:50:09.184829Z","shell.execute_reply":"2022-12-14T08:50:12.446955Z"},"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-12-14T08:50:16.810216Z","iopub.execute_input":"2022-12-14T08:50:16.810710Z","iopub.status.idle":"2022-12-14T08:50:16.829021Z","shell.execute_reply.started":"2022-12-14T08:50:16.810667Z","shell.execute_reply":"2022-12-14T08:50:16.824462Z"},"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-12-14T08:50:23.452795Z","iopub.execute_input":"2022-12-14T08:50:23.453154Z","iopub.status.idle":"2022-12-14T08:50:23.463871Z","shell.execute_reply.started":"2022-12-14T08:50:23.453123Z","shell.execute_reply":"2022-12-14T08:50:23.461912Z"},"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-12-14T08:50:41.068215Z","iopub.execute_input":"2022-12-14T08:50:41.068707Z","iopub.status.idle":"2022-12-14T08:50:41.075876Z","shell.execute_reply.started":"2022-12-14T08:50:41.068667Z","shell.execute_reply":"2022-12-14T08:50:41.074845Z"},"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-12-14T08:50:44.715037Z","iopub.execute_input":"2022-12-14T08:50:44.715402Z","iopub.status.idle":"2022-12-14T08:50:50.684758Z","shell.execute_reply.started":"2022-12-14T08:50:44.715374Z","shell.execute_reply":"2022-12-14T08:50:50.683923Z"},"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-12-14T08:51:01.460181Z","iopub.execute_input":"2022-12-14T08:51:01.460575Z","iopub.status.idle":"2022-12-14T09:09:59.568521Z","shell.execute_reply.started":"2022-12-14T08:51:01.460536Z","shell.execute_reply":"2022-12-14T09:09:59.567460Z"},"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-12-14T09:10:48.363166Z","iopub.execute_input":"2022-12-14T09:10:48.363556Z","iopub.status.idle":"2022-12-14T09:10:48.552417Z","shell.execute_reply.started":"2022-12-14T09:10:48.363521Z","shell.execute_reply":"2022-12-14T09:10:48.551674Z"},"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-12-14T09:10:53.067749Z","iopub.execute_input":"2022-12-14T09:10:53.068852Z","iopub.status.idle":"2022-12-14T09:10:53.265472Z","shell.execute_reply.started":"2022-12-14T09:10:53.068808Z","shell.execute_reply":"2022-12-14T09:10:53.264623Z"},"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-12-14T09:10:57.089461Z","iopub.execute_input":"2022-12-14T09:10:57.089860Z","iopub.status.idle":"2022-12-14T09:10:57.279572Z","shell.execute_reply.started":"2022-12-14T09:10:57.089828Z","shell.execute_reply":"2022-12-14T09:10:57.278831Z"},"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-12-14T09:11:02.307728Z","iopub.execute_input":"2022-12-14T09:11:02.308414Z","iopub.status.idle":"2022-12-14T09:11:02.498983Z","shell.execute_reply.started":"2022-12-14T09:11:02.308376Z","shell.execute_reply":"2022-12-14T09:11:02.498117Z"},"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-12-14T09:11:08.399459Z","iopub.execute_input":"2022-12-14T09:11:08.399843Z","iopub.status.idle":"2022-12-14T09:11:08.982262Z","shell.execute_reply.started":"2022-12-14T09:11:08.399808Z","shell.execute_reply":"2022-12-14T09:11:08.980811Z"},"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-12-14T09:11:18.924394Z","iopub.execute_input":"2022-12-14T09:11:18.925238Z","iopub.status.idle":"2022-12-14T09:11:22.110486Z","shell.execute_reply.started":"2022-12-14T09:11:18.925196Z","shell.execute_reply":"2022-12-14T09:11:22.109662Z"},"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":"2022-12-14T09:11:26.908376Z","iopub.execute_input":"2022-12-14T09:11:26.908734Z","iopub.status.idle":"2022-12-14T09:11:26.961838Z","shell.execute_reply.started":"2022-12-14T09:11:26.908704Z","shell.execute_reply":"2022-12-14T09:11:26.961047Z"},"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-12-14T09:12:15.349930Z","iopub.execute_input":"2022-12-14T09:12:15.350720Z","iopub.status.idle":"2022-12-14T09:12:15.356559Z","shell.execute_reply.started":"2022-12-14T09:12:15.350683Z","shell.execute_reply":"2022-12-14T09:12:15.355597Z"},"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-12-14T09:12:19.052143Z","iopub.execute_input":"2022-12-14T09:12:19.052569Z","iopub.status.idle":"2022-12-14T09:13:15.905825Z","shell.execute_reply.started":"2022-12-14T09:12:19.052534Z","shell.execute_reply":"2022-12-14T09:13:15.904805Z"},"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-12-14T09:13:43.385561Z","iopub.execute_input":"2022-12-14T09:13:43.385968Z","iopub.status.idle":"2022-12-14T09:13:43.397198Z","shell.execute_reply.started":"2022-12-14T09:13:43.385932Z","shell.execute_reply":"2022-12-14T09:13:43.396217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.heatmap(m)","metadata":{"execution":{"iopub.status.busy":"2022-12-14T09:13:46.592952Z","iopub.execute_input":"2022-12-14T09:13:46.593336Z","iopub.status.idle":"2022-12-14T09:13:46.863429Z","shell.execute_reply.started":"2022-12-14T09:13:46.593305Z","shell.execute_reply":"2022-12-14T09:13:46.862615Z"},"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-12-14T09:13:53.343952Z","iopub.execute_input":"2022-12-14T09:13:53.344329Z","iopub.status.idle":"2022-12-14T09:13:53.348912Z","shell.execute_reply.started":"2022-12-14T09:13:53.344298Z","shell.execute_reply":"2022-12-14T09:13:53.347998Z"},"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-12-14T09:13:57.009074Z","iopub.execute_input":"2022-12-14T09:13:57.009443Z","iopub.status.idle":"2022-12-14T09:27:14.250619Z","shell.execute_reply.started":"2022-12-14T09:13:57.009411Z","shell.execute_reply":"2022-12-14T09:27:14.249826Z"},"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-12-14T09:27:21.196543Z","iopub.execute_input":"2022-12-14T09:27:21.196931Z","iopub.status.idle":"2022-12-14T09:27:21.202253Z","shell.execute_reply.started":"2022-12-14T09:27:21.196899Z","shell.execute_reply":"2022-12-14T09:27:21.201294Z"},"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-12-14T09:27:26.913194Z","iopub.execute_input":"2022-12-14T09:27:26.913553Z","iopub.status.idle":"2022-12-14T09:27:29.026850Z","shell.execute_reply.started":"2022-12-14T09:27:26.913524Z","shell.execute_reply":"2022-12-14T09:27:29.026014Z"},"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-12-14T09:27:38.614099Z","iopub.execute_input":"2022-12-14T09:27:38.614984Z","iopub.status.idle":"2022-12-14T09:27:38.630841Z","shell.execute_reply.started":"2022-12-14T09:27:38.614931Z","shell.execute_reply":"2022-12-14T09:27:38.629839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x,y = next(iter(loader))","metadata":{"execution":{"iopub.status.busy":"2022-12-14T09:27:40.935798Z","iopub.execute_input":"2022-12-14T09:27:40.936176Z","iopub.status.idle":"2022-12-14T09:27:41.716431Z","shell.execute_reply.started":"2022-12-14T09:27:40.936146Z","shell.execute_reply":"2022-12-14T09:27:41.715177Z"},"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-12-14T09:27:46.049582Z","iopub.execute_input":"2022-12-14T09:27:46.049984Z","iopub.status.idle":"2022-12-14T09:27:46.738121Z","shell.execute_reply.started":"2022-12-14T09:27:46.049949Z","shell.execute_reply":"2022-12-14T09:27:46.737236Z"},"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-12-14T09:28:04.311625Z","iopub.execute_input":"2022-12-14T09:28:04.312001Z","iopub.status.idle":"2022-12-14T09:28:04.488834Z","shell.execute_reply.started":"2022-12-14T09:28:04.311970Z","shell.execute_reply":"2022-12-14T09:28:04.487947Z"},"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-12-14T09:28:09.464387Z","iopub.execute_input":"2022-12-14T09:28:09.464763Z","iopub.status.idle":"2022-12-14T09:44:24.242806Z","shell.execute_reply.started":"2022-12-14T09:28:09.464732Z","shell.execute_reply":"2022-12-14T09:44:24.241739Z"},"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-12-14T09:44:28.446360Z","iopub.execute_input":"2022-12-14T09:44:28.446752Z","iopub.status.idle":"2022-12-14T09:44:33.219322Z","shell.execute_reply.started":"2022-12-14T09:44:28.446716Z","shell.execute_reply":"2022-12-14T09:44:33.218135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.rmdir(\"/kaggle/working/test\")","metadata":{"execution":{"iopub.status.busy":"2022-12-14T09:44:36.564558Z","iopub.execute_input":"2022-12-14T09:44:36.565386Z","iopub.status.idle":"2022-12-14T09:44:36.613474Z","shell.execute_reply.started":"2022-12-14T09:44:36.565346Z","shell.execute_reply":"2022-12-14T09:44:36.611588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"/kaggle/working/submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-12-14T09:44:39.864805Z","iopub.execute_input":"2022-12-14T09:44:39.865490Z","iopub.status.idle":"2022-12-14T09:44:41.213528Z","shell.execute_reply.started":"2022-12-14T09:44:39.865454Z","shell.execute_reply":"2022-12-14T09:44:41.212711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}