{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"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"},"colab":{"machine_shape":"hm","gpuType":"T4"},"accelerator":"GPU","kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":20270,"databundleVersionId":1222630,"sourceType":"competition"},{"sourceId":9797223,"sourceType":"datasetVersion","datasetId":982170},{"sourceId":266165479,"sourceType":"kernelVersion"}],"dockerImageVersionId":31090,"isInternetEnabled":true,"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T17:38:26.746129Z","iopub.execute_input":"2025-10-08T17:38:26.746468Z","iopub.status.idle":"2025-10-08T17:38:26.750770Z","shell.execute_reply.started":"2025-10-08T17:38:26.746443Z","shell.execute_reply":"2025-10-08T17:38:26.749952Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import timm\n# from pprint import pprint\n# model_names = timm.list_models(pretrained=True)\n# pprint(model_names)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T17:38:26.752106Z","iopub.execute_input":"2025-10-08T17:38:26.752391Z","iopub.status.idle":"2025-10-08T17:38:26.765649Z","shell.execute_reply.started":"2025-10-08T17:38:26.752365Z","shell.execute_reply":"2025-10-08T17:38:26.764838Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import random\nimport numpy as np\nimport torch\nimport os\n\ndef seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    \nseed_everything(42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T17:38:26.766489Z","iopub.execute_input":"2025-10-08T17:38:26.766694Z","iopub.status.idle":"2025-10-08T17:38:26.781303Z","shell.execute_reply.started":"2025-10-08T17:38:26.766662Z","shell.execute_reply":"2025-10-08T17:38:26.780611Z"}},"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-08T17:38:26.782831Z","iopub.execute_input":"2025-10-08T17:38:26.783111Z","iopub.status.idle":"2025-10-08T17:38:26.796788Z","shell.execute_reply.started":"2025-10-08T17:38:26.783093Z","shell.execute_reply":"2025-10-08T17:38:26.796203Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class args:\n    batch_size = 8\n    image_size = 384\n    epochs = 1 #10\n    fold = 0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T17:38:26.797442Z","iopub.execute_input":"2025-10-08T17:38:26.797636Z","iopub.status.idle":"2025-10-08T17:38:26.809927Z","shell.execute_reply.started":"2025-10-08T17:38:26.797621Z","shell.execute_reply":"2025-10-08T17:38:26.809295Z"}},"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            \"features\": torch.tensor(features, dtype=torch.float),\n            \"targets\": torch.tensor(targets, dtype=torch.float),\n        }","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T17:38:26.810766Z","iopub.execute_input":"2025-10-08T17:38:26.810999Z","iopub.status.idle":"2025-10-08T17:38:26.824708Z","shell.execute_reply.started":"2025-10-08T17:38:26.810974Z","shell.execute_reply":"2025-10-08T17:38:26.824043Z"}},"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=True, 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-08T17:38:26.825415Z","iopub.execute_input":"2025-10-08T17:38:26.825735Z","iopub.status.idle":"2025-10-08T17:38:26.839143Z","shell.execute_reply.started":"2025-10-08T17:38:26.825709Z","shell.execute_reply":"2025-10-08T17:38:26.838511Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_aug = albumentations.Compose(\n    [\n        albumentations.LongestMaxSize(224, p=1),\n        albumentations.PadIfNeeded(224,224, p=1,border_mode=0),\n        albumentations.HorizontalFlip(p=0.5),\n        albumentations.VerticalFlip(p=0.1),\n        albumentations.Rotate(limit=180, p=0.5),\n        albumentations.ShiftScaleRotate(\n            shift_limit=0.1, scale_limit=0.1, rotate_limit=45, p=0.5\n        ),\n        albumentations.HueSaturationValue(\n            hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5\n        ),\n        albumentations.RandomBrightnessContrast(\n            brightness_limit=(-0.1, 0.1), contrast_limit=(-0.1, 0.1), p=0.5\n        ),\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)\nvalid_aug = albumentations.Compose(\n    [\n        albumentations.LongestMaxSize(224, p=1),\n        albumentations.PadIfNeeded(224,224, p=1,border_mode=0),\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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T17:38:26.865032Z","iopub.execute_input":"2025-10-08T17:38:26.865636Z","iopub.status.idle":"2025-10-08T17:38:26.877213Z","shell.execute_reply.started":"2025-10-08T17:38:26.865614Z","shell.execute_reply":"2025-10-08T17:38:26.876604Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/suraj-kumar-23bcs10146-creating-folds/train_5folds.csv\")\ndf.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T17:38:26.878521Z","iopub.execute_input":"2025-10-08T17:38:26.878789Z","iopub.status.idle":"2025-10-08T17:38:26.950741Z","shell.execute_reply.started":"2025-10-08T17:38:26.878765Z","shell.execute_reply":"2025-10-08T17:38:26.949973Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Encode all categorical features (skip image_name, patient_id, target)\nfor col in ['sex', 'anatom_site_general_challenge']:\n    le = LabelEncoder()\n    df[col] = le.fit_transform(df[col].astype(str))\n\ndf.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T17:38:26.951669Z","iopub.execute_input":"2025-10-08T17:38:26.951952Z","iopub.status.idle":"2025-10-08T17:38:26.974954Z","shell.execute_reply.started":"2025-10-08T17:38:26.951927Z","shell.execute_reply":"2025-10-08T17:38:26.974366Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(1):\n    print(f'training fold: {i} start')\n    args.fold = i\n    df_train = df[df.kfold != args.fold].reset_index(drop=True)\n    df_valid = df[df.kfold == args.fold].reset_index(drop=True)\n    dense_features = [\n        'sex', \n        'age_approx',\n        'anatom_site_general_challenge',\n        \n    ]\n    train_img_paths = [f\"/kaggle/input/siim-isic-melanoma-classification/jpeg/train/{x}.jpg\" for x in df_train[\"image_name\"].values]\n    valid_img_paths = [f\"/kaggle/input/siim-isic-melanoma-classification/jpeg/train/{x}.jpg\" for x in df_valid[\"image_name\"].values]\n    train_dataset = MelanomaDataset(\n        image_paths=train_img_paths,\n        dense_features=df_train[dense_features].values,\n        targets=df_train.target.values,\n        augmentations=train_aug,\n    )\n    \n    valid_dataset = MelanomaDataset(\n        image_paths=valid_img_paths,\n        dense_features=df_valid[dense_features].values,\n        targets=df_valid.target.values,\n        augmentations=valid_aug,\n    )\n    \n    model = MelanomaModel()\n    model = Tez(model)\n    config = TezConfig(\n        training_batch_size=args.batch_size,\n        validation_batch_size=2 * args.batch_size,\n        epochs=args.epochs,\n        step_scheduler_after=\"epoch\",\n        step_scheduler_metric=\"valid_binaryloss\",\n        fp16=True,\n        # fp16=False,\n        val_strategy=\"batch\",\n        val_steps=900,\n    )\n    \n    es = EarlyStopping(\n        monitor=\"valid_binaryloss\",\n        model_path=f\"model_f{args.fold}.bin\",\n        patience=4,#3,\n        mode=\"min\",\n        save_weights_only=True,\n    )\n    \n    model.fit(\n        train_dataset,\n        valid_dataset=valid_dataset,\n        callbacks=[es],\n        config=config,\n    )\n    print(f'training fold: {i} complete')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-08T17:38:26.975798Z","iopub.execute_input":"2025-10-08T17:38:26.975997Z","execution_failed":"2025-10-08T17:39:25.237Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}