{"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":6640479,"sourceType":"datasetVersion","datasetId":3833517},{"sourceId":6827935,"sourceType":"datasetVersion","datasetId":3926155},{"sourceId":7056311,"sourceType":"datasetVersion","datasetId":4061631},{"sourceId":145733747,"sourceType":"kernelVersion"},{"sourceId":152653965,"sourceType":"kernelVersion"}],"dockerImageVersionId":30559,"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\nimport numpy as np\nimport pandas as pd\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\nimport joblib\nfrom tqdm import tqdm\nfrom collections import defaultdict\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold\nimport timm\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nfrom colorama import Fore, Back, Style\nb_ = Fore.BLUE\nsr_ = Style.RESET_ALL\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nos.environ['CUDA_LAUNCH_BLOCKING'] = \"1\"\nos.environ['CURL_CA_BUNDLE'] = ''","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-28T01:33:28.304855Z","iopub.execute_input":"2023-11-28T01:33:28.30513Z","iopub.status.idle":"2023-11-28T01:33:35.860211Z","shell.execute_reply.started":"2023-11-28T01:33:28.305104Z","shell.execute_reply":"2023-11-28T01:33:35.859393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CONFIG = {\n    \"seed\": 42,\n    \"img_size\": 2048,\n    \"model_name\": \"convnext_base_in22k\",\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-11-28T01:33:35.86177Z","iopub.execute_input":"2023-11-28T01:33:35.862171Z","iopub.status.idle":"2023-11-28T01:33:35.927978Z","shell.execute_reply.started":"2023-11-28T01:33:35.862145Z","shell.execute_reply":"2023-11-28T01:33:35.926981Z"},"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-11-28T01:33:35.929109Z","iopub.execute_input":"2023-11-28T01:33:35.929407Z","iopub.status.idle":"2023-11-28T01:33:35.962776Z","shell.execute_reply.started":"2023-11-28T01:33:35.929382Z","shell.execute_reply":"2023-11-28T01:33:35.962046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT_DIR = '/kaggle/input/UBC-OCEAN'\nTEST_DIR = '/kaggle/input/UBC-OCEAN/test_thumbnails'\nALT_TEST_DIR = '/kaggle/input/UBC-OCEAN/test_images'\nLABEL_ENCODER_BIN = \"/kaggle/input/ubc-train-with-convnext/label_encoder.pkl\"\nBEST_WEIGHT = \"/kaggle/input/ubc-train-with-convnext/Acc0.74_Loss0.7577_epoch6.bin\"\nBEST_WEIGHT2 = \"/kaggle/input/ubc-train-with-convnext/Acc0.80_Loss0.6564_epoch10.bin\"","metadata":{"execution":{"iopub.status.busy":"2023-11-28T01:33:35.965792Z","iopub.execute_input":"2023-11-28T01:33:35.966361Z","iopub.status.idle":"2023-11-28T01:33:35.970856Z","shell.execute_reply.started":"2023-11-28T01:33:35.966332Z","shell.execute_reply":"2023-11-28T01:33:35.969914Z"},"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\"","metadata":{"execution":{"iopub.status.busy":"2023-11-28T01:33:35.971739Z","iopub.execute_input":"2023-11-28T01:33:35.971966Z","iopub.status.idle":"2023-11-28T01:33:35.981466Z","shell.execute_reply.started":"2023-11-28T01:33:35.971945Z","shell.execute_reply":"2023-11-28T01:33:35.980616Z"},"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\ndf","metadata":{"execution":{"iopub.status.busy":"2023-11-28T01:33:35.98259Z","iopub.execute_input":"2023-11-28T01:33:35.982904Z","iopub.status.idle":"2023-11-28T01:33:36.028416Z","shell.execute_reply.started":"2023-11-28T01:33:35.982871Z","shell.execute_reply":"2023-11-28T01:33:36.027423Z"},"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-11-28T01:33:36.029655Z","iopub.execute_input":"2023-11-28T01:33:36.030006Z","iopub.status.idle":"2023-11-28T01:33:36.041875Z","shell.execute_reply.started":"2023-11-28T01:33:36.029971Z","shell.execute_reply":"2023-11-28T01:33:36.041043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder = joblib.load( LABEL_ENCODER_BIN )","metadata":{"execution":{"iopub.status.busy":"2023-11-28T01:33:36.043126Z","iopub.execute_input":"2023-11-28T01:33:36.043491Z","iopub.status.idle":"2023-11-28T01:33:36.051276Z","shell.execute_reply.started":"2023-11-28T01:33:36.043459Z","shell.execute_reply":"2023-11-28T01:33:36.05026Z"},"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-11-28T01:33:36.052459Z","iopub.execute_input":"2023-11-28T01:33:36.052773Z","iopub.status.idle":"2023-11-28T01:33:36.067301Z","shell.execute_reply.started":"2023-11-28T01:33:36.052742Z","shell.execute_reply":"2023-11-28T01:33:36.066531Z"},"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-11-28T01:33:36.068569Z","iopub.execute_input":"2023-11-28T01:33:36.068811Z","iopub.status.idle":"2023-11-28T01:33:36.658191Z","shell.execute_reply.started":"2023-11-28T01:33:36.06879Z","shell.execute_reply":"2023-11-28T01:33:36.657306Z"},"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-11-28T01:33:36.661498Z","iopub.execute_input":"2023-11-28T01:33:36.661774Z","iopub.status.idle":"2023-11-28T01:33:36.678187Z","shell.execute_reply.started":"2023-11-28T01:33:36.66175Z","shell.execute_reply":"2023-11-28T01:33:36.677367Z"},"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-11-28T01:33:36.679341Z","iopub.execute_input":"2023-11-28T01:33:36.679665Z","iopub.status.idle":"2023-11-28T01:33:36.689Z","shell.execute_reply.started":"2023-11-28T01:33:36.679631Z","shell.execute_reply":"2023-11-28T01:33:36.688124Z"},"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-11-28T01:33:36.690041Z","iopub.execute_input":"2023-11-28T01:33:36.690703Z","iopub.status.idle":"2023-11-28T01:33:36.699771Z","shell.execute_reply.started":"2023-11-28T01:33:36.690678Z","shell.execute_reply":"2023-11-28T01:33:36.69896Z"},"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-11-28T01:33:36.700634Z","iopub.execute_input":"2023-11-28T01:33:36.700887Z","iopub.status.idle":"2023-11-28T01:33:36.711254Z","shell.execute_reply.started":"2023-11-28T01:33:36.700865Z","shell.execute_reply":"2023-11-28T01:33:36.710508Z"},"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)\n        in_features = self.model.head.in_features\n        self.model.head = 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('convnext_base_in22k', CONFIG['num_classes'])\nmodel2 = UBCModel('convnext_base_in22k', CONFIG['num_classes'])\nmodel.load_state_dict(torch.load( BEST_WEIGHT ))\nmodel.to(CONFIG['device']);\nmodel2.load_state_dict(torch.load( BEST_WEIGHT2 ))\nmodel2.to(CONFIG['device']);","metadata":{"execution":{"iopub.status.busy":"2023-11-28T01:33:36.712317Z","iopub.execute_input":"2023-11-28T01:33:36.712628Z","iopub.status.idle":"2023-11-28T01:34:19.963332Z","shell.execute_reply.started":"2023-11-28T01:33:36.712598Z","shell.execute_reply":"2023-11-28T01:34:19.961718Z"},"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-11-28T01:34:19.964525Z"},"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        \n        outputs1 = model(images)\n        outputs2 = model2(images)\n        outputs = 0.5*outputs1+0.5*outputs2\n        outputs = model.softmax(outputs)\n        preds.append( outputs.detach().cpu().numpy() )\n\npreds = np.vstack(preds)\nprint(preds.shape)","metadata":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}