{"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":267285441,"sourceType":"kernelVersion"}],"dockerImageVersionId":31153,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys\nsys.path.append(\"/kaggle/input/tez-lib\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:45:41.402977Z","iopub.execute_input":"2025-10-11T15:45:41.403314Z","iopub.status.idle":"2025-10-11T15:45:41.408300Z","shell.execute_reply.started":"2025-10-11T15:45:41.403291Z","shell.execute_reply":"2025-10-11T15:45:41.407210Z"}},"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-11T15:45:42.254572Z","iopub.execute_input":"2025-10-11T15:45:42.254906Z","iopub.status.idle":"2025-10-11T15:45:42.262426Z","shell.execute_reply.started":"2025-10-11T15:45:42.254882Z","shell.execute_reply":"2025-10-11T15:45:42.261448Z"}},"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 tqdm import tqdm\nfrom sklearn.preprocessing import LabelEncoder","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:45:43.248658Z","iopub.execute_input":"2025-10-11T15:45:43.248987Z","iopub.status.idle":"2025-10-11T15:45:58.113757Z","shell.execute_reply.started":"2025-10-11T15:45:43.248963Z","shell.execute_reply":"2025-10-11T15:45:58.112616Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class args:\n    batch_size = 8\n    image_size = 384\n    epochs = 1\n    fold = 0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:45:59.986611Z","iopub.execute_input":"2025-10-11T15:45:59.987257Z","iopub.status.idle":"2025-10-11T15:45:59.992658Z","shell.execute_reply.started":"2025-10-11T15:45:59.987208Z","shell.execute_reply":"2025-10-11T15:45:59.991620Z"}},"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-11T15:46:01.264658Z","iopub.execute_input":"2025-10-11T15:46:01.264980Z","iopub.status.idle":"2025-10-11T15:46:01.273314Z","shell.execute_reply.started":"2025-10-11T15:46:01.264958Z","shell.execute_reply":"2025-10-11T15:46:01.272116Z"}},"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, {}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:46:03.083994Z","iopub.execute_input":"2025-10-11T15:46:03.084915Z","iopub.status.idle":"2025-10-11T15:46:03.095755Z","shell.execute_reply.started":"2025-10-11T15:46:03.084878Z","shell.execute_reply":"2025-10-11T15:46:03.094614Z"}},"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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:42:33.552412Z","iopub.status.idle":"2025-10-11T15:42:33.552958Z","shell.execute_reply.started":"2025-10-11T15:42:33.552745Z","shell.execute_reply":"2025-10-11T15:42:33.552766Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/10095-venkateshalampally-siim-isic-k-folds/train_5folds.csv\")\ndf.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:42:33.553891Z","iopub.status.idle":"2025-10-11T15:42:33.554273Z","shell.execute_reply.started":"2025-10-11T15:42:33.554080Z","shell.execute_reply":"2025-10-11T15:42:33.554100Z"}},"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-11T15:42:33.555792Z","iopub.status.idle":"2025-10-11T15:42:33.556222Z","shell.execute_reply.started":"2025-10-11T15:42:33.556006Z","shell.execute_reply":"2025-10-11T15:42:33.556024Z"}},"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')","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}