{"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":6746686,"sourceType":"datasetVersion","datasetId":3884593},{"sourceId":6827935,"sourceType":"datasetVersion","datasetId":3926155},{"sourceId":6874344,"sourceType":"datasetVersion","datasetId":3950227},{"sourceId":147635265,"sourceType":"kernelVersion"}],"dockerImageVersionId":30559,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"**Code copy and edit from \n\n\n**https://www.kaggle.com/code/khailashsanthakumar/ubc-pytorch-effb0-with-classweights-inference\n\n**https://www.kaggle.com/code/motono0223/ubc-infer-efficientnetb0-crop-resize-2048pix\n\n**https://www.kaggle.com/code/yinankaggle/ensemble-inference-resnet50\n\n\nPlease upvote if it helps you.","metadata":{}},{"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-11-15T18:01:10.725514Z","iopub.execute_input":"2023-11-15T18:01:10.726181Z","iopub.status.idle":"2023-11-15T18:01:17.09562Z","shell.execute_reply.started":"2023-11-15T18:01:10.726148Z","shell.execute_reply":"2023-11-15T18:01:17.094774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CONFIG = {\n    \"seed\": 42,\n    \"img_size\": 2048,\n    \"model_name\": \"tf_efficientnetv2_s_in21ft1k\",\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-15T18:01:17.097482Z","iopub.execute_input":"2023-11-15T18:01:17.09801Z","iopub.status.idle":"2023-11-15T18:01:17.125318Z","shell.execute_reply.started":"2023-11-15T18:01:17.097976Z","shell.execute_reply":"2023-11-15T18:01:17.124445Z"},"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-15T18:01:17.126327Z","iopub.execute_input":"2023-11-15T18:01:17.126598Z","iopub.status.idle":"2023-11-15T18:01:17.148304Z","shell.execute_reply.started":"2023-11-15T18:01:17.126574Z","shell.execute_reply":"2023-11-15T18:01:17.147514Z"},"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/ubcpytorchwith-classweights-training-fold1of5/label_encoder.pkl\"\nBEST_WEIGHT = \"/kaggle/input/baseline-0-36/Acc0.70_Loss1.0140_epoch29_tf_efficientnetv2_s_in21ft1k_0.36.bin\"\nBEST_WEIGHT2 = \"/kaggle/input/ubc-efficienetnetb0-fold1of10-2048pix-thumbnails/Recall0.9178_Acc0.9437_Loss0.1685_epoch9.bin\"\nBEST_WEIGHT3 = \"/kaggle/input/ubc-efficienetnetb0-fold1of10-2048pix-thumbnails/Recall0.8858_Acc0.9155_Loss0.2106_epoch1.bin\"\nBEST_WEIGHT4 = \"/kaggle/input/ver-21-10/Acc0.50_Loss1.2095_epoch4.bin\"","metadata":{"execution":{"iopub.status.busy":"2023-11-15T18:01:22.001283Z","iopub.execute_input":"2023-11-15T18:01:22.001664Z","iopub.status.idle":"2023-11-15T18:01:22.007148Z","shell.execute_reply.started":"2023-11-15T18:01:22.001635Z","shell.execute_reply":"2023-11-15T18:01:22.006042Z"},"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-15T18:01:23.199097Z","iopub.execute_input":"2023-11-15T18:01:23.199724Z","iopub.status.idle":"2023-11-15T18:01:23.204364Z","shell.execute_reply.started":"2023-11-15T18:01:23.199691Z","shell.execute_reply":"2023-11-15T18:01:23.20334Z"},"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-11-15T18:01:23.631553Z","iopub.execute_input":"2023-11-15T18:01:23.631914Z","iopub.status.idle":"2023-11-15T18:01:23.663664Z","shell.execute_reply.started":"2023-11-15T18:01:23.631883Z","shell.execute_reply":"2023-11-15T18:01:23.662911Z"},"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-15T18:01:24.150594Z","iopub.execute_input":"2023-11-15T18:01:24.150927Z","iopub.status.idle":"2023-11-15T18:01:24.164451Z","shell.execute_reply.started":"2023-11-15T18:01:24.150903Z","shell.execute_reply":"2023-11-15T18:01:24.163577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder = joblib.load( LABEL_ENCODER_BIN )","metadata":{"execution":{"iopub.status.busy":"2023-11-15T18:01:24.664291Z","iopub.execute_input":"2023-11-15T18:01:24.66511Z","iopub.status.idle":"2023-11-15T18:01:24.67512Z","shell.execute_reply.started":"2023-11-15T18:01:24.665079Z","shell.execute_reply":"2023-11-15T18:01:24.6743Z"},"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-15T18:01:25.50651Z","iopub.execute_input":"2023-11-15T18:01:25.507197Z","iopub.status.idle":"2023-11-15T18:01:25.520185Z","shell.execute_reply.started":"2023-11-15T18:01:25.507169Z","shell.execute_reply":"2023-11-15T18:01:25.519283Z"},"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-15T18:01:26.137545Z","iopub.execute_input":"2023-11-15T18:01:26.137884Z","iopub.status.idle":"2023-11-15T18:01:26.699213Z","shell.execute_reply.started":"2023-11-15T18:01:26.137859Z","shell.execute_reply":"2023-11-15T18:01:26.698273Z"},"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-15T18:01:26.700835Z","iopub.execute_input":"2023-11-15T18:01:26.70114Z","iopub.status.idle":"2023-11-15T18:01:26.717287Z","shell.execute_reply.started":"2023-11-15T18:01:26.701115Z","shell.execute_reply":"2023-11-15T18:01:26.716405Z"},"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-15T18:01:29.345619Z","iopub.execute_input":"2023-11-15T18:01:29.34623Z","iopub.status.idle":"2023-11-15T18:01:29.355409Z","shell.execute_reply.started":"2023-11-15T18:01:29.346196Z","shell.execute_reply":"2023-11-15T18:01:29.354547Z"},"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-15T18:01:30.870089Z","iopub.execute_input":"2023-11-15T18:01:30.870451Z","iopub.status.idle":"2023-11-15T18:01:30.876504Z","shell.execute_reply.started":"2023-11-15T18:01:30.870421Z","shell.execute_reply":"2023-11-15T18:01:30.875459Z"},"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-15T18:01:33.838062Z","iopub.execute_input":"2023-11-15T18:01:33.838686Z","iopub.status.idle":"2023-11-15T18:01:33.84655Z","shell.execute_reply.started":"2023-11-15T18:01:33.838655Z","shell.execute_reply":"2023-11-15T18:01:33.845586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class 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('tf_efficientnetv2_s_in21ft1k', CONFIG['num_classes'])\nmodel2 = UBCModel('tf_efficientnet_b0_ns', CONFIG['num_classes'])\nmodel3 = UBCModel('tf_efficientnet_b0_ns', CONFIG['num_classes'])\nmodel4 = UBCModel('tf_efficientnetv2_l', 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']);\nmodel3.load_state_dict(torch.load( BEST_WEIGHT3 ))\nmodel3.to(CONFIG['device']);\nmodel4.load_state_dict(torch.load( BEST_WEIGHT4 ))\nmodel4.to(CONFIG['device'])","metadata":{"execution":{"iopub.status.busy":"2023-11-15T18:02:46.688003Z","iopub.execute_input":"2023-11-15T18:02:46.688388Z","iopub.status.idle":"2023-11-15T18:03:00.228048Z","shell.execute_reply.started":"2023-11-15T18:02:46.688357Z","shell.execute_reply":"2023-11-15T18:03:00.22714Z"},"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-15T18:03:00.229503Z","iopub.execute_input":"2023-11-15T18:03:00.229781Z","iopub.status.idle":"2023-11-15T18:03:00.235379Z","shell.execute_reply.started":"2023-11-15T18:03:00.229757Z","shell.execute_reply":"2023-11-15T18:03:00.234333Z"},"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        outputs3 = model3(images)\n        outputs4 = model4(images)\n        outputs = 0.65*(0.35*outputs3+0.65*outputs2)+0.35*(0.55*outputs1+0.45*outputs4)\n        outputs = model.softmax(outputs)\n        preds.append( outputs.detach().cpu().numpy() )\n\npreds = np.vstack(preds)\nprint(preds.shape)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T18:04:32.510654Z","iopub.execute_input":"2023-11-15T18:04:32.511009Z","iopub.status.idle":"2023-11-15T18:04:38.670466Z","shell.execute_reply.started":"2023-11-15T18:04:32.510979Z","shell.execute_reply":"2023-11-15T18:04:38.669285Z"},"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-11-15T18:04:40.137455Z","iopub.execute_input":"2023-11-15T18:04:40.137821Z","iopub.status.idle":"2023-11-15T18:04:40.153881Z","shell.execute_reply.started":"2023-11-15T18:04:40.137792Z","shell.execute_reply":"2023-11-15T18:04:40.152956Z"},"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-11-15T18:04:41.207202Z","iopub.execute_input":"2023-11-15T18:04:41.207592Z","iopub.status.idle":"2023-11-15T18:04:41.216922Z","shell.execute_reply.started":"2023-11-15T18:04:41.207563Z","shell.execute_reply":"2023-11-15T18:04:41.216022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub","metadata":{"execution":{"iopub.status.busy":"2023-11-15T18:04:42.145306Z","iopub.execute_input":"2023-11-15T18:04:42.146192Z","iopub.status.idle":"2023-11-15T18:04:42.155613Z","shell.execute_reply.started":"2023-11-15T18:04:42.146158Z","shell.execute_reply":"2023-11-15T18:04:42.154637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}