{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":20270,"databundleVersionId":1222630,"sourceType":"competition"},{"sourceId":9797223,"sourceType":"datasetVersion","datasetId":982170},{"sourceId":267256261,"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        print(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-11T11:40:53.078505Z","iopub.execute_input":"2025-10-11T11:40:53.078848Z","iopub.status.idle":"2025-10-11T11:42:26.845930Z","shell.execute_reply.started":"2025-10-11T11:40:53.078825Z","shell.execute_reply":"2025-10-11T11:42:26.845107Z"}},"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-11T14:24:21.863895Z","iopub.execute_input":"2025-10-11T14:24:21.864108Z","iopub.status.idle":"2025-10-11T14:24:21.873431Z","shell.execute_reply.started":"2025-10-11T14:24:21.864087Z","shell.execute_reply":"2025-10-11T14:24:21.872575Z"}},"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-11T14:24:29.571940Z","iopub.execute_input":"2025-10-11T14:24:29.572438Z","iopub.status.idle":"2025-10-11T14:24:32.944606Z","shell.execute_reply.started":"2025-10-11T14:24:29.572416Z","shell.execute_reply":"2025-10-11T14:24:32.944041Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# !pip install tez","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T11:42:26.881144Z","iopub.execute_input":"2025-10-11T11:42:26.881352Z","iopub.status.idle":"2025-10-11T11:42:30.166716Z","shell.execute_reply.started":"2025-10-11T11:42:26.881333Z","shell.execute_reply":"2025-10-11T11:42:30.165985Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn as nn\n\nfrom tez import Tez, TezConfig\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\nnp.Inf = np.inf","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T14:24:38.731744Z","iopub.execute_input":"2025-10-11T14:24:38.732384Z","iopub.status.idle":"2025-10-11T14:24:48.401492Z","shell.execute_reply.started":"2025-10-11T14:24:38.732362Z","shell.execute_reply":"2025-10-11T14:24:48.400787Z"}},"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-11T11:42:30.174978Z","iopub.execute_input":"2025-10-11T11:42:30.175293Z","iopub.status.idle":"2025-10-11T11:42:30.193842Z","shell.execute_reply.started":"2025-10-11T11:42:30.175271Z","shell.execute_reply":"2025-10-11T11:42:30.193277Z"}},"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-11T11:42:30.194591Z","iopub.execute_input":"2025-10-11T11:42:30.194791Z","iopub.status.idle":"2025-10-11T11:42:30.211654Z","shell.execute_reply.started":"2025-10-11T11:42:30.194777Z","shell.execute_reply":"2025-10-11T11:42:30.211057Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# class PawpularModel(tez.Model):\nclass 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        # 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-11T11:42:30.212393Z","iopub.execute_input":"2025-10-11T11:42:30.212649Z","iopub.status.idle":"2025-10-11T11:42:30.236718Z","shell.execute_reply.started":"2025-10-11T11:42:30.212633Z","shell.execute_reply":"2025-10-11T11:42:30.236113Z"}},"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-11T11:42:30.237534Z","iopub.execute_input":"2025-10-11T11:42:30.237771Z","iopub.status.idle":"2025-10-11T11:42:30.266053Z","shell.execute_reply.started":"2025-10-11T11:42:30.237750Z","shell.execute_reply":"2025-10-11T11:42:30.265450Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/shrimay-somani-23bcs10117-kfold/train_5folds.csv\")\ndf.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T11:42:30.266812Z","iopub.execute_input":"2025-10-11T11:42:30.267055Z","iopub.status.idle":"2025-10-11T11:42:30.416061Z","shell.execute_reply.started":"2025-10-11T11:42:30.267035Z","shell.execute_reply":"2025-10-11T11:42:30.415306Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# pip install -U tez safetensors tqdm\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-11T11:42:30.416855Z","iopub.execute_input":"2025-10-11T11:42:30.417110Z","iopub.status.idle":"2025-10-11T11:42:34.755001Z","shell.execute_reply.started":"2025-10-11T11:42:30.417088Z","shell.execute_reply":"2025-10-11T11:42:34.754202Z"}},"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=False,\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-11T11:42:34.756115Z","iopub.execute_input":"2025-10-11T11:42:34.756353Z","iopub.status.idle":"2025-10-11T12:24:19.302117Z","shell.execute_reply.started":"2025-10-11T11:42:34.756320Z","shell.execute_reply":"2025-10-11T12:24:19.301483Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}