{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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":45867,"databundleVersionId":6924515,"sourceType":"competition"},{"sourceId":3729,"sourceType":"modelInstanceVersion","modelInstanceId":2656}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# CS184a Project - UBC Ovarian Cancer Subtype Classification","metadata":{}},{"cell_type":"markdown","source":"## Imports for Model and Data","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# Image processing\nimport timm\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\n# Pytorch\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\n# Utils\nimport joblib\nfrom tqdm import tqdm\nfrom collections import defaultdict\n\n# Sklearn Imports\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold\n\n# For colored terminal text\nfrom colorama import Fore, Back, Style\nb_ = Fore.BLUE\nsr_ = Style.RESET_ALL\n\n# Format and filter potential warnings and errors\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# For descriptive error messages\nos.environ['CUDA_LAUNCH_BLOCKING'] = \"1\"","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:33.498272Z","iopub.execute_input":"2023-12-08T05:33:33.499154Z","iopub.status.idle":"2023-12-08T05:33:40.360268Z","shell.execute_reply.started":"2023-12-08T05:33:33.499116Z","shell.execute_reply":"2023-12-08T05:33:40.359092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Image and Model Hyperparameters","metadata":{}},{"cell_type":"code","source":"CONFIG = {\n    \"seed\": 42,\n    \"epochs\": 15,\n    \"img_size\": 512,\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    \"num_classes\": 5,\n    \"train_batch_size\": 32,\n    \"valid_batch_size\": 64,\n    \"learning_rate\": 0.0001,\n    \"scheduler\": 'CosineAnnealingLR',\n    \"min_lr\": 0.000001,\n    \"T_max\": 500,\n    \"weight_decay\": 0.000001,\n    \"fold\" : 0,\n    \"n_fold\": 5,\n    \"n_accumulate\": 1,\n    \"device\": torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\"),\n}","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:40.362736Z","iopub.execute_input":"2023-12-08T05:33:40.363426Z","iopub.status.idle":"2023-12-08T05:33:40.399933Z","shell.execute_reply.started":"2023-12-08T05:33:40.363382Z","shell.execute_reply":"2023-12-08T05:33:40.398718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Set Seed","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-12-08T05:33:40.401488Z","iopub.execute_input":"2023-12-08T05:33:40.401898Z","iopub.status.idle":"2023-12-08T05:33:40.425648Z","shell.execute_reply.started":"2023-12-08T05:33:40.401859Z","shell.execute_reply":"2023-12-08T05:33:40.424452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT_DIR = '/kaggle/input/UBC-OCEAN'\nTRAIN_DIR = '/kaggle/input/UBC-OCEAN/train_thumbnails'\nTEST_DIR = '/kaggle/input/UBC-OCEAN/test_images'","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:40.428137Z","iopub.execute_input":"2023-12-08T05:33:40.42869Z","iopub.status.idle":"2023-12-08T05:33:40.433221Z","shell.execute_reply.started":"2023-12-08T05:33:40.428659Z","shell.execute_reply":"2023-12-08T05:33:40.432143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_train_file_path(image_id):\n    return f\"{TRAIN_DIR}/{image_id}_thumbnail.png\"","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:40.434683Z","iopub.execute_input":"2023-12-08T05:33:40.435007Z","iopub.status.idle":"2023-12-08T05:33:40.446247Z","shell.execute_reply.started":"2023-12-08T05:33:40.434979Z","shell.execute_reply":"2023-12-08T05:33:40.445287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Retrieve Data from CSV Files and Link Them to Thumbnails","metadata":{}},{"cell_type":"code","source":"train_images = sorted(glob.glob(f\"{TRAIN_DIR}/*.png\"))","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:40.447562Z","iopub.execute_input":"2023-12-08T05:33:40.447931Z","iopub.status.idle":"2023-12-08T05:33:40.567775Z","shell.execute_reply.started":"2023-12-08T05:33:40.447896Z","shell.execute_reply":"2023-12-08T05:33:40.56664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(f\"{ROOT_DIR}/train.csv\")\ndf['file_path'] = df['image_id'].apply(get_train_file_path)\ndf = df[ df[\"file_path\"].isin(train_images) ].reset_index(drop=True)\ndf","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:40.569174Z","iopub.execute_input":"2023-12-08T05:33:40.569589Z","iopub.status.idle":"2023-12-08T05:33:40.621958Z","shell.execute_reply.started":"2023-12-08T05:33:40.569554Z","shell.execute_reply":"2023-12-08T05:33:40.620766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n# Assuming 'df' is your DataFrame with a 'label' column\n\ncounts = [0, 0, 0, 0, 0]\nlabels = ['CC', 'EC', 'HGSC', 'LGSC', 'MC']\n\nfor index, row in df.iterrows():\n    counts[labels.index(row['label'])] += 1\n\nfig, ax = plt.subplots(1, 1)\nax.set_title('Distribution of Class Labels in Training Dataset')\nax.pie(counts, labels=labels, autopct='%1.0f%%')\n\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:40.623444Z","iopub.execute_input":"2023-12-08T05:33:40.625469Z","iopub.status.idle":"2023-12-08T05:33:40.870399Z","shell.execute_reply.started":"2023-12-08T05:33:40.625429Z","shell.execute_reply":"2023-12-08T05:33:40.86857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder = LabelEncoder()\ndf['label'] = encoder.fit_transform(df['label'])\n\nwith open(\"label_encoder.pkl\", \"wb\") as fp:\n    joblib.dump(encoder, fp)","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:40.873378Z","iopub.execute_input":"2023-12-08T05:33:40.874984Z","iopub.status.idle":"2023-12-08T05:33:40.886349Z","shell.execute_reply.started":"2023-12-08T05:33:40.874922Z","shell.execute_reply":"2023-12-08T05:33:40.884958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CONFIG['T_max'] = df.shape[0] * (CONFIG[\"n_fold\"]-1) * CONFIG['epochs'] // CONFIG['train_batch_size'] // CONFIG[\"n_fold\"]\nCONFIG['T_max']","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:40.895135Z","iopub.execute_input":"2023-12-08T05:33:40.896564Z","iopub.status.idle":"2023-12-08T05:33:40.909021Z","shell.execute_reply.started":"2023-12-08T05:33:40.89649Z","shell.execute_reply":"2023-12-08T05:33:40.906953Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create Folds for k-Fold Cross Validation","metadata":{}},{"cell_type":"code","source":"skf = StratifiedKFold(n_splits=CONFIG['n_fold'])\n\nfor fold, ( _, val_) in enumerate(skf.split(X=df, y=df.label)):\n      df.loc[val_ , \"kfold\"] = int(fold)","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:40.911685Z","iopub.execute_input":"2023-12-08T05:33:40.912628Z","iopub.status.idle":"2023-12-08T05:33:40.925163Z","shell.execute_reply.started":"2023-12-08T05:33:40.912572Z","shell.execute_reply":"2023-12-08T05:33:40.924223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Format Data","metadata":{}},{"cell_type":"markdown","source":"### Data Class","metadata":{}},{"cell_type":"markdown","source":"Will be used to get relevant image information from thumbnails that are linked to csv file entries.\n\n","metadata":{}},{"cell_type":"code","source":"class UBCData(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-12-08T05:33:40.926904Z","iopub.execute_input":"2023-12-08T05:33:40.927245Z","iopub.status.idle":"2023-12-08T05:33:40.935955Z","shell.execute_reply.started":"2023-12-08T05:33:40.927206Z","shell.execute_reply":"2023-12-08T05:33:40.934803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Format and Transform Images","metadata":{}},{"cell_type":"code","source":"data_transforms = {\n    \"train\": A.Compose([\n        A.Resize(CONFIG['img_size'], CONFIG['img_size']),\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-12-08T05:33:40.93717Z","iopub.execute_input":"2023-12-08T05:33:40.937456Z","iopub.status.idle":"2023-12-08T05:33:40.947974Z","shell.execute_reply.started":"2023-12-08T05:33:40.93743Z","shell.execute_reply":"2023-12-08T05:33:40.946981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## GeM Pooling Implementation","metadata":{}},{"cell_type":"markdown","source":"Implementation taken from the following [link](https://amaarora.github.io/posts/2020-08-30-gempool.html)","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-12-08T05:33:40.949554Z","iopub.execute_input":"2023-12-08T05:33:40.950531Z","iopub.status.idle":"2023-12-08T05:33:40.958924Z","shell.execute_reply.started":"2023-12-08T05:33:40.950502Z","shell.execute_reply":"2023-12-08T05:33:40.958048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Creating a Model","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        inputs = self.model.classifier.in_features\n        self.model.classifier = nn.Identity()\n        self.model.global_pool = nn.Identity()\n        self.pooling = GeM()\n        # self.pooling = nn.AdaptiveAvgPool2d((1, 1))\n        # self.pooling = nn.AdaptiveMaxPool2d((1, 1))\n        self.linear = nn.Linear(inputs, num_classes)\n        self.softmax = nn.Softmax(dim=1)\n\n    def forward(self, images):\n        out = self.model(images)\n        out = self.pooling(out).flatten(1)\n        out = self.linear(out)\n        return out\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-12-08T05:33:40.960251Z","iopub.execute_input":"2023-12-08T05:33:40.960618Z","iopub.status.idle":"2023-12-08T05:33:46.252471Z","shell.execute_reply.started":"2023-12-08T05:33:40.960585Z","shell.execute_reply":"2023-12-08T05:33:46.251533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Implement a Loss Function","metadata":{}},{"cell_type":"markdown","source":"For this problem, we can use the built-in CrossEntropyLoss function as our loss function.\n\n","metadata":{}},{"cell_type":"code","source":"def criterion(outputs, labels):\n    return nn.CrossEntropyLoss()(outputs, labels)","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:46.253752Z","iopub.execute_input":"2023-12-08T05:33:46.254048Z","iopub.status.idle":"2023-12-08T05:33:46.258425Z","shell.execute_reply.started":"2023-12-08T05:33:46.254021Z","shell.execute_reply":"2023-12-08T05:33:46.257464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training (for a single epoch)","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:32:01.989941Z","iopub.execute_input":"2023-12-08T05:32:01.990918Z","iopub.status.idle":"2023-12-08T05:32:01.997408Z","shell.execute_reply.started":"2023-12-08T05:32:01.990872Z","shell.execute_reply":"2023-12-08T05:32:01.996318Z"}}},{"cell_type":"code","source":"def train_epoch(model, optimizer, scheduler, dataloader, device, epoch):\n    model.train()\n    \n    data_size = 0\n    current_loss = 0.0\n    current_acc  = 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        \n        current_loss += (loss.item() * batch_size)\n        current_acc  += acc.item()\n        data_size += batch_size\n        \n        epoch_loss = current_loss / data_size\n        epoch_acc = current_acc / data_size\n        \n        bar.set_postfix(Epoch=epoch, Train_Loss=epoch_loss, Train_Acc=epoch_acc,\n                        LR=optimizer.param_groups[0]['lr'])\n    gc.collect()\n    \n    return epoch_loss, epoch_acc","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:46.259608Z","iopub.execute_input":"2023-12-08T05:33:46.259888Z","iopub.status.idle":"2023-12-08T05:33:46.271002Z","shell.execute_reply.started":"2023-12-08T05:33:46.259864Z","shell.execute_reply":"2023-12-08T05:33:46.269632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Validation (for a single epoch)","metadata":{}},{"cell_type":"code","source":"@torch.inference_mode()\ndef validation_epoch(model, dataloader, device, epoch):\n    model.eval()\n    \n    data_size = 0\n    current_loss = 0.0\n    current_acc = 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        current_loss += (loss.item() * batch_size)\n        current_acc  += acc.item()\n        data_size += batch_size\n        \n        epoch_loss = current_loss / data_size\n        epoch_acc = current_acc / data_size\n        \n        bar.set_postfix(Epoch=epoch, Valid_Loss=epoch_loss, Valid_Acc=epoch_acc,\n                        LR=optimizer.param_groups[0]['lr'])   \n    \n    gc.collect()\n    \n    return epoch_loss, epoch_acc","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:46.272374Z","iopub.execute_input":"2023-12-08T05:33:46.272855Z","iopub.status.idle":"2023-12-08T05:33:46.283754Z","shell.execute_reply.started":"2023-12-08T05:33:46.27282Z","shell.execute_reply":"2023-12-08T05:33:46.282824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train the Model (over all epochs)","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 = copy.deepcopy(model.state_dict())\n    best_epoch_acc = -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(model, optimizer, scheduler, \n                                           dataloader=train_loader, \n                                           device=CONFIG['device'], epoch=epoch)\n        \n        val_epoch_loss, val_epoch_acc = validation_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        \n        # deep copy the model\n        if best_epoch_acc <= val_epoch_acc:\n            print(f\"{b_}Validation Accuracy Improved ({best_epoch_acc} ---> {val_epoch_acc})\")\n            best_epoch_acc = val_epoch_acc\n            best_model = copy.deepcopy(model.state_dict())\n            PATH = \"Acc{:.2f}_Loss{:.4f}_epoch{:.0f}.bin\".format(best_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 Accuracy: {:.4f}\".format(best_epoch_acc))\n    \n    # load best model weights\n    model.load_state_dict(best_model)\n    \n    return model, history","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:46.284926Z","iopub.execute_input":"2023-12-08T05:33:46.28526Z","iopub.status.idle":"2023-12-08T05:33:46.297309Z","shell.execute_reply.started":"2023-12-08T05:33:46.285214Z","shell.execute_reply":"2023-12-08T05:33:46.296295Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Prepare for Training Execution","metadata":{}},{"cell_type":"markdown","source":"### Fetch Scheduler","metadata":{}},{"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-12-08T05:33:46.298795Z","iopub.execute_input":"2023-12-08T05:33:46.299077Z","iopub.status.idle":"2023-12-08T05:33:46.30926Z","shell.execute_reply.started":"2023-12-08T05:33:46.299051Z","shell.execute_reply":"2023-12-08T05:33:46.308254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prepare Loaders","metadata":{}},{"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 = UBCData(df_train, transforms=data_transforms[\"train\"])\n    valid_dataset = UBCData(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-12-08T05:33:46.310624Z","iopub.execute_input":"2023-12-08T05:33:46.310945Z","iopub.status.idle":"2023-12-08T05:33:46.321344Z","shell.execute_reply.started":"2023-12-08T05:33:46.31092Z","shell.execute_reply":"2023-12-08T05:33:46.320316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_loader, valid_loader = prepare_loaders(df, fold=CONFIG[\"fold\"])","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:33:46.322671Z","iopub.execute_input":"2023-12-08T05:33:46.322986Z","iopub.status.idle":"2023-12-08T05:33:46.334762Z","shell.execute_reply.started":"2023-12-08T05:33:46.322962Z","shell.execute_reply":"2023-12-08T05:33:46.333672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Initialize Optimizer and Scheduler","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-12-08T05:33:46.336365Z","iopub.execute_input":"2023-12-08T05:33:46.33673Z","iopub.status.idle":"2023-12-08T05:33:46.345422Z","shell.execute_reply.started":"2023-12-08T05:33:46.336702Z","shell.execute_reply":"2023-12-08T05:33:46.344423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Execute Training","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-12-08T05:33:46.34674Z","iopub.execute_input":"2023-12-08T05:33:46.347538Z","iopub.status.idle":"2023-12-08T05:46:19.889892Z","shell.execute_reply.started":"2023-12-08T05:33:46.347508Z","shell.execute_reply":"2023-12-08T05:46:19.888844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Write Results to CSV","metadata":{}},{"cell_type":"code","source":"history = pd.DataFrame.from_dict(history)\nhistory.to_csv(\"history.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:46:19.891415Z","iopub.execute_input":"2023-12-08T05:46:19.891738Z","iopub.status.idle":"2023-12-08T05:46:19.900925Z","shell.execute_reply.started":"2023-12-08T05:46:19.89171Z","shell.execute_reply":"2023-12-08T05:46:19.899968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Result Visualization","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.title(\"Model Loss with Increasing Epochs\")\nplt.xlabel(\"epochs\")\nplt.ylabel(\"Loss\")\nplt.grid()\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:46:19.90234Z","iopub.execute_input":"2023-12-08T05:46:19.903167Z","iopub.status.idle":"2023-12-08T05:46:20.211937Z","shell.execute_reply.started":"2023-12-08T05:46:19.903127Z","shell.execute_reply":"2023-12-08T05:46:20.210994Z"},"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.title(\"Model Accuracy with Increasing Epochs\")\nplt.xlabel(\"epochs\")\nplt.ylabel(\"Accuracy\")\nplt.grid()\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-08T05:46:20.215722Z","iopub.execute_input":"2023-12-08T05:46:20.216044Z","iopub.status.idle":"2023-12-08T05:46:20.529642Z","shell.execute_reply.started":"2023-12-08T05:46:20.216016Z","shell.execute_reply":"2023-12-08T05:46:20.528635Z"},"trusted":true},"execution_count":null,"outputs":[]}]}