{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":20270,"databundleVersionId":1222630,"sourceType":"competition"},{"sourceId":9797223,"sourceType":"datasetVersion","datasetId":982170},{"sourceId":265636816,"sourceType":"kernelVersion"},{"sourceId":266639375,"sourceType":"kernelVersion"}],"dockerImageVersionId":31090,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys\nsys.path.append(\"../input/tez-lib/\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-08T18:58:09.906696Z","iopub.execute_input":"2025-10-08T18:58:09.907146Z","iopub.status.idle":"2025-10-08T18:58:09.915065Z","shell.execute_reply.started":"2025-10-08T18:58:09.907108Z","shell.execute_reply":"2025-10-08T18:58:09.914228Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn as nn\n\nfrom tez import Tez, TezConfig\nimport tez\nimport albumentations\nimport pandas as pd\nimport cv2\nimport numpy as np\nimport timm\nimport torch.nn as nn\nfrom sklearn import metrics\nimport torch\nfrom tez.callbacks import EarlyStopping\nfrom tez import Tez, TezConfig, Callback\nfrom tqdm import tqdm\n\nfrom sklearn.preprocessing import LabelEncoder\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T18:58:09.916457Z","iopub.execute_input":"2025-10-08T18:58:09.916708Z","iopub.status.idle":"2025-10-08T18:58:55.947972Z","shell.execute_reply.started":"2025-10-08T18:58:09.916689Z","shell.execute_reply":"2025-10-08T18:58:55.947130Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class args:\n    batch_size = 64#16\n    image_size = 384 #64","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T18:58:55.948850Z","iopub.execute_input":"2025-10-08T18:58:55.949347Z","iopub.status.idle":"2025-10-08T18:58:55.953787Z","shell.execute_reply.started":"2025-10-08T18:58:55.949320Z","shell.execute_reply":"2025-10-08T18:58:55.952949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def sigmoid(x):\n    return 1 / (1 + math.exp(-x))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T18:58:55.956029Z","iopub.execute_input":"2025-10-08T18:58:55.956256Z","iopub.status.idle":"2025-10-08T18:58:55.975155Z","shell.execute_reply.started":"2025-10-08T18:58:55.956232Z","shell.execute_reply":"2025-10-08T18:58:55.974380Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class MelanomaDataset:\n    def __init__(self, image_paths, dense_features, targets, augmentations):\n        self.image_paths = image_paths\n        self.dense_features = dense_features\n        self.targets = targets\n        self.augmentations = augmentations\n        \n    def __len__(self):\n        return len(self.image_paths)\n    \n    def __getitem__(self, item):\n        image = cv2.imread(self.image_paths[item])\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        \n        if self.augmentations is not None:\n            augmented = self.augmentations(image=image)\n            image = augmented[\"image\"]\n            \n        image = np.transpose(image, (2, 0, 1)).astype(np.float32)\n        \n        features = self.dense_features[item, :]\n        targets = self.targets[item]\n        \n        return {\n            \"image\": torch.tensor(image, dtype=torch.float),\n            \"features\": torch.tensor(features, dtype=torch.float),\n            \"targets\": torch.tensor(targets, dtype=torch.float),\n        }\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T18:58:55.975965Z","iopub.execute_input":"2025-10-08T18:58:55.976218Z","iopub.status.idle":"2025-10-08T18:58:55.989935Z","shell.execute_reply.started":"2025-10-08T18:58:55.976195Z","shell.execute_reply":"2025-10-08T18:58:55.989267Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class MelanomaModel(nn.Module):\n    def __init__(self):\n        super().__init__()        \n        self.model = timm.create_model(\"resnet50\", pretrained=False, in_chans=3)#resnet50#resnet101#eca_nfnet_l1#resnest101e\n\n        \n        self.dropout = nn.Dropout(0.5)# increase dropout\n        # self.out = nn.Linear(1280+12, 1)\n        self.out = nn.Linear(1000, 1)\n        # self.out_final = nn.Linear(512, 1)\n        \n        self.step_scheduler_after = \"epoch\"\n\n\n    def monitor_metrics(self, outputs, targets, loss):\n        valid_binaryloss = loss\n        if str(valid_binaryloss) == 'nan':\n            valid_binaryloss = float('inf')\n        return {\"binaryloss\": valid_binaryloss}\n\n    def optimizer_scheduler(self):\n        opt = torch.optim.AdamW(self.parameters(), lr=2.5e-05, weight_decay=0.01)\n        sch = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(\n            opt, T_0=10, T_mult=1, eta_min=1e-6, last_epoch=-1\n        )\n        return opt,sch\n\n    def forward(self, image, features, targets=None):\n\n        x = self.model(image)\n        x = self.dropout(x)\n        # x = torch.cat([x, features], dim=1)\n        # x = self.dropout(x)\n        x = self.out(x)\n        # x = self.dropout(x)\n        # x = self.out_final(x)\n\n        if targets is not None:\n            # loss = nn.MSELoss()(x, targets.view(-1, 1))\n            loss = nn.BCEWithLogitsLoss()(x, targets.view(-1, 1).type_as(x))\n            metrics = self.monitor_metrics(x, targets, loss)\n            return x, loss, metrics\n        return x, 0, {}\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T18:58:55.990547Z","iopub.execute_input":"2025-10-08T18:58:55.990718Z","iopub.status.idle":"2025-10-08T18:58:56.006116Z","shell.execute_reply.started":"2025-10-08T18:58:55.990703Z","shell.execute_reply":"2025-10-08T18:58:56.005545Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_aug = albumentations.Compose(\n    [\n        albumentations.Resize(args.image_size, args.image_size, p=1),\n        albumentations.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    ],\n    p=1.0,\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T18:58:56.006865Z","iopub.execute_input":"2025-10-08T18:58:56.007124Z","iopub.status.idle":"2025-10-08T18:58:56.024877Z","shell.execute_reply.started":"2025-10-08T18:58:56.007107Z","shell.execute_reply":"2025-10-08T18:58:56.024081Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nsuper_final_predictions = []\nfor i in range(1):\n    model = MelanomaModel()\n    model = Tez(model)\n    model.load(f\"/kaggle/input/training-suraj-kumar-23bcs10146-melanoma/model_f{i}.bin\", weights_only=True)\n    \n    df_test = pd.read_csv(\"/kaggle/input/siim-isic-melanoma-classification/test.csv\")\n    test_img_paths = [f\"/kaggle/input/siim-isic-melanoma-classification/jpeg/test/{x}.jpg\" for x in df_test[\"image_name\"].values]\n    dense_features = [\n        # 'sex', \n        # 'age_approx',\n        # 'anatom_site_general_challenge',\n        \n    ]\n    \n    test_dataset = MelanomaDataset(\n        image_paths=test_img_paths,\n        dense_features=df_test[dense_features].values,\n        targets=np.ones(len(test_img_paths)),\n        augmentations=test_aug,\n    )\n    test_predictions = model.predict(test_dataset, batch_size=2*args.batch_size, n_jobs=-1)\n    \n    final_test_predictions = []\n    for preds in tqdm(test_predictions):\n        final_test_predictions.extend(preds.ravel().tolist())\n    \n    # final_test_predictions = [sigmoid(x) * 100 for x in final_test_predictions]\n    super_final_predictions.append(final_test_predictions)\n\nsuper_final_predictions = np.mean(np.column_stack(super_final_predictions), axis=1)\ndf_test[\"target\"] = super_final_predictions\ndf_test = df_test[[\"image_name\", \"target\"]]\ndf_test.to_csv(\"submission.csv\", index=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T18:58:56.025691Z","iopub.execute_input":"2025-10-08T18:58:56.025996Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test.head()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}