{"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":267296642,"sourceType":"kernelVersion"}],"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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:16:36.456929Z","iopub.execute_input":"2025-10-11T15:16:36.457153Z","iopub.status.idle":"2025-10-11T15:16:36.475116Z","shell.execute_reply.started":"2025-10-11T15:16:36.457133Z","shell.execute_reply":"2025-10-11T15:16:36.471328Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import random\nimport numpy as np\nimport torch\nimport os\nimport torch.nn as nn\nimport timm\nimport albumentations\nimport pandas as pd\nimport cv2\nfrom tez import Tez, TezConfig\nfrom tez.callbacks import EarlyStopping","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:16:36.476319Z","iopub.execute_input":"2025-10-11T15:16:36.476583Z","iopub.status.idle":"2025-10-11T15:16:49.309262Z","shell.execute_reply.started":"2025-10-11T15:16:36.476561Z","shell.execute_reply":"2025-10-11T15:16:49.308691Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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:16:49.309930Z","iopub.execute_input":"2025-10-11T15:16:49.310300Z","iopub.status.idle":"2025-10-11T15:16:49.319069Z","shell.execute_reply.started":"2025-10-11T15:16:49.310283Z","shell.execute_reply":"2025-10-11T15:16:49.318414Z"}},"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:16:49.319850Z","iopub.execute_input":"2025-10-11T15:16:49.320679Z","iopub.status.idle":"2025-10-11T15:16:49.333759Z","shell.execute_reply.started":"2025-10-11T15:16:49.320655Z","shell.execute_reply":"2025-10-11T15:16:49.333116Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CustomDataset:\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        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        }","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:16:49.335279Z","iopub.execute_input":"2025-10-11T15:16:49.335563Z","iopub.status.idle":"2025-10-11T15:16:49.349832Z","shell.execute_reply.started":"2025-10-11T15:16:49.335547Z","shell.execute_reply":"2025-10-11T15:16:49.349118Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CustomModel(nn.Module):\n    def __init__(self):\n        super().__init__()        \n        self.model = timm.create_model(\"resnet50\", pretrained=True, in_chans=3)\n        self.dropout = nn.Dropout(0.5)\n        self.out = nn.Linear(1000, 1)\n\n    def monitor_metrics(self, outputs, targets, loss):\n        # Return tensor, not float\n        valid_binaryloss = loss.detach()\n        if torch.isnan(valid_binaryloss):\n            valid_binaryloss = torch.tensor(float('inf')).to(loss.device)\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\n        )\n        return opt, sch\n\n    def forward(self, image, features, targets=None):\n        x = self.model(image)\n        x = self.dropout(x)\n        x = self.out(x)\n\n        if targets is not None:\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, torch.tensor(0.0).to(x.device), {}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:16:49.366805Z","iopub.execute_input":"2025-10-11T15:16:49.367158Z","iopub.status.idle":"2025-10-11T15:16:49.386534Z","shell.execute_reply.started":"2025-10-11T15:16:49.367135Z","shell.execute_reply":"2025-10-11T15:16:49.385764Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_aug = albumentations.Compose(\n    [\n        albumentations.LongestMaxSize(args.image_size, p=1),\n        albumentations.PadIfNeeded(args.image_size, args.image_size, 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(shift_limit=0.1, scale_limit=0.1, rotate_limit=45, p=0.5),\n        albumentations.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),\n        albumentations.RandomBrightnessContrast(brightness_limit=(-0.1, 0.1), contrast_limit=(-0.1, 0.1), p=0.5),\n        albumentations.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n    ],\n    p=1.0,\n)\n\nvalid_aug = albumentations.Compose(\n    [\n        albumentations.LongestMaxSize(args.image_size, p=1),\n        albumentations.PadIfNeeded(args.image_size, args.image_size, p=1, border_mode=0),\n        albumentations.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n    ],\n    p=1.0,\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:16:49.387276Z","iopub.execute_input":"2025-10-11T15:16:49.387568Z","iopub.status.idle":"2025-10-11T15:16:49.409679Z","shell.execute_reply.started":"2025-10-11T15:16:49.387552Z","shell.execute_reply":"2025-10-11T15:16:49.408981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/10121-yash-agarwal-kfold-siim/train_5folds.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:16:49.410250Z","iopub.execute_input":"2025-10-11T15:16:49.410481Z","iopub.status.idle":"2025-10-11T15:16:49.504481Z","shell.execute_reply.started":"2025-10-11T15:16:49.410465Z","shell.execute_reply":"2025-10-11T15:16:49.503919Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dense_features = ['age_approx']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:16:49.505301Z","iopub.execute_input":"2025-10-11T15:16:49.505534Z","iopub.status.idle":"2025-10-11T15:16:49.509007Z","shell.execute_reply.started":"2025-10-11T15:16:49.505518Z","shell.execute_reply":"2025-10-11T15:16:49.508306Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"i = 0\nprint(f'Training fold: {i} start')\nargs.fold = 0\ndf_train = df[df.kfold != args.fold].reset_index(drop=True)\ndf_valid = df[df.kfold == args.fold].reset_index(drop=True)\n\ntrain_img_paths = [f\"/kaggle/input/siim-isic-melanoma-classification/jpeg/train/{x}.jpg\" for x in df_train[\"image_name\"].values]\nvalid_img_paths = [f\"/kaggle/input/siim-isic-melanoma-classification/jpeg/train/{x}.jpg\" for x in df_valid[\"image_name\"].values]\n\ntrain_dataset = CustomDataset(\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\nvalid_dataset = CustomDataset(\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\nmodel = CustomModel()\nmodel = Tez(model)\nconfig = 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    val_strategy=\"batch\",\n    val_steps=900,\n)\n\nes = EarlyStopping(\n    monitor=\"valid_binaryloss\",\n    model_path=f\"model_f{args.fold}.bin\",\n    patience=4,\n    mode=\"min\",\n    save_weights_only=True,\n)\n\nmodel.fit(\n    train_dataset,\n    valid_dataset=valid_dataset,\n    callbacks=[es],\n    config=config,\n)\n\nprint(f'Training fold: {i} complete')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T15:19:02.430107Z","iopub.execute_input":"2025-10-11T15:19:02.430814Z","execution_failed":"2025-10-11T15:20:35.120Z"}},"outputs":[],"execution_count":null}]}