{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n#    for filename in filenames:\n        #print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-04-05T01:26:26.588620Z","iopub.execute_input":"2023-04-05T01:26:26.589124Z","iopub.status.idle":"2023-04-05T01:26:26.624964Z","shell.execute_reply.started":"2023-04-05T01:26:26.589074Z","shell.execute_reply":"2023-04-05T01:26:26.623748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd /kaggle/input/bilinear","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:26.627506Z","iopub.execute_input":"2023-04-05T01:26:26.628349Z","iopub.status.idle":"2023-04-05T01:26:26.637352Z","shell.execute_reply.started":"2023-04-05T01:26:26.628302Z","shell.execute_reply":"2023-04-05T01:26:26.635996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport cv2\nfrom torchvision import transforms\nfrom torchvision.transforms import ToTensor\nfrom torch.utils.data import Dataset, DataLoader\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom tqdm import trange\nimport torchvision\nfrom CompactBilinearPooling import CompactBilinearPooling","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:26.639300Z","iopub.execute_input":"2023-04-05T01:26:26.640127Z","iopub.status.idle":"2023-04-05T01:26:29.853747Z","shell.execute_reply.started":"2023-04-05T01:26:26.640082Z","shell.execute_reply":"2023-04-05T01:26:29.852524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd /kaggle/working","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:29.856401Z","iopub.execute_input":"2023-04-05T01:26:29.856843Z","iopub.status.idle":"2023-04-05T01:26:29.864112Z","shell.execute_reply.started":"2023-04-05T01:26:29.856814Z","shell.execute_reply":"2023-04-05T01:26:29.862835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make sure you're using cuda (GPU) by checking the hardware accelerator under Runtime -> Change runtime type\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(\"We're using:\", device)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:29.866159Z","iopub.execute_input":"2023-04-05T01:26:29.867029Z","iopub.status.idle":"2023-04-05T01:26:29.992107Z","shell.execute_reply.started":"2023-04-05T01:26:29.866988Z","shell.execute_reply":"2023-04-05T01:26:29.990812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if torch.cuda.device_count() > 1:\n        print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n        #model = nn.DataParallel(model).cuda()","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:29.995670Z","iopub.execute_input":"2023-04-05T01:26:29.996025Z","iopub.status.idle":"2023-04-05T01:26:30.020581Z","shell.execute_reply.started":"2023-04-05T01:26:29.995992Z","shell.execute_reply":"2023-04-05T01:26:30.019543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!nvidia-smi","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:30.023503Z","iopub.execute_input":"2023-04-05T01:26:30.024376Z","iopub.status.idle":"2023-04-05T01:26:31.212678Z","shell.execute_reply.started":"2023-04-05T01:26:30.024332Z","shell.execute_reply":"2023-04-05T01:26:31.211298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MyDataset(Dataset):\n\n    def __init__(self, image_path, transform=None):\n        self.image_path = image_path\n        self.labels = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv')\n        self.transform = transform\n\n    def __len__(self):\n        \n        # STUDENT TODO START: Return the number of samples in the dataset\n        return len(self.labels)\n        # STUDENT TODO END\n\n    def __getitem__(self, idx):\n        \n        if torch.is_tensor(idx):\n            idx = idx.tolist()\n\n        # STUDENT TODO START: Create the path to each image by joining the root path with the name of the file as found in labels.csv\n        img_name = self.image_path + '/' + self.labels.iloc[idx]['image_id']\n        # STUDENT TODO END\n\n        # Read the image from the file path\n        image = Image.open(img_name)\n        # Transform the image using self.transform\n        if self.transform:\n            image = self.transform(image)\n\n        if \"label\" in self.labels.columns:\n            # STUDENT TODO START: Extract label name and encode it using the LABELS_TO_ENCODING dictionary\n            label = self.labels.iloc[idx]['label']\n            # STUDENT TODO END\n            sample = (image, label)\n        else:\n            sample = (image)\n        return sample","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:31.216179Z","iopub.execute_input":"2023-04-05T01:26:31.216586Z","iopub.status.idle":"2023-04-05T01:26:31.226631Z","shell.execute_reply.started":"2023-04-05T01:26:31.216538Z","shell.execute_reply":"2023-04-05T01:26:31.225312Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Credit: https://www.kaggle.com/code/aliabdin1/calculate-mean-std-of-images/notebook\nmean = np.array([0.42984136, 0.49624753, 0.3129598 ])\nstd = np.array([0.21417203, 0.21910103, 0.19542212])","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:31.228641Z","iopub.execute_input":"2023-04-05T01:26:31.229461Z","iopub.status.idle":"2023-04-05T01:26:31.242814Z","shell.execute_reply.started":"2023-04-05T01:26:31.229422Z","shell.execute_reply":"2023-04-05T01:26:31.241719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=mean,\n    std=std), transforms.Resize((256,256))])","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:31.248591Z","iopub.execute_input":"2023-04-05T01:26:31.248969Z","iopub.status.idle":"2023-04-05T01:26:31.255344Z","shell.execute_reply.started":"2023-04-05T01:26:31.248937Z","shell.execute_reply":"2023-04-05T01:26:31.253989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = MyDataset(image_path=\"/kaggle/input/cassava-leaf-disease-classification/train_images\", transform=transform)\ntrain_data, test_data = torch.utils.data.random_split(dataset, [0.7, 0.3])","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:31.257313Z","iopub.execute_input":"2023-04-05T01:26:31.257787Z","iopub.status.idle":"2023-04-05T01:26:31.322897Z","shell.execute_reply.started":"2023-04-05T01:26:31.257719Z","shell.execute_reply":"2023-04-05T01:26:31.321759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class BCNN(nn.Module):\n  def __init__(self, num_classes):\n    super(BCNN, self).__init__()\n    features = torchvision.models.resnet34(pretrained=True)\n    self.conv = nn.Sequential(*list(features.children())[:-2])\n    self.fc = nn.Linear(512 * 512, num_classes)\n    self.softmax = nn.Softmax()\n\n  def forward(self, input):\n    features = self.conv(input)\n    features_size = features.size(2) * features.size(3)\n\n    features = features.view(features.size(0), 512, features_size)\n\n    features_T = torch.transpose(features, 1, 2)\n    features = torch.bmm(features, features_T) / (features_size)\n\n    features = features.view(features.size(0), 512 * 512)\n\n\n    features = torch.sign(features) * torch.sqrt(torch.abs(features) + 1e-12)\n\n    features = torch.nn.functional.normalize(features)\n\n\n    out = self.fc(features)\n    softmax = self.softmax(out)\n    return softmax","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:31.324764Z","iopub.execute_input":"2023-04-05T01:26:31.325410Z","iopub.status.idle":"2023-04-05T01:26:31.336916Z","shell.execute_reply.started":"2023-04-05T01:26:31.325368Z","shell.execute_reply":"2023-04-05T01:26:31.335788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = nn.DataParallel(BCNN(5)).cuda()\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=1e-4, weight_decay=1e-6, amsgrad=False) #torch.optim.Adam(model.parameters(), lr=5*1e-3)\n","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:31.339814Z","iopub.execute_input":"2023-04-05T01:26:31.340248Z","iopub.status.idle":"2023-04-05T01:26:35.720882Z","shell.execute_reply.started":"2023-04-05T01:26:31.340206Z","shell.execute_reply":"2023-04-05T01:26:35.719713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_loader = DataLoader(dataset=train_data, batch_size = 128, shuffle= True, num_workers=2)\ntest_loader = DataLoader(dataset=test_data, batch_size = 128, shuffle=False, num_workers=2)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:35.722770Z","iopub.execute_input":"2023-04-05T01:26:35.723221Z","iopub.status.idle":"2023-04-05T01:26:35.730488Z","shell.execute_reply.started":"2023-04-05T01:26:35.723177Z","shell.execute_reply":"2023-04-05T01:26:35.729328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Start fine-tuning...')","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:35.731997Z","iopub.execute_input":"2023-04-05T01:26:35.733051Z","iopub.status.idle":"2023-04-05T01:26:35.744117Z","shell.execute_reply.started":"2023-04-05T01:26:35.733009Z","shell.execute_reply":"2023-04-05T01:26:35.742911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def test_model(model, test_loader):\n    model.eval()\n    with torch.no_grad():\n        correct = 0\n        total = 0\n        for images, labels in test_loader:\n            images = images.to(device)\n            labels = labels.to(device)\n\n            outputs = model(images)\n\n            _,prediction = torch.max(outputs.data, 1)\n            correct += (prediction == labels).sum().item()\n            total += labels.size(0)\n        model.train()\n        return 100 * correct / total","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:35.746198Z","iopub.execute_input":"2023-04-05T01:26:35.746652Z","iopub.status.idle":"2023-04-05T01:26:35.755734Z","shell.execute_reply.started":"2023-04-05T01:26:35.746611Z","shell.execute_reply":"2023-04-05T01:26:35.754505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_acc = 0.\nbest_epoch = None\nend_patient = 0\nnum_epochs = 50\nscheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.1, patience=3, verbose=True)\n\nsave_model_path = ''\ntrain_loss = []\ntrain_accuracy = []\ntest_accuracy = []\n\nfor epoch in range(num_epochs):\n    correct = 0\n    total = 0\n    epoch_loss = 0.\n    for i, (images, labels) in enumerate(train_loader):\n        images = images.to(device)\n        labels = labels.to(device)\n\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n        epoch_loss += loss\n        _, prediction = torch.max(outputs.data, 1)\n        correct += (prediction == labels).sum().item()\n        total += labels.size(0)\n\n        print('Epoch %d: Iter %d, Loss %g' % (epoch + 1, i + 1, loss))\n        train_loss.append(loss)\n    train_acc = 100 * correct / total\n    print('Testing on test dataset...')\n    test_acc = test_model(model, test_loader)\n    print('Epoch [{}/{}] Loss: {:.4f} Train_Acc: {:.4f}  Test_Acc: {:.4f}'\n          .format(epoch + 1, num_epochs, epoch_loss, train_acc, test_acc))\n    scheduler.step(test_acc)\n    train_accuracy.append(train_acc)\n    test_accuracy.append(test_acc)\n    if test_acc > best_acc:\n        best_acc = test_acc\n        best_epoch = epoch + 1\n        #model_file = os.path.join(save_model_path, 'resnet34_epoch_%d_acc_%g.pth' %\n        #                          (best_epoch, best_acc))\n        #if os.path.isfile(model_file):\n        #    os.remove(os.path.join(save_model_path, 'resnet34__epoch_%d_acc_%g.pth' %\n        #                            (best_epoch, best_acc)))\n        print('The accuracy is improved, save model')\n        torch.save(model.state_dict(), os.path.join(\n                                                    'resnet34_tuning_epoch_%d_acc_%g.pth' %\n                                                    (best_epoch, best_acc)))\n\nprint('After the training, the end of the epoch %d, the accuracy %g is the highest' % (best_epoch, best_acc))","metadata":{"execution":{"iopub.status.busy":"2023-04-05T01:26:35.757559Z","iopub.execute_input":"2023-04-05T01:26:35.758321Z","iopub.status.idle":"2023-04-05T05:35:13.309394Z","shell.execute_reply.started":"2023-04-05T01:26:35.758280Z","shell.execute_reply":"2023-04-05T05:35:13.308295Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2023-04-05T05:35:13.311116Z","iopub.execute_input":"2023-04-05T05:35:13.311885Z","iopub.status.idle":"2023-04-05T05:35:13.319444Z","shell.execute_reply.started":"2023-04-05T05:35:13.311823Z","shell.execute_reply":"2023-04-05T05:35:13.317116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(np.arange(1,51),train_accuracy,label='Train Accuracy')\nplt.plot(np.arange(1,51),test_accuracy,label='Test Accuracy')\nplt.legend()\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.title('Accuracy Versus Epochs')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-04-05T05:35:13.321480Z","iopub.execute_input":"2023-04-05T05:35:13.322058Z","iopub.status.idle":"2023-04-05T05:35:13.624202Z","shell.execute_reply.started":"2023-04-05T05:35:13.322018Z","shell.execute_reply":"2023-04-05T05:35:13.623127Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = nn.DataParallel(BCNN(5)).to(device)\nmodel.load_state_dict(torch.load('resnet34_tuning_epoch_29_acc_83.689.pth'))\n","metadata":{"execution":{"iopub.status.busy":"2023-04-05T05:35:57.658837Z","iopub.execute_input":"2023-04-05T05:35:57.659627Z","iopub.status.idle":"2023-04-05T05:35:58.272092Z","shell.execute_reply.started":"2023-04-05T05:35:57.659586Z","shell.execute_reply":"2023-04-05T05:35:58.270942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nb_classes = 5\n\nconfusion_matrix = torch.zeros(nb_classes, nb_classes)\nmodel.eval()\nwith torch.no_grad():\n    for i, (inputs, classes) in enumerate(test_loader):\n        inputs = inputs.to(device)\n        classes = classes.to(device)\n        #print(classes)\n        outputs = model(inputs)\n        _, preds = torch.max(outputs, 1)\n        for t, p in zip(classes.view(-1), preds.view(-1)):\n                confusion_matrix[t.long(), p.long()] += 1\n\nprint(confusion_matrix)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T05:36:02.198738Z","iopub.execute_input":"2023-04-05T05:36:02.199973Z","iopub.status.idle":"2023-04-05T05:37:23.548075Z","shell.execute_reply.started":"2023-04-05T05:36:02.199918Z","shell.execute_reply":"2023-04-05T05:37:23.546603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import itertools\n\ndef plot_confusion_matrix(cm, classes,\n                          normalize=True,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    if normalize:\n        cm = cm/ np.sum(cm)\n\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    fmt = '.2%' #if normalize else 'd'\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt),\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    plt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2023-04-05T05:37:23.550664Z","iopub.execute_input":"2023-04-05T05:37:23.552183Z","iopub.status.idle":"2023-04-05T05:37:23.563927Z","shell.execute_reply.started":"2023-04-05T05:37:23.552127Z","shell.execute_reply":"2023-04-05T05:37:23.562246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure()\nnum_classes=5\nM = confusion_matrix.numpy()\nplot_confusion_matrix(M, classes=np.arange(num_classes), normalize=True)\nprint(\"Accuracy:\",np.trace(M/np.sum(M)))","metadata":{"execution":{"iopub.status.busy":"2023-04-05T05:37:23.567270Z","iopub.execute_input":"2023-04-05T05:37:23.568075Z","iopub.status.idle":"2023-04-05T05:37:23.988055Z","shell.execute_reply.started":"2023-04-05T05:37:23.568043Z","shell.execute_reply":"2023-04-05T05:37:23.986915Z"},"trusted":true},"execution_count":null,"outputs":[]}]}