{"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":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Import Required Libraries 📚</h1></span>","metadata":{}},{"cell_type":"code","source":"import os\nimport gc\nimport cv2\nimport math\nimport copy\nimport time\nimport random\nimport glob\nfrom matplotlib import pyplot as plt\n\n# For data manipulation\nimport numpy as np\nimport pandas as pd\n\n# Pytorch Imports\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.cuda import amp\nimport torchvision\n\nimport torchmetrics\n\n# Utils\nimport joblib\nfrom tqdm import tqdm\nfrom collections import defaultdict, Counter\n\n# Sklearn Imports\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold, StratifiedGroupKFold\n\n# For Image Models\nimport timm\n\n# Albumentations for augmentations\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\n# For colored terminal text\nfrom colorama import Fore, Back, Style\nb_ = Fore.BLUE\nsr_ = Style.RESET_ALL\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# For descriptive error messages\nos.environ['CUDA_LAUNCH_BLOCKING'] = \"1\"","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:45:44.379517Z","iopub.execute_input":"2023-11-04T13:45:44.379777Z","iopub.status.idle":"2023-11-04T13:46:00.148495Z","shell.execute_reply.started":"2023-11-04T13:45:44.379753Z","shell.execute_reply":"2023-11-04T13:46:00.147507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Training Configuration ⚙️</h1></span>","metadata":{}},{"cell_type":"code","source":"CONFIG = {\n    \"seed\": 42,\n    \"epochs\": 10,\n    \"img_size\": 2048,\n    \"model_name\": \"tf_efficientnet_b0_ns\",\n    \"checkpoint_path\" : \"/kaggle/input/tf-efficientnet/pytorch/tf-efficientnet-b0/1/tf_efficientnet_b0_aa-827b6e33.pth\",\n    \"pretrained\" : \"/kaggle/input/ubc-efficienetnetb0-fold1of10-2048pix-thumbnails/Recall0.9178_Acc0.9437_Loss0.1685_epoch9.bin\",\n    \"num_classes\": 5,\n    \"train_batch_size\": 2,\n    \"valid_batch_size\": 4,\n    \"learning_rate\": 2e-5,\n    \"scheduler\": 'CosineAnnealingLR',\n    \"min_lr\": 1e-6,\n    \"T_max\": 500,\n    \"weight_decay\": 1e-6,\n    \"fold\" : 0,\n    \"n_fold\": 10,\n    \"n_accumulate\": 1,\n    \"device\": torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\"),\n}","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.150087Z","iopub.execute_input":"2023-11-04T13:46:00.150598Z","iopub.status.idle":"2023-11-04T13:46:00.18094Z","shell.execute_reply.started":"2023-11-04T13:46:00.150571Z","shell.execute_reply":"2023-11-04T13:46:00.179988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Set Seed for Reproducibility</h1></span>","metadata":{}},{"cell_type":"code","source":"def set_seed(seed=42):\n    '''Sets the seed of the entire notebook so results are the same every time we run.\n    This is for REPRODUCIBILITY.'''\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    # When running on the CuDNN backend, two further options must be set\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False\n    # Set a fixed value for the hash seed\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    \nset_seed(CONFIG['seed'])","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.182247Z","iopub.execute_input":"2023-11-04T13:46:00.182535Z","iopub.status.idle":"2023-11-04T13:46:00.200391Z","shell.execute_reply.started":"2023-11-04T13:46:00.18251Z","shell.execute_reply":"2023-11-04T13:46:00.199591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT_DIR = '/kaggle/input/ubc-crop-training-raw-images'\nTEST_DIR = '/kaggle/input/UBC-OCEAN/test_images'","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.202697Z","iopub.execute_input":"2023-11-04T13:46:00.202998Z","iopub.status.idle":"2023-11-04T13:46:00.210667Z","shell.execute_reply.started":"2023-11-04T13:46:00.202964Z","shell.execute_reply":"2023-11-04T13:46:00.209674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Read the Data 📖</h1>","metadata":{}},{"cell_type":"code","source":"df_ori = pd.read_csv(\"/kaggle/input/UBC-OCEAN/train.csv\")\ndf_ori","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.211805Z","iopub.execute_input":"2023-11-04T13:46:00.212135Z","iopub.status.idle":"2023-11-04T13:46:00.253286Z","shell.execute_reply.started":"2023-11-04T13:46:00.212105Z","shell.execute_reply":"2023-11-04T13:46:00.252433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(f\"{ROOT_DIR}/train.csv\")\ndf[\"file_path\"] = df[\"file_path\"].apply(lambda x: f\"{ROOT_DIR}/{x}\" )\ndf","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.254375Z","iopub.execute_input":"2023-11-04T13:46:00.254916Z","iopub.status.idle":"2023-11-04T13:46:00.280276Z","shell.execute_reply.started":"2023-11-04T13:46:00.254885Z","shell.execute_reply":"2023-11-04T13:46:00.279418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[\"label\"].unique()","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.28142Z","iopub.execute_input":"2023-11-04T13:46:00.281753Z","iopub.status.idle":"2023-11-04T13:46:00.292309Z","shell.execute_reply.started":"2023-11-04T13:46:00.281722Z","shell.execute_reply":"2023-11-04T13:46:00.29147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder = LabelEncoder()\ndf['label_str'] = df['label']\ndf_ori[\"label\"] = encoder.fit_transform(df_ori['label'])\ndf['label'] = encoder.transform(df['label_str'])\n\nwith open(\"label_encoder.pkl\", \"wb\") as fp:\n    joblib.dump(encoder, fp)","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.29352Z","iopub.execute_input":"2023-11-04T13:46:00.29406Z","iopub.status.idle":"2023-11-04T13:46:00.303617Z","shell.execute_reply.started":"2023-11-04T13:46:00.294026Z","shell.execute_reply":"2023-11-04T13:46:00.302842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CLASS_WEIGHTS = Counter(df[\"label\"].values)\nCLASS_WEIGHTS = [ df.shape[0] / CLASS_WEIGHTS[i] for i in sorted(df[\"label\"].unique()) ]\nCLASS_WEIGHTS = [ val / sum(CLASS_WEIGHTS) for val in CLASS_WEIGHTS ]\nCLASS_WEIGHTS","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.304557Z","iopub.execute_input":"2023-11-04T13:46:00.304827Z","iopub.status.idle":"2023-11-04T13:46:00.317689Z","shell.execute_reply.started":"2023-11-04T13:46:00.304795Z","shell.execute_reply":"2023-11-04T13:46:00.316817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Create Folds</h1></span>","metadata":{}},{"cell_type":"code","source":"skf = StratifiedGroupKFold(n_splits=CONFIG['n_fold'], shuffle=True, random_state=CONFIG[\"seed\"])\n\nfor fold, ( _, val_) in enumerate(skf.split(X=df, y=df.label, groups=df.image_id)):\n      df.loc[val_ , \"kfold\"] = int(fold)","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.321051Z","iopub.execute_input":"2023-11-04T13:46:00.321313Z","iopub.status.idle":"2023-11-04T13:46:00.812102Z","shell.execute_reply.started":"2023-11-04T13:46:00.321292Z","shell.execute_reply":"2023-11-04T13:46:00.811097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CONFIG['T_max'] = df[df[\"kfold\"]!=CONFIG[\"fold\"]].shape[0] * CONFIG['epochs'] // CONFIG['train_batch_size']\nCONFIG['T_max']","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.813339Z","iopub.execute_input":"2023-11-04T13:46:00.813624Z","iopub.status.idle":"2023-11-04T13:46:00.821503Z","shell.execute_reply.started":"2023-11-04T13:46:00.813594Z","shell.execute_reply":"2023-11-04T13:46:00.820604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Dataset Class</h1></span>","metadata":{}},{"cell_type":"code","source":"class UBCDataset(Dataset):\n    def __init__(self, df, transforms=None):\n        self.df = df\n        self.file_names = df['file_path'].values\n        self.labels = df['label'].values\n        self.transforms = transforms\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, index):\n        img_path = self.file_names[index]\n        img = cv2.imread(img_path)\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        label = self.labels[index]\n        \n        if self.transforms:\n            img = self.transforms(image=img)[\"image\"]\n            \n        return {\n            'image': img,\n            'label': torch.tensor(label, dtype=torch.long)\n        }","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.822694Z","iopub.execute_input":"2023-11-04T13:46:00.822947Z","iopub.status.idle":"2023-11-04T13:46:00.831821Z","shell.execute_reply.started":"2023-11-04T13:46:00.822925Z","shell.execute_reply":"2023-11-04T13:46:00.830914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Augmentations</h1></span>","metadata":{}},{"cell_type":"code","source":"data_transforms = {\n    \"train\": A.Compose([\n        A.Resize(CONFIG['img_size'], CONFIG['img_size']),\n        A.Flip(p=0.5),\n        A.VerticalFlip(p=0.5),\n        A.RandomRotate90(p=1.0),\n        A.ShiftScaleRotate(shift_limit=0.1, \n                           scale_limit=0.15, \n                           rotate_limit=60, \n                           p=0.5),\n        A.HueSaturationValue(\n                hue_shift_limit=0.2, \n                sat_shift_limit=0.2, \n                val_shift_limit=0.2, \n                p=0.5\n            ),\n        A.RandomBrightnessContrast(\n                brightness_limit=(-0.1,0.1), \n                contrast_limit=(-0.1, 0.1), \n                p=0.5\n            ),\n        A.Normalize(\n                mean=[0.485, 0.456, 0.406], \n                std=[0.229, 0.224, 0.225], \n                max_pixel_value=255.0, \n                p=1.0\n            ),\n        ToTensorV2()], p=1.),\n    \n    \"valid\": A.Compose([\n        A.Resize(CONFIG['img_size'], CONFIG['img_size']),\n        A.Normalize(\n                mean=[0.485, 0.456, 0.406], \n                std=[0.229, 0.224, 0.225], \n                max_pixel_value=255.0, \n                p=1.0\n            ),\n        ToTensorV2()], p=1.)\n}","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.833096Z","iopub.execute_input":"2023-11-04T13:46:00.833694Z","iopub.status.idle":"2023-11-04T13:46:00.846277Z","shell.execute_reply.started":"2023-11-04T13:46:00.833662Z","shell.execute_reply":"2023-11-04T13:46:00.845529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">GeM Pooling</h1></span>","metadata":{}},{"cell_type":"code","source":"class GeM(nn.Module):\n    def __init__(self, p=3, eps=1e-6):\n        super(GeM, self).__init__()\n        self.p = nn.Parameter(torch.ones(1)*p)\n        self.eps = eps\n\n    def forward(self, x):\n        return self.gem(x, p=self.p, eps=self.eps)\n        \n    def gem(self, x, p=3, eps=1e-6):\n        return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(1./p)\n        \n    def __repr__(self):\n        return self.__class__.__name__ + \\\n                '(' + 'p=' + '{:.4f}'.format(self.p.data.tolist()[0]) + \\\n                ', ' + 'eps=' + str(self.eps) + ')'","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.84763Z","iopub.execute_input":"2023-11-04T13:46:00.847986Z","iopub.status.idle":"2023-11-04T13:46:00.85794Z","shell.execute_reply.started":"2023-11-04T13:46:00.847941Z","shell.execute_reply":"2023-11-04T13:46:00.857081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Create Model</h1></span>","metadata":{}},{"cell_type":"code","source":"class UBCModel(nn.Module):\n    def __init__(self, model_name, num_classes, pretrained=True, checkpoint_path=None):\n        super(UBCModel, self).__init__()\n        self.model = timm.create_model(model_name, pretrained=pretrained, checkpoint_path=checkpoint_path)\n\n        in_features = self.model.classifier.in_features\n        self.model.classifier = nn.Identity()\n        self.model.global_pool = nn.Identity()\n        self.pooling = GeM()\n        self.linear = nn.Linear(in_features, num_classes)\n        self.softmax = nn.Softmax(dim=1)\n\n    def forward(self, images):\n        features = self.model(images)\n        pooled_features = self.pooling(features).flatten(1)\n        output = self.linear(pooled_features)\n        return output\n\n    \nmodel = UBCModel(CONFIG['model_name'], CONFIG['num_classes'], checkpoint_path=CONFIG['checkpoint_path'])\nmodel.to(CONFIG['device']);","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:00.859135Z","iopub.execute_input":"2023-11-04T13:46:00.859389Z","iopub.status.idle":"2023-11-04T13:46:07.058058Z","shell.execute_reply.started":"2023-11-04T13:46:00.859366Z","shell.execute_reply":"2023-11-04T13:46:07.05718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if \"pretrained\" in CONFIG:\n    model.load_state_dict( torch.load(CONFIG[\"pretrained\"]))","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.05916Z","iopub.execute_input":"2023-11-04T13:46:07.059437Z","iopub.status.idle":"2023-11-04T13:46:07.341622Z","shell.execute_reply.started":"2023-11-04T13:46:07.059413Z","shell.execute_reply":"2023-11-04T13:46:07.340818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Loss Function</h1></span>","metadata":{}},{"cell_type":"code","source":"def criterion(outputs, labels):\n    return nn.CrossEntropyLoss( weight = torch.tensor(CLASS_WEIGHTS).cuda() )(outputs, labels)","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.34282Z","iopub.execute_input":"2023-11-04T13:46:07.343122Z","iopub.status.idle":"2023-11-04T13:46:07.347813Z","shell.execute_reply.started":"2023-11-04T13:46:07.343096Z","shell.execute_reply":"2023-11-04T13:46:07.34692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Training Function</h1></span>","metadata":{}},{"cell_type":"code","source":"def train_one_epoch(model, optimizer, scheduler, dataloader, device, epoch):\n    model.train()\n    \n    dataset_size = 0\n    running_loss = 0.0\n    running_acc  = 0.0\n    running_recall = 0.0\n    \n    bar = tqdm(enumerate(dataloader), total=len(dataloader))\n    for step, data in bar:\n        images = data['image'].to(device, dtype=torch.float)\n        labels = data['label'].to(device, dtype=torch.long)\n        \n        batch_size = images.size(0)\n        \n        outputs = model(images)\n        loss = criterion(outputs, labels)        \n        loss = loss / CONFIG['n_accumulate']\n            \n        loss.backward()\n    \n        if (step + 1) % CONFIG['n_accumulate'] == 0:\n            optimizer.step()\n\n            # zero the parameter gradients\n            optimizer.zero_grad()\n\n            if scheduler is not None:\n                scheduler.step()\n                \n        _, predicted = torch.max(model.softmax(outputs), 1)\n        acc = torch.sum( predicted == labels )\n        recall_nn = torchmetrics.Recall(task=\"multiclass\", average='macro', num_classes=CONFIG[\"num_classes\"]).cuda()\n        recall = recall_nn(predicted, labels)\n        \n        running_loss += (loss.item() * batch_size)\n        running_acc  += acc.item()\n        running_recall += (recall.item() * batch_size)\n        dataset_size += batch_size\n        \n        epoch_loss = running_loss / dataset_size\n        epoch_acc = running_acc / dataset_size\n        epoch_recall = running_recall / dataset_size\n        \n        bar.set_postfix(Epoch=epoch, Train_Loss=epoch_loss, Train_Acc=epoch_acc, Train_Recall=epoch_recall,\n                        LR=optimizer.param_groups[0]['lr'])\n    gc.collect()\n    \n    return epoch_loss, epoch_acc, epoch_recall","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.348975Z","iopub.execute_input":"2023-11-04T13:46:07.349394Z","iopub.status.idle":"2023-11-04T13:46:07.360903Z","shell.execute_reply.started":"2023-11-04T13:46:07.349362Z","shell.execute_reply":"2023-11-04T13:46:07.360196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Validation Function</h1></span>","metadata":{}},{"cell_type":"code","source":"@torch.inference_mode()\ndef valid_one_epoch(model, dataloader, device, epoch):\n    model.eval()\n    \n    dataset_size = 0\n    running_loss = 0.0\n    running_acc = 0.0\n    running_recall = 0.0\n    \n    bar = tqdm(enumerate(dataloader), total=len(dataloader))\n    for step, data in bar:        \n        images = data['image'].to(device, dtype=torch.float)\n        labels = data['label'].to(device, dtype=torch.long)\n        \n        batch_size = images.size(0)\n\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n\n        _, predicted = torch.max(model.softmax(outputs), 1)\n        acc = torch.sum( predicted == labels )\n        \n        recall_nn = torchmetrics.Recall(task=\"multiclass\", average='macro', num_classes=CONFIG[\"num_classes\"]).cuda()\n        recall = recall_nn(predicted, labels)\n\n        running_loss += (loss.item() * batch_size)\n        running_acc  += acc.item()\n        running_recall += (recall.item() * batch_size)\n        dataset_size += batch_size\n        \n        epoch_loss = running_loss / dataset_size\n        epoch_acc = running_acc / dataset_size\n        epoch_recall = running_recall / dataset_size\n        \n        bar.set_postfix(Epoch=epoch, Valid_Loss=epoch_loss, Valid_Acc=epoch_acc, Valid_Recall=epoch_recall,\n                        LR=optimizer.param_groups[0]['lr'])   \n    \n    gc.collect()\n    \n    return epoch_loss, epoch_acc, epoch_recall","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.361822Z","iopub.execute_input":"2023-11-04T13:46:07.362092Z","iopub.status.idle":"2023-11-04T13:46:07.375005Z","shell.execute_reply.started":"2023-11-04T13:46:07.362069Z","shell.execute_reply":"2023-11-04T13:46:07.374187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Run Training</h1></span>","metadata":{}},{"cell_type":"code","source":"def run_training(model, optimizer, scheduler, device, num_epochs):\n    if torch.cuda.is_available():\n        print(\"[INFO] Using GPU: {}\\n\".format(torch.cuda.get_device_name()))\n    \n    start = time.time()\n    best_model_wts = copy.deepcopy(model.state_dict())\n    best_epoch_recall = -np.inf\n    history = defaultdict(list)\n    \n    for epoch in range(1, num_epochs + 1): \n        gc.collect()\n        train_epoch_loss, train_epoch_acc, train_epoch_recall = train_one_epoch(model, optimizer, scheduler, \n                                           dataloader=train_loader, \n                                           device=CONFIG['device'], epoch=epoch)\n        \n        val_epoch_loss, val_epoch_acc, val_epoch_recall = valid_one_epoch(model, valid_loader, device=CONFIG['device'], \n                                         epoch=epoch)\n    \n        history['Train Loss'].append(train_epoch_loss)\n        history['Valid Loss'].append(val_epoch_loss)\n        history['Train Accuracy'].append(train_epoch_acc)\n        history['Valid Accuracy'].append(val_epoch_acc)\n        history['Train Recall'].append(train_epoch_recall)\n        history['Valid Recall'].append(val_epoch_recall)\n        history['lr'].append( scheduler.get_lr()[0] )\n        \n        # deep copy the model\n        if best_epoch_recall <= val_epoch_recall:\n            print(f\"{b_}Validation Recall Improved ({best_epoch_recall} ---> {val_epoch_recall})\")\n            best_epoch_recall = val_epoch_recall\n            best_model_wts = copy.deepcopy(model.state_dict())\n            PATH = \"Recall{:.4f}_Acc{:.4f}_Loss{:.4f}_epoch{:.0f}.bin\".format(val_epoch_recall, val_epoch_acc, val_epoch_loss, epoch)\n            torch.save(model.state_dict(), PATH)\n            # Save a model file from the current directory\n            print(f\"Model Saved{sr_}\")\n            \n        print()\n    \n    end = time.time()\n    time_elapsed = end - start\n    print('Training complete in {:.0f}h {:.0f}m {:.0f}s'.format(\n        time_elapsed // 3600, (time_elapsed % 3600) // 60, (time_elapsed % 3600) % 60))\n    print(\"Best Recall: {:.4f}\".format(best_epoch_recall))\n    \n    # load best model weights\n    model.load_state_dict(best_model_wts)\n    \n    return model, history","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.376158Z","iopub.execute_input":"2023-11-04T13:46:07.37645Z","iopub.status.idle":"2023-11-04T13:46:07.38952Z","shell.execute_reply.started":"2023-11-04T13:46:07.376427Z","shell.execute_reply":"2023-11-04T13:46:07.388795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def fetch_scheduler(optimizer):\n    if CONFIG['scheduler'] == 'CosineAnnealingLR':\n        scheduler = lr_scheduler.CosineAnnealingLR(optimizer,T_max=CONFIG['T_max'], \n                                                   eta_min=CONFIG['min_lr'])\n    elif CONFIG['scheduler'] == 'CosineAnnealingWarmRestarts':\n        scheduler = lr_scheduler.CosineAnnealingWarmRestarts(optimizer,T_0=CONFIG['T_0'], \n                                                             eta_min=CONFIG['min_lr'])\n    elif CONFIG['scheduler'] == None:\n        return None\n        \n    return scheduler","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.390542Z","iopub.execute_input":"2023-11-04T13:46:07.3908Z","iopub.status.idle":"2023-11-04T13:46:07.402806Z","shell.execute_reply.started":"2023-11-04T13:46:07.390778Z","shell.execute_reply":"2023-11-04T13:46:07.401909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prepare_loaders(df, fold):\n    df_train = df[df.kfold != fold].reset_index(drop=True)\n    df_valid = df[df.kfold == fold].reset_index(drop=True)\n    \n    train_dataset = UBCDataset(df_train, transforms=data_transforms[\"train\"])\n    valid_dataset = UBCDataset(df_valid, transforms=data_transforms[\"valid\"])\n\n    train_loader = DataLoader(train_dataset, batch_size=CONFIG['train_batch_size'], \n                              num_workers=2, shuffle=True, pin_memory=True, drop_last=True)\n    valid_loader = DataLoader(valid_dataset, batch_size=CONFIG['valid_batch_size'], \n                              num_workers=2, shuffle=False, pin_memory=True)\n    \n    return train_loader, valid_loader","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.403907Z","iopub.execute_input":"2023-11-04T13:46:07.405203Z","iopub.status.idle":"2023-11-04T13:46:07.416153Z","shell.execute_reply.started":"2023-11-04T13:46:07.405177Z","shell.execute_reply":"2023-11-04T13:46:07.415485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Prepare Dataloaders</span>","metadata":{}},{"cell_type":"code","source":"train_loader, valid_loader = prepare_loaders(df, fold=CONFIG[\"fold\"])","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.417282Z","iopub.execute_input":"2023-11-04T13:46:07.417549Z","iopub.status.idle":"2023-11-04T13:46:07.430341Z","shell.execute_reply.started":"2023-11-04T13:46:07.417526Z","shell.execute_reply":"2023-11-04T13:46:07.429485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Define Optimizer and Scheduler</span>","metadata":{}},{"cell_type":"code","source":"optimizer = optim.Adam(model.parameters(), lr=CONFIG['learning_rate'], \n                       weight_decay=CONFIG['weight_decay'])\nscheduler = fetch_scheduler(optimizer)","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.431237Z","iopub.execute_input":"2023-11-04T13:46:07.431493Z","iopub.status.idle":"2023-11-04T13:46:07.440637Z","shell.execute_reply.started":"2023-11-04T13:46:07.43147Z","shell.execute_reply":"2023-11-04T13:46:07.439823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Start Training</span>","metadata":{}},{"cell_type":"code","source":"model, history = run_training(model, optimizer, scheduler,\n                              device=CONFIG['device'],\n                              num_epochs=CONFIG['epochs'])","metadata":{"execution":{"iopub.status.busy":"2023-11-04T13:46:07.44157Z","iopub.execute_input":"2023-11-04T13:46:07.441812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = pd.DataFrame.from_dict(history)\nhistory.to_csv(\"history.csv\", index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Logs</h1></span>","metadata":{}},{"cell_type":"code","source":"plt.plot( range(history.shape[0]), history[\"Train Loss\"].values, label=\"Train Loss\")\nplt.plot( range(history.shape[0]), history[\"Valid Loss\"].values, label=\"Valid Loss\")\nplt.xlabel(\"epochs\")\nplt.ylabel(\"Loss\")\nplt.grid()\nplt.legend()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot( range(history.shape[0]), history[\"Train Recall\"].values, label=\"Train Recall\")\nplt.plot( range(history.shape[0]), history[\"Valid Recall\"].values, label=\"Valid Recall\")\nplt.xlabel(\"epochs\")\nplt.ylabel(\"Recall\")\nplt.grid()\nplt.legend()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot( range(history.shape[0]), history[\"Train Accuracy\"].values, label=\"Train Accuracy\")\nplt.plot( range(history.shape[0]), history[\"Valid Accuracy\"].values, label=\"Valid Accuracy\")\nplt.xlabel(\"epochs\")\nplt.ylabel(\"Accuracy\")\nplt.grid()\nplt.legend()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot( range(history.shape[0]), history[\"lr\"].values, label=\"lr\")\nplt.xlabel(\"epochs\")\nplt.ylabel(\"lr\")\nplt.grid()\nplt.legend()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">oof</h1></span>","metadata":{}},{"cell_type":"code","source":"oof_dataset = UBCDataset(df, transforms=data_transforms[\"valid\"])\noof_loader = DataLoader(oof_dataset, batch_size=CONFIG['valid_batch_size'], num_workers=2, shuffle=False, pin_memory=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"total_preds_conf = []\ntotal_preds_label = []\nwith torch.no_grad():\n    bar = tqdm(enumerate(oof_loader), total=len(oof_loader))\n    for step, data in bar:        \n        images = data['image'].to(CONFIG[\"device\"], dtype=torch.float)        \n        batch_size = images.size(0)\n        outputs = model(images)\n        preds_conf = model.softmax(outputs)\n        _, preds_label = torch.max(preds_conf, 1)\n        total_preds_conf.append( preds_conf.detach().cpu().numpy() )\n        total_preds_label.append( preds_label.detach().cpu().numpy() )\ntotal_preds_conf = np.concatenate(total_preds_conf, axis=0)\ntotal_preds_label = np.concatenate(total_preds_label).flatten()\ntotal_preds_label2 = encoder.inverse_transform( total_preds_label )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(total_preds_conf.shape[-1]):\n    df[f\"pred_conf_{i}\"] = total_preds_conf[:, i]\ndf[\"pred_label\"] = total_preds_label\ndf[\"pred_label_str\"] = total_preds_label2\ndf.to_csv(\"oof.csv\", index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}