{"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":6874344,"sourceType":"datasetVersion","datasetId":3950227},{"sourceId":7166316,"sourceType":"datasetVersion","datasetId":4139825},{"sourceId":7186110,"sourceType":"datasetVersion","datasetId":4154379},{"sourceId":7237755,"sourceType":"datasetVersion","datasetId":4191586},{"sourceId":7246074,"sourceType":"datasetVersion","datasetId":4197586},{"sourceId":7267054,"sourceType":"datasetVersion","datasetId":4212315},{"sourceId":3729,"sourceType":"modelInstanceVersion","modelInstanceId":2656}],"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport gc\nimport cv2\nimport math\nimport copy\nimport time\nimport random\nimport glob\nfrom PIL import Image\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-23T14:20:41.004465Z","iopub.execute_input":"2023-12-23T14:20:41.004763Z","iopub.status.idle":"2023-12-23T14:20:48.61953Z","shell.execute_reply.started":"2023-12-23T14:20:41.00474Z","shell.execute_reply":"2023-12-23T14:20:48.618554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CONFIG = {\n    \"seed\": 42,\n    \"img_size\": 512,\n    \"model_name\": \"tf_efficientnet_b0_ns\",\n    \"num_classes\": 5,\n    \"valid_batch_size\": 4,\n    \"device\": torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\"),\n}","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:48.621102Z","iopub.execute_input":"2023-12-23T14:20:48.621528Z","iopub.status.idle":"2023-12-23T14:20:48.651823Z","shell.execute_reply.started":"2023-12-23T14:20:48.621502Z","shell.execute_reply":"2023-12-23T14:20:48.650868Z"},"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-23T14:20:48.652931Z","iopub.execute_input":"2023-12-23T14:20:48.653226Z","iopub.status.idle":"2023-12-23T14:20:48.677364Z","shell.execute_reply.started":"2023-12-23T14:20:48.653202Z","shell.execute_reply":"2023-12-23T14:20:48.67618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT_DIR = '/kaggle/input/UBC-OCEAN'\nTEST_DIR = '/kaggle/input/UBC-OCEAN/test_thumbnails'\n\nLABEL_ENCODER_BIN = \"/kaggle/input/ubc-efficienetnetb0-fold1of10-2048pix-thumbnails/label_encoder.pkl\"\nBEST_WEIGHT = \"/kaggle/input/phewphew/Recall0.8776_Acc0.9259_Loss0.2257_epoch3.bin\"\nBEST_WEIGHT1 = \"/kaggle/input/ubc-efficienetnetb0-fold1of10-2048pix-thumbnails/Recall0.9178_Acc0.9437_Loss0.1685_epoch9.bin\"\nBEST_WEIGHT2 = \"/kaggle/input/ubc-efficienetnetb0-fold1of10-2048pix-thumbnails/Recall0.8858_Acc0.9155_Loss0.2106_epoch1.bin\"\nBEST_WEIGHT3 = \"/kaggle/input/eweweew/Recall0.8547_Acc0.9231_Loss0.1468_epoch2.bin\"","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:48.680493Z","iopub.execute_input":"2023-12-23T14:20:48.681262Z","iopub.status.idle":"2023-12-23T14:20:48.687466Z","shell.execute_reply.started":"2023-12-23T14:20:48.681227Z","shell.execute_reply":"2023-12-23T14:20:48.686416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_test_file_path(image_id):\n    return f\"{TEST_DIR}/{image_id}_thumbnail.png\"","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:48.68896Z","iopub.execute_input":"2023-12-23T14:20:48.689335Z","iopub.status.idle":"2023-12-23T14:20:48.699554Z","shell.execute_reply.started":"2023-12-23T14:20:48.689302Z","shell.execute_reply":"2023-12-23T14:20:48.698599Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(f\"{ROOT_DIR}/test.csv\")\ndf['file_path'] = df['image_id'].apply(get_test_file_path)\ndf['label'] = 0 # dummy\ndf","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:48.700779Z","iopub.execute_input":"2023-12-23T14:20:48.701143Z","iopub.status.idle":"2023-12-23T14:20:48.735209Z","shell.execute_reply.started":"2023-12-23T14:20:48.701112Z","shell.execute_reply":"2023-12-23T14:20:48.734207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub = pd.read_csv(f\"{ROOT_DIR}/sample_submission.csv\")\ndf_sub","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:48.736382Z","iopub.execute_input":"2023-12-23T14:20:48.736678Z","iopub.status.idle":"2023-12-23T14:20:48.748169Z","shell.execute_reply.started":"2023-12-23T14:20:48.736637Z","shell.execute_reply":"2023-12-23T14:20:48.747329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder = joblib.load( LABEL_ENCODER_BIN )","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:48.749543Z","iopub.execute_input":"2023-12-23T14:20:48.750205Z","iopub.status.idle":"2023-12-23T14:20:48.759883Z","shell.execute_reply.started":"2023-12-23T14:20:48.75017Z","shell.execute_reply":"2023-12-23T14:20:48.759057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_cropped_images(file_path, image_id, th_area = 1000):\n    image = Image.open(file_path)\n    # Aspect ratio\n    as_ratio = image.size[0] / image.size[1]\n    \n    sxs, exs, sys, eys = [],[],[],[]\n    if as_ratio >= 1.5:\n        # Crop\n        mask = np.max( np.array(image) > 0, axis=-1 ).astype(np.uint8)\n        retval, labels = cv2.connectedComponents(mask)\n        if retval >= as_ratio:\n            x, y = np.meshgrid( np.arange(image.size[0]), np.arange(image.size[1]) )\n            for label in range(1, retval):\n                area = np.sum(labels == label)\n                if area < th_area:\n                    continue\n                xs, ys= x[ labels == label ], y[ labels == label ]\n                sx, ex = np.min(xs), np.max(xs)\n                cx = (sx + ex) // 2\n                crop_size = image.size[1]\n                sx = max(0, cx-crop_size//2)\n                ex = min(sx + crop_size - 1, image.size[0]-1)\n                sx = ex - crop_size + 1\n                sy, ey = 0, image.size[1]-1\n                sxs.append(sx)\n                exs.append(ex)\n                sys.append(sy)\n                eys.append(ey)\n        else:\n            crop_size = image.size[1]\n            for i in range(int(as_ratio)):\n                sxs.append( i * crop_size )\n                exs.append( (i+1) * crop_size - 1 )\n                sys.append( 0 )\n                eys.append( crop_size - 1 )\n    else:\n        # Not Crop (entire image)\n        sxs, exs, sys, eys = [0,],[image.size[0]-1],[0,],[image.size[1]-1]\n\n    df_crop = pd.DataFrame()\n    df_crop[\"image_id\"] = [image_id] * len(sxs)\n    df_crop[\"file_path\"] = [file_path] * len(sxs)\n    df_crop[\"sx\"] = sxs\n    df_crop[\"ex\"] = exs\n    df_crop[\"sy\"] = sys\n    df_crop[\"ey\"] = eys\n    return df_crop","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:48.760908Z","iopub.execute_input":"2023-12-23T14:20:48.761173Z","iopub.status.idle":"2023-12-23T14:20:48.774466Z","shell.execute_reply.started":"2023-12-23T14:20:48.761151Z","shell.execute_reply":"2023-12-23T14:20:48.773437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dfs = []\nfor (file_path, image_id) in zip(df[\"file_path\"], df[\"image_id\"]):\n    dfs.append( get_cropped_images(file_path, image_id) )\n\ndf_crop = pd.concat(dfs)\ndf_crop[\"label\"] = 0 # dummy\ndf_crop","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:48.777684Z","iopub.execute_input":"2023-12-23T14:20:48.777971Z","iopub.status.idle":"2023-12-23T14:20:49.333727Z","shell.execute_reply.started":"2023-12-23T14:20:48.777938Z","shell.execute_reply":"2023-12-23T14:20:49.332817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_crop = df_crop.drop_duplicates(subset=[\"image_id\", \"sx\", \"ex\", \"sy\", \"ey\"]).reset_index(drop=True)\ndf_crop","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:49.334949Z","iopub.execute_input":"2023-12-23T14:20:49.335243Z","iopub.status.idle":"2023-12-23T14:20:49.352798Z","shell.execute_reply.started":"2023-12-23T14:20:49.33522Z","shell.execute_reply":"2023-12-23T14:20:49.351898Z"},"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        self.sxs = df[\"sx\"].values\n        self.exs = df[\"ex\"].values\n        self.sys = df[\"sy\"].values\n        self.eys = df[\"ey\"].values\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, index):\n        img_path = self.file_names[index]\n        sx = self.sxs[index]\n        ex = self.exs[index]\n        sy = self.sys[index]\n        ey = self.eys[index]\n        img = cv2.imread(img_path)\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        label = self.labels[index]\n        \n        img = img[ sy:ey, sx:ex, : ]\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-23T14:20:49.353881Z","iopub.execute_input":"2023-12-23T14:20:49.354205Z","iopub.status.idle":"2023-12-23T14:20:49.36377Z","shell.execute_reply.started":"2023-12-23T14:20:49.354171Z","shell.execute_reply":"2023-12-23T14:20:49.362621Z"},"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}","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:20:49.365121Z","iopub.execute_input":"2023-12-23T14:20:49.365492Z","iopub.status.idle":"2023-12-23T14:20:49.374329Z","shell.execute_reply.started":"2023-12-23T14:20:49.365459Z","shell.execute_reply":"2023-12-23T14:20:49.373407Z"},"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-23T14:36:43.971051Z","iopub.execute_input":"2023-12-23T14:36:43.971692Z","iopub.status.idle":"2023-12-23T14:36:43.979529Z","shell.execute_reply.started":"2023-12-23T14:36:43.971656Z","shell.execute_reply":"2023-12-23T14:36:43.978539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nclass UBCModel(nn.Module):\n    def __init__(self, model_name, num_classes, pretrained=False, 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\n\n    \nmodel = UBCModel(CONFIG['model_name'], CONFIG['num_classes'])\nmodel.load_state_dict(torch.load( BEST_WEIGHT ))\nmodel.to(CONFIG['device'])\nmodel1 = UBCModel(CONFIG['model_name'], CONFIG['num_classes'])\nmodel1.load_state_dict(torch.load( BEST_WEIGHT1 ))\nmodel1.to(CONFIG['device'])\nmodel2 = UBCModel(CONFIG['model_name'], CONFIG['num_classes'])\nmodel2.load_state_dict(torch.load( BEST_WEIGHT2 ))\nmodel2.to(CONFIG['device'])\nmodel3 = UBCModel(CONFIG['model_name'], CONFIG['num_classes'])\nmodel3.load_state_dict(torch.load( BEST_WEIGHT3 ))\nmodel3.to(CONFIG['device'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dataset = UBCDataset(df_crop, transforms=data_transforms[\"valid\"])\ntest_loader = DataLoader(test_dataset, batch_size=CONFIG['valid_batch_size'], \n                          num_workers=2, shuffle=False, pin_memory=True)","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:37:42.260659Z","iopub.execute_input":"2023-12-23T14:37:42.261151Z","iopub.status.idle":"2023-12-23T14:37:42.266802Z","shell.execute_reply.started":"2023-12-23T14:37:42.261112Z","shell.execute_reply":"2023-12-23T14:37:42.265873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"a=1\nb=10\nc=10\nd=1","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:37:43.407665Z","iopub.execute_input":"2023-12-23T14:37:43.408028Z","iopub.status.idle":"2023-12-23T14:37:43.412329Z","shell.execute_reply.started":"2023-12-23T14:37:43.407997Z","shell.execute_reply":"2023-12-23T14:37:43.411383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = []\nwith torch.no_grad():\n    bar = tqdm(enumerate(test_loader), total=len(test_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        outputs1 = model1(images)\n        outputs2 = model2(images)\n        outputs3 = model3(images)\n        output = (a*outputs + b*outputs1 + c*outputs2 + d*outputs3)/(a+b+c+d)\n        outputs = model.softmax(output)\n        preds.append( outputs.detach().cpu().numpy() )\n\npreds = np.vstack(preds)\nprint(preds.shape)","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:37:44.419467Z","iopub.execute_input":"2023-12-23T14:37:44.419826Z","iopub.status.idle":"2023-12-23T14:37:44.809595Z","shell.execute_reply.started":"2023-12-23T14:37:44.419797Z","shell.execute_reply":"2023-12-23T14:37:44.808528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(preds.shape[-1]):\n    df_crop[f\"cat{i}\"] = preds[:, i]\n\ndict_label = {}\nfor image_id, gdf in df_crop.groupby(\"image_id\"):\n    dict_label[image_id] = np.argmax( gdf[ [f\"cat{i}\" for i in range(preds.shape[-1])] ].values.max(axis=0) )\n    #dict_label[image_id] = np.argmax( gdf[ [f\"cat{i}\" for i in range(preds.shape[-1])] ].values.mean(axis=0) )\npreds = np.array( [ dict_label[image_id] for image_id in df[\"image_id\"].values ] )","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:37:45.763788Z","iopub.execute_input":"2023-12-23T14:37:45.764698Z","iopub.status.idle":"2023-12-23T14:37:45.775176Z","shell.execute_reply.started":"2023-12-23T14:37:45.764657Z","shell.execute_reply":"2023-12-23T14:37:45.77398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_labels = encoder.inverse_transform( preds )\ndf_sub[\"label\"] = pred_labels\ndf_sub.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:37:46.823227Z","iopub.execute_input":"2023-12-23T14:37:46.823879Z","iopub.status.idle":"2023-12-23T14:37:46.831396Z","shell.execute_reply.started":"2023-12-23T14:37:46.823846Z","shell.execute_reply":"2023-12-23T14:37:46.830443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub","metadata":{"execution":{"iopub.status.busy":"2023-12-23T14:37:48.71592Z","iopub.execute_input":"2023-12-23T14:37:48.716278Z","iopub.status.idle":"2023-12-23T14:37:48.725292Z","shell.execute_reply.started":"2023-12-23T14:37:48.716253Z","shell.execute_reply":"2023-12-23T14:37:48.724318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}