{"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,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":13329768,"sourceType":"datasetVersion","datasetId":8451043},{"sourceId":267187182,"sourceType":"kernelVersion"}],"dockerImageVersionId":31154,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        os.path.join(dirname, filename)\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-11T07:49:45.665860Z","iopub.execute_input":"2025-10-11T07:49:45.666102Z","iopub.status.idle":"2025-10-11T07:51:29.554322Z","shell.execute_reply.started":"2025-10-11T07:49:45.666084Z","shell.execute_reply":"2025-10-11T07:51:29.553665Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys\nsys.path.append(\"/kaggle/input/tez-lib\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T07:51:29.555546Z","iopub.execute_input":"2025-10-11T07:51:29.555893Z","iopub.status.idle":"2025-10-11T07:51:29.559615Z","shell.execute_reply.started":"2025-10-11T07:51:29.555868Z","shell.execute_reply":"2025-10-11T07:51:29.558867Z"}},"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-11T07:51:29.560374Z","iopub.execute_input":"2025-10-11T07:51:29.560605Z","iopub.status.idle":"2025-10-11T07:51:33.087187Z","shell.execute_reply.started":"2025-10-11T07:51:29.560585Z","shell.execute_reply":"2025-10-11T07:51:33.086609Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install tez","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T07:51:33.087900Z","iopub.execute_input":"2025-10-11T07:51:33.088206Z","iopub.status.idle":"2025-10-11T07:52:52.874009Z","shell.execute_reply.started":"2025-10-11T07:51:33.088188Z","shell.execute_reply":"2025-10-11T07:52:52.873266Z"}},"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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T07:52:52.876218Z","iopub.execute_input":"2025-10-11T07:52:52.876491Z","iopub.status.idle":"2025-10-11T07:53:01.819787Z","shell.execute_reply.started":"2025-10-11T07:52:52.876467Z","shell.execute_reply":"2025-10-11T07:53:01.818980Z"}},"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-11T07:53:01.820636Z","iopub.execute_input":"2025-10-11T07:53:01.821177Z","iopub.status.idle":"2025-10-11T07:53:01.824936Z","shell.execute_reply.started":"2025-10-11T07:53:01.821152Z","shell.execute_reply":"2025-10-11T07:53:01.824234Z"}},"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        }","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T07:53:01.825684Z","iopub.execute_input":"2025-10-11T07:53:01.825997Z","iopub.status.idle":"2025-10-11T07:53:01.849461Z","shell.execute_reply.started":"2025-10-11T07:53:01.825980Z","shell.execute_reply":"2025-10-11T07:53:01.848921Z"}},"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        # rmse = torch.sqrt(loss).cpu().detach().numpy()\n        rmse = loss\n        if str(rmse) == 'nan':\n            rmse = float('inf')\n        # return {\"rmse\": rmse}\n        return {\"rmse\": rmse}\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        \n        if targets is not None:\n\n            # loss = nn.BCEWithLogitsLoss()(x, targets.view(-1, 1).type_as(x))\n            loss = nn.MSELoss()(x, targets.view(-1, 1))\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-11T07:53:01.850276Z","iopub.execute_input":"2025-10-11T07:53:01.851042Z","iopub.status.idle":"2025-10-11T07:53:01.868383Z","shell.execute_reply.started":"2025-10-11T07:53:01.851017Z","shell.execute_reply":"2025-10-11T07:53:01.867665Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_aug = albumentations.Compose(\n    [\n#         albumentations.Resize(args.image_size, args.image_size, p=1),\n        albumentations.LongestMaxSize(args.image_size, p=1),\n        albumentations.PadIfNeeded(args.image_size,args.image_size, p=1,border_mode=0),\n        \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        \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)\n\nvalid_aug = albumentations.Compose(\n    [\n#         albumentations.Resize(args.image_size, args.image_size, p=1),\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(\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-11T07:53:01.869103Z","iopub.execute_input":"2025-10-11T07:53:01.869311Z","iopub.status.idle":"2025-10-11T07:53:01.890304Z","shell.execute_reply.started":"2025-10-11T07:53:01.869296Z","shell.execute_reply":"2025-10-11T07:53:01.889670Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/kfolds/train_5folds.csv\")\ndf.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T07:53:01.890958Z","iopub.execute_input":"2025-10-11T07:53:01.891184Z","iopub.status.idle":"2025-10-11T07:53:02.009660Z","shell.execute_reply.started":"2025-10-11T07:53:01.891165Z","shell.execute_reply":"2025-10-11T07:53:02.009033Z"}},"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)\ndense_features = [\n    \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]\ntrain_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\nvalid_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\nmodel = MelanomaModel()\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_rmse\",\n    fp16=True,\n    # fp16=False,\n    val_strategy=\"batch\",\n    val_steps=900,\n)\n\nes = EarlyStopping(\n    monitor=\"valid_rmse\",\n    model_path=f\"model_f{args.fold}.bin\",\n    patience=4,#3,\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)\nprint(f'training fold: {i} complete')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T07:53:02.010264Z","iopub.execute_input":"2025-10-11T07:53:02.010446Z","execution_failed":"2025-10-11T07:53:10.005Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}