{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset, DataLoader\n\nimport os\nimport json\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_DIR = '../input/herbarium-2021-fgvc8/train/'\nTEST_DIR = '../input/herbarium-2021-fgvc8/test/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with open(TRAIN_DIR + 'metadata.json', \"r\", encoding=\"ISO-8859-1\") as file:\n    train = json.load(file)    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_img = pd.DataFrame(train['images'])\ntrain_ann = pd.DataFrame(train['annotations']).drop(columns='image_id')\ntrain_df = train_img.merge(train_ann, on='id')\n\nprint(len(train_df))\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH = 128\nEPOCHS = 5\n\nLR = 0.01\nIM_SIZE = 224","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tr_df = train_df[:20000]\nlen(tr_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_Train, Y_Train = tr_df['file_name'].values, tr_df['category_id'].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Transform = transforms.Compose(\n    [transforms.ToTensor(),\n    transforms.Resize((IM_SIZE, IM_SIZE)),\n    transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class GetData(Dataset):\n    def __init__(self, Dir, FNames, Labels, Transform):\n        self.dir = Dir\n        self.fnames = FNames\n        self.transform = Transform\n        self.labels = Labels         \n        \n    def __len__(self):\n        return len(self.fnames)\n\n    def __getitem__(self, index):       \n        x = Image.open(os.path.join(self.dir, self.fnames[index]))\n    \n        if \"train\" in self.dir:             \n            return self.transform(x), self.labels[index]\n        elif \"test\" in self.dir:            \n            return self.transform(x), self.fnames[index]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trainset = GetData(TRAIN_DIR, X_Train, Y_Train, Transform)\ntrainloader = DataLoader(trainset, batch_size=BATCH, shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"NUM_CL = len(train_df['category_id'].value_counts())\nNUM_CL","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"next(iter(trainloader))[0].shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\ndevice","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = torchvision.models.densenet169(pretrained=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.classifier.in_features) \nprint(model.classifier.out_features)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for param in model.parameters():\n    param.requires_grad = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_inputs = model.classifier.in_features\nlast_layer = nn.Linear(n_inputs, NUM_CL)\nmodel.classifier = last_layer\nif torch.cuda.is_available():\n    model.cuda()\nprint(model.classifier.out_features)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.classifier.parameters())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"training_history = {'accuracy':[],'loss':[]}\nvalidation_history = {'accuracy':[],'loss':[]}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Normal Training\ndef train(trainloader, model, criterion, optimizer, scaler, device=torch.device(\"cpu\")):\n  train_acc = 0.0\n  train_loss = 0.0\n  for images, labels in tqdm(trainloader):\n    images = images.to(device)\n    labels = labels.to(device)\n    optimizer.zero_grad()\n#     with torch.cuda.amp.autocast(enabled=True):\n    output = model(images)\n    loss = criterion(output, labels)\n    scaler.scale(loss).backward()\n    scaler.step(optimizer)\n    scaler.update()\n    acc = ((output.argmax(dim=1) == labels).float().mean())\n    train_acc += acc\n    train_loss += loss\n  return train_acc/len(trainloader), train_loss/len(trainloader)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Normal Evaluation\ndef evaluate(testloader, model, criterion, device=torch.device(\"cpu\")):\n  eval_acc = 0.0\n  eval_loss = 0.0\n  for images, labels in tqdm(testloader):\n    images = images.to(device)\n    labels = labels.to(device)\n    with torch.no_grad():\n      output = model(images)\n      loss = criterion(output, labels)\n\n    acc = ((output.argmax(dim=1) == labels).float().mean())\n    eval_acc += acc\n    eval_loss += loss\n  \n  return eval_acc/len(testloader), eval_loss/len(testloader)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n## Normal Training\nscaler = torch.cuda.amp.GradScaler(enabled=True)\nfor epoch in range(EPOCHS):\n  train_acc, train_loss = train(trainloader, model, criterion, optimizer, scaler, device=device)\n#   eval_acc, eval_loss = evaluate(val_loader, model, criterion, device=torch.device(\"cuda\"))\n  print(\"\")\n  print(f\"Epoch {epoch + 1} | Train Acc: {train_acc*100} | Train Loss: {train_loss}\")\n#   print(f\"\\t Val Acc: {eval_acc*100} | Val Loss: {eval_loss}\")\n  print(\"====\"*8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"torch.save(model.state_dict(), \"model.pth\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\nwith open(TEST_DIR + 'metadata.json', \"r\", encoding=\"ISO-8859-1\") as file:\n    test = json.load(file)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.DataFrame(test['images'])\nX_Test = test_df['file_name'].values\nprint(len(test_df))\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"testset = GetData(TEST_DIR, X_Test, None, Transform)\ntestloader = DataLoader(testset, batch_size=1, shuffle=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\ns_ls = []\n\nwith torch.no_grad():\n    model.eval()\n    for image, fname in testloader: \n        image = image.to(device)\n        \n        logits = model(image)        \n        ps = torch.exp(logits)        \n        _, top_class = ps.topk(1, dim=1)\n        \n        for pred in top_class:\n            s_ls.append([fname[0].split('/')[-1][:-4], pred.item()])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.DataFrame.from_records(s_ls, columns=['Id', 'Predicted'])\nsub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}