{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":45867,"databundleVersionId":6924515,"sourceType":"competition"},{"sourceId":6640479,"sourceType":"datasetVersion","datasetId":3833517}],"dockerImageVersionId":30617,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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\nfor 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-12-13T05:33:50.758932Z","iopub.execute_input":"2023-12-13T05:33:50.759376Z","iopub.status.idle":"2023-12-13T05:33:50.780074Z","shell.execute_reply.started":"2023-12-13T05:33:50.759345Z","shell.execute_reply":"2023-12-13T05:33:50.779034Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install timm","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:35:34.754568Z","iopub.execute_input":"2023-12-13T05:35:34.755407Z","iopub.status.idle":"2023-12-13T05:35:39.70626Z","shell.execute_reply.started":"2023-12-13T05:35:34.755367Z","shell.execute_reply":"2023-12-13T05:35:39.704947Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install albumentations","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:36:48.747754Z","iopub.execute_input":"2023-12-13T05:36:48.748809Z","iopub.status.idle":"2023-12-13T05:36:54.683911Z","shell.execute_reply.started":"2023-12-13T05:36:48.748767Z","shell.execute_reply":"2023-12-13T05:36:54.68241Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install colorama","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:37:12.246293Z","iopub.execute_input":"2023-12-13T05:37:12.246719Z","iopub.status.idle":"2023-12-13T05:37:15.956352Z","shell.execute_reply.started":"2023-12-13T05:37:12.246683Z","shell.execute_reply":"2023-12-13T05:37:15.955165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\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 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-12-13T05:37:19.686009Z","iopub.execute_input":"2023-12-13T05:37:19.68646Z","iopub.status.idle":"2023-12-13T05:37:19.701394Z","shell.execute_reply.started":"2023-12-13T05:37:19.68642Z","shell.execute_reply":"2023-12-13T05:37:19.700657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CONFIG = {\n    \"seed\": 42,\n    \"img_size\": 512, #380\n    \"model_name\": 'efficientnetv2_rw_m',\n    \"num_classes\": 5,\n    \"batch_size\": 8,\n    \"test_batch_size\":1,\n    \"num_epochs\" : 3,\n    \"device\": torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\"),\n}","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:41:50.908103Z","iopub.execute_input":"2023-12-13T05:41:50.90903Z","iopub.status.idle":"2023-12-13T05:41:50.914205Z","shell.execute_reply.started":"2023-12-13T05:41:50.908992Z","shell.execute_reply":"2023-12-13T05:41:50.913465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-13T05:41:55.095162Z","iopub.execute_input":"2023-12-13T05:41:55.095599Z","iopub.status.idle":"2023-12-13T05:41:55.104331Z","shell.execute_reply.started":"2023-12-13T05:41:55.095562Z","shell.execute_reply":"2023-12-13T05:41:55.103664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT_DIR = '/kaggle/input/UBC-OCEAN'\nTEST_DIR = '/kaggle/input/UBC-OCEAN/test_thumbnails'\nTRAIN_DIR = '/kaggle/input/UBC-OCEAN/train_thumbnails'\nALT_TEST_DIR = '/kaggle/input/UBC-OCEAN/test_images'\nALT_TRAIN_DIR = '/kaggle/input/UBC-OCEAN/train_images'\nLABEL_ENCODER_BIN = \"/kaggle/input/ubcpytorchwith-classweights-training-fold1of5/label_encoder.pkl\"","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:42:26.754782Z","iopub.execute_input":"2023-12-13T05:42:26.755959Z","iopub.status.idle":"2023-12-13T05:42:26.760303Z","shell.execute_reply.started":"2023-12-13T05:42:26.755917Z","shell.execute_reply":"2023-12-13T05:42:26.75963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_test_file_path(image_id):\n    if os.path.exists(f\"{TEST_DIR}/{image_id}_thumbnail.png\"):\n        return f\"{TEST_DIR}/{image_id}_thumbnail.png\"\n    else:\n        return f\"{ALT_TEST_DIR}/{image_id}.png\"\n\n\ndef get_train_file_path(image_id):\n    if os.path.exists(f\"{TRAIN_DIR}/{image_id}_thumbnail.png\"):\n        return f\"{TRAIN_DIR}/{image_id}_thumbnail.png\"\n    else:\n        return f\"{ALT_TRAIN_DIR}/{image_id}.png\"","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:43:55.056846Z","iopub.execute_input":"2023-12-13T05:43:55.057239Z","iopub.status.idle":"2023-12-13T05:43:55.062451Z","shell.execute_reply.started":"2023-12-13T05:43:55.057208Z","shell.execute_reply":"2023-12-13T05:43:55.061797Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:43:59.153201Z","iopub.execute_input":"2023-12-13T05:43:59.153654Z","iopub.status.idle":"2023-12-13T05:43:59.424507Z","shell.execute_reply.started":"2023-12-13T05:43:59.153575Z","shell.execute_reply":"2023-12-13T05:43:59.42366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder = joblib.load( LABEL_ENCODER_BIN )","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:44:02.710357Z","iopub.execute_input":"2023-12-13T05:44:02.710806Z","iopub.status.idle":"2023-12-13T05:44:02.71916Z","shell.execute_reply.started":"2023-12-13T05:44:02.710769Z","shell.execute_reply":"2023-12-13T05:44:02.718357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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(encoder.transform([label]), dtype=torch.long)\n        }","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:44:53.04565Z","iopub.execute_input":"2023-12-13T05:44:53.046526Z","iopub.status.idle":"2023-12-13T05:44:53.053662Z","shell.execute_reply.started":"2023-12-13T05:44:53.046487Z","shell.execute_reply":"2023-12-13T05:44:53.052862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_transforms = {\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    \"train\": 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-13T05:44:57.349265Z","iopub.execute_input":"2023-12-13T05:44:57.34971Z","iopub.status.idle":"2023-12-13T05:44:57.356345Z","shell.execute_reply.started":"2023-12-13T05:44:57.34967Z","shell.execute_reply":"2023-12-13T05:44:57.355411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-13T05:45:00.590672Z","iopub.execute_input":"2023-12-13T05:45:00.591548Z","iopub.status.idle":"2023-12-13T05:45:00.599202Z","shell.execute_reply.started":"2023-12-13T05:45:00.591502Z","shell.execute_reply":"2023-12-13T05:45:00.59824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)\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","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:45:04.23276Z","iopub.execute_input":"2023-12-13T05:45:04.233426Z","iopub.status.idle":"2023-12-13T05:45:04.239368Z","shell.execute_reply.started":"2023-12-13T05:45:04.233391Z","shell.execute_reply":"2023-12-13T05:45:04.238681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=CONFIG['seed'])  # you can choose another random state","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:45:08.192301Z","iopub.execute_input":"2023-12-13T05:45:08.193347Z","iopub.status.idle":"2023-12-13T05:45:08.197966Z","shell.execute_reply.started":"2023-12-13T05:45:08.193301Z","shell.execute_reply":"2023-12-13T05:45:08.197227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df.drop('label', axis=1)  # feature matrix\ny = df['label']  # target variable\n# Enumerate over each split index and train and test indices\nfor fold, (train_index, test_index) in enumerate(skf.split(X, y), 1):\n    df_train , df_valid = df.iloc[train_index],df.iloc[test_index]\n    # At this point, you can create and train your model with the training data\n    # And subsequently evaluate its performance with the test data\n    print(f'Fold: {fold}, Train set: {len(train_index)}, Test set: {len(test_index)}')\n    # Additional model training and evaluation code should be here\n    model = UBCModel(CONFIG['model_name'], CONFIG['num_classes'])\n    model.to(CONFIG['device']);\n    criterion = nn.CrossEntropyLoss()\n    optimizer = AdamW(model.parameters())\n    prev_loss = 1e6\n    train_dataset = UBCDataset(df_train, transforms=data_transforms[\"train\"])\n    train_loader = DataLoader(train_dataset, batch_size=CONFIG['batch_size'], \n                          num_workers=2, shuffle=True, pin_memory=True)\n    test_dataset = UBCDataset(df_valid, transforms=data_transforms[\"valid\"])\n    test_loader = DataLoader(test_dataset, batch_size=CONFIG['batch_size'], \n                          num_workers=2, shuffle=True, pin_memory=True)\n    for epoch in range(CONFIG[\"num_epochs\"]):\n        model.train()  # Set the model to training mode\n\n        running_loss = 0.0\n        correct = 0\n        total = 0\n        bar = tqdm(enumerate(train_loader), total=len(train_loader))\n        device = CONFIG['device']\n        for step, data in bar:\n            inputs, labels = data['image'] , data['label']\n            inputs, labels = inputs.to(device), labels.to(device)\n\n            # Zero the parameter gradients\n            optimizer.zero_grad()\n\n            # Forward pass\n            outputs = model(inputs)\n            # Calculate the loss\n            loss = criterion(outputs, labels.view(-1))\n\n            # Backpropagation and optimization\n            loss.backward()\n            optimizer.step()\n\n            # Update the running loss\n            running_loss += loss.item()\n            _, predicted = torch.max(outputs, 1) # Class with the highest probability is our prediction\n            predicted = predicted.reshape(-1,1)\n            total += labels.size(0)\n            correct += (predicted == labels).sum().item()\n        # Print the average loss for this epoch\n        print(f'Epoch [{epoch+1}/{CONFIG[\"num_epochs\"]}] Training Loss: {running_loss/len(train_loader)}')\n        print(f'Training Accuracy: {(correct/total) * 100:.2f}%')\n        if running_loss < prev_loss : \n            prev_loss = running_loss \n            torch.save(model.state_dict(), 'best-model_{}.pt'.format(fold))\n        # Evaluation\n        model.eval() # Set the model to evaluation mode\n        correct = 0\n        total = 0\n        total_valid_loss=0\n        with torch.no_grad(): # No need to track the gradients\n            bar = tqdm(enumerate(test_loader), total=len(test_loader))\n            for step, data in bar:\n                inputs, labels = data['image'] , data['label']\n                inputs, labels = inputs.to(device), labels.to(device)\n                output = model(inputs) # Get the model's predictions\n                val_loss = criterion(output, labels.view(-1)) # Calculate the loss\n                total_valid_loss += val_loss.item()\n                _, predicted = torch.max(output, 1) # Class with the highest probability is our prediction\n                predicted = predicted.reshape(-1,1)\n                total += labels.size(0)\n                correct += (predicted == labels).sum().item() # Count correct predictions\n        accuracy = correct / total\n        total_valid_loss = total_valid_loss / len(test_loader)\n        print('Validation Loss : {}'.format(total_valid_loss))\n        print(f'Validation Accuracy: {accuracy * 100:.2f}%')","metadata":{"execution":{"iopub.status.busy":"2023-12-13T05:45:14.91342Z","iopub.execute_input":"2023-12-13T05:45:14.914396Z","iopub.status.idle":"2023-12-13T05:46:34.93192Z","shell.execute_reply.started":"2023-12-13T05:45:14.914356Z","shell.execute_reply":"2023-12-13T05:46:34.930651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}