{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":19991,"databundleVersionId":1117522,"sourceType":"competition"},{"sourceId":1205039,"sourceType":"datasetVersion","datasetId":685665},{"sourceId":11435727,"sourceType":"datasetVersion","datasetId":7162928}],"dockerImageVersionId":29928,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Alaska2 Baseline PyTorch","metadata":{}},{"cell_type":"markdown","source":"# Main Ideas\n\n- 4 Classes\n- GroupKFold splitting\n- Class Balance\n- Flips\n- Label Smoothing\n- EfficientNetB2\n- ReduceLROnPlateau","metadata":{}},{"cell_type":"markdown","source":"# Dependencies","metadata":{}},{"cell_type":"code","source":"!pip install -q efficientnet_pytorch > /dev/null","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:25.075467Z","iopub.execute_input":"2025-04-16T13:15:25.075799Z","iopub.status.idle":"2025-04-16T13:15:32.932974Z","shell.execute_reply.started":"2025-04-16T13:15:25.075764Z","shell.execute_reply":"2025-04-16T13:15:32.932082Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from glob import glob\nfrom sklearn.model_selection import GroupKFold\nimport cv2\nfrom skimage import io\nimport torch\nfrom torch import nn\nimport os\nfrom datetime import datetime\nimport time\nimport random\nimport cv2\nimport pandas as pd\nimport numpy as np\nimport albumentations as A\nimport matplotlib.pyplot as plt\nfrom albumentations.pytorch.transforms import ToTensorV2\nfrom torch.utils.data import Dataset,DataLoader\nfrom torch.utils.data.sampler import SequentialSampler, RandomSampler\nimport sklearn\n\nSEED = 42\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    torch.backends.cudnn.benchmark = True\n\nseed_everything(SEED)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:32.936085Z","iopub.execute_input":"2025-04-16T13:15:32.936458Z","iopub.status.idle":"2025-04-16T13:15:35.956206Z","shell.execute_reply.started":"2025-04-16T13:15:32.936412Z","shell.execute_reply":"2025-04-16T13:15:35.955554Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# GroupKFold splitting\n\nI think group splitting by image_name is really important for correct validation in this competition ;) ","metadata":{}},{"cell_type":"code","source":"%%time\n\ndataset = []\n\nfor label, kind in enumerate(['Cover', 'JMiPOD', 'JUNIWARD', 'UERD']):\n    for path in glob('../input/alaska2-image-steganalysis/Cover/*.jpg'):\n        dataset.append({\n            'kind': kind,\n            'image_name': path.split('/')[-1],\n            'label': label\n        })\n\nrandom.shuffle(dataset)\ndataset = pd.DataFrame(dataset)\n\ngkf = GroupKFold(n_splits=5)\n\ndataset.loc[:, 'fold'] = 0\nfor fold_number, (train_index, val_index) in enumerate(gkf.split(X=dataset.index, y=dataset['label'], groups=dataset['image_name'])):\n    dataset.loc[dataset.iloc[val_index].index, 'fold'] = fold_number","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:35.958475Z","iopub.execute_input":"2025-04-16T13:15:35.958842Z","iopub.status.idle":"2025-04-16T13:15:44.956885Z","shell.execute_reply.started":"2025-04-16T13:15:35.958802Z","shell.execute_reply":"2025-04-16T13:15:44.955967Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"In any case original dataframe with splitting:","metadata":{}},{"cell_type":"code","source":"# dataset = pd.read_csv('../input/alaska2-public-baseline/groupkfold_by_shonenkov.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:44.958255Z","iopub.execute_input":"2025-04-16T13:15:44.958603Z","iopub.status.idle":"2025-04-16T13:15:44.962553Z","shell.execute_reply.started":"2025-04-16T13:15:44.958565Z","shell.execute_reply":"2025-04-16T13:15:44.961706Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Simple Augs: Flips","metadata":{}},{"cell_type":"code","source":"def get_train_transforms():\n    return A.Compose([\n            A.HorizontalFlip(p=0.5),\n            A.VerticalFlip(p=0.5),\n            A.Resize(height=512, width=512, p=1.0),\n            ToTensorV2(p=1.0),\n        ], p=1.0)\n\ndef get_valid_transforms():\n    return A.Compose([\n            A.Resize(height=512, width=512, p=1.0),\n            ToTensorV2(p=1.0),\n        ], p=1.0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:44.963949Z","iopub.execute_input":"2025-04-16T13:15:44.964193Z","iopub.status.idle":"2025-04-16T13:15:44.973485Z","shell.execute_reply.started":"2025-04-16T13:15:44.964168Z","shell.execute_reply":"2025-04-16T13:15:44.972791Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Dataset","metadata":{}},{"cell_type":"code","source":"DATA_ROOT_PATH = '../input/alaska2-image-steganalysis'\n\ndef onehot(size, target):\n    vec = torch.zeros(size, dtype=torch.float32)\n    vec[target] = 1.\n    return vec\n\nclass DatasetRetriever(Dataset):\n\n    def __init__(self, kinds, image_names, labels, transforms=None):\n        super().__init__()\n        self.kinds = kinds\n        self.image_names = image_names\n        self.labels = labels\n        self.transforms = transforms\n\n    def __getitem__(self, index: int):\n        kind, image_name, label = self.kinds[index], self.image_names[index], self.labels[index]\n        image = cv2.imread(f'{DATA_ROOT_PATH}/{kind}/{image_name}', cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n        if self.transforms:\n            sample = {'image': image}\n            sample = self.transforms(**sample)\n            image = sample['image']\n            \n        target = onehot(4, label)\n        return image, target\n\n    def __len__(self) -> int:\n        return self.image_names.shape[0]\n\n    def get_labels(self):\n        return list(self.labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:44.974474Z","iopub.execute_input":"2025-04-16T13:15:44.974715Z","iopub.status.idle":"2025-04-16T13:15:44.983755Z","shell.execute_reply.started":"2025-04-16T13:15:44.974676Z","shell.execute_reply":"2025-04-16T13:15:44.983078Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fold_number = 0\n\ntrain_dataset = DatasetRetriever(\n    kinds=dataset[dataset['fold'] != fold_number].kind.values,\n    image_names=dataset[dataset['fold'] != fold_number].image_name.values,\n    labels=dataset[dataset['fold'] != fold_number].label.values,\n    transforms=get_train_transforms(),\n)\n\nvalidation_dataset = DatasetRetriever(\n    kinds=dataset[dataset['fold'] == fold_number].kind.values,\n    image_names=dataset[dataset['fold'] == fold_number].image_name.values,\n    labels=dataset[dataset['fold'] == fold_number].label.values,\n    transforms=get_valid_transforms(),\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:44.984996Z","iopub.execute_input":"2025-04-16T13:15:44.985231Z","iopub.status.idle":"2025-04-16T13:15:45.052279Z","shell.execute_reply.started":"2025-04-16T13:15:44.985208Z","shell.execute_reply":"2025-04-16T13:15:45.051353Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image, target = train_dataset[0]\nnumpy_image = image.permute(1,2,0).cpu().numpy()\n\nfig, ax = plt.subplots(1, 1, figsize=(16, 8))\n    \nax.set_axis_off()\nax.imshow(numpy_image);","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:45.053430Z","iopub.execute_input":"2025-04-16T13:15:45.053657Z","iopub.status.idle":"2025-04-16T13:15:45.397274Z","shell.execute_reply.started":"2025-04-16T13:15:45.053634Z","shell.execute_reply":"2025-04-16T13:15:45.396514Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Metrics","metadata":{}},{"cell_type":"code","source":"from sklearn import metrics\n\nclass AverageMeter(object):\n    \"\"\"Computes and stores the average and current value\"\"\"\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.val = 0\n        self.avg = 0\n        self.sum = 0\n        self.count = 0\n\n    def update(self, val, n=1):\n        self.val = val\n        self.sum += val * n\n        self.count += n\n        self.avg = self.sum / self.count\n        \n        \ndef alaska_weighted_auc(y_true, y_valid):\n    \"\"\"\n    https://www.kaggle.com/anokas/weighted-auc-metric-updated\n    \"\"\"\n    tpr_thresholds = [0.0, 0.4, 1.0]\n    weights = [2, 1]\n\n    fpr, tpr, thresholds = metrics.roc_curve(y_true, y_valid, pos_label=1)\n\n    # size of subsets\n    areas = np.array(tpr_thresholds[1:]) - np.array(tpr_thresholds[:-1])\n\n    # The total area is normalized by the sum of weights such that the final weighted AUC is between 0 and 1.\n    normalization = np.dot(areas, weights)\n\n    competition_metric = 0\n    for idx, weight in enumerate(weights):\n        y_min = tpr_thresholds[idx]\n        y_max = tpr_thresholds[idx + 1]\n        mask = (y_min < tpr) & (tpr < y_max)\n        # pdb.set_trace()\n\n        x_padding = np.linspace(fpr[mask][-1], 1, 100)\n\n        x = np.concatenate([fpr[mask], x_padding])\n        y = np.concatenate([tpr[mask], [y_max] * len(x_padding)])\n        y = y - y_min  # normalize such that curve starts at y=0\n        score = metrics.auc(x, y)\n        submetric = score * weight\n        best_subscore = (y_max - y_min) * weight\n        competition_metric += submetric\n\n    return competition_metric / normalization\n        \nclass RocAucMeter(object):\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.y_true = np.array([0,1])\n        self.y_pred = np.array([0.5,0.5])\n        self.score = 0\n\n    def update(self, y_true, y_pred):\n        y_true = y_true.cpu().numpy().argmax(axis=1).clip(min=0, max=1).astype(int)\n        y_pred = 1 - nn.functional.softmax(y_pred, dim=1).data.cpu().numpy()[:,0]\n        self.y_true = np.hstack((self.y_true, y_true))\n        self.y_pred = np.hstack((self.y_pred, y_pred))\n        self.score = alaska_weighted_auc(self.y_true, self.y_pred)\n    \n    @property\n    def avg(self):\n        return self.score","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:45.398770Z","iopub.execute_input":"2025-04-16T13:15:45.399072Z","iopub.status.idle":"2025-04-16T13:15:45.413794Z","shell.execute_reply.started":"2025-04-16T13:15:45.399046Z","shell.execute_reply":"2025-04-16T13:15:45.413027Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Label Smoothing","metadata":{}},{"cell_type":"code","source":"class LabelSmoothing(nn.Module):\n    def __init__(self, smoothing = 0.05):\n        super(LabelSmoothing, self).__init__()\n        self.confidence = 1.0 - smoothing\n        self.smoothing = smoothing\n\n    def forward(self, x, target):\n        if self.training:\n            x = x.float()\n            target = target.float()\n            logprobs = torch.nn.functional.log_softmax(x, dim = -1)\n\n            nll_loss = -logprobs * target\n            nll_loss = nll_loss.sum(-1)\n    \n            smooth_loss = -logprobs.mean(dim=-1)\n\n            loss = self.confidence * nll_loss + self.smoothing * smooth_loss\n\n            return loss.mean()\n        else:\n            return torch.nn.functional.cross_entropy(x, target)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:45.415180Z","iopub.execute_input":"2025-04-16T13:15:45.415518Z","iopub.status.idle":"2025-04-16T13:15:45.425878Z","shell.execute_reply.started":"2025-04-16T13:15:45.415475Z","shell.execute_reply":"2025-04-16T13:15:45.424988Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Fitter","metadata":{}},{"cell_type":"code","source":"import warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nclass Fitter:\n    \n    def __init__(self, model, device, config):\n        self.config = config\n        self.epoch = 0\n        \n        self.base_dir = './'\n        self.log_path = f'{self.base_dir}/log.txt'\n        self.best_summary_loss = 10**5\n\n        self.model = model\n        self.device = device\n\n        param_optimizer = list(self.model.named_parameters())\n        no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n        optimizer_grouped_parameters = [\n            {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.001},\n            {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n        ] \n\n        self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=config.lr)\n        self.scheduler = config.SchedulerClass(self.optimizer, **config.scheduler_params)\n        self.criterion = LabelSmoothing().to(self.device)\n        self.log(f'Fitter prepared. Device is {self.device}')\n\n    def fit(self, train_loader, validation_loader):\n        for e in range(self.config.n_epochs):\n            if self.config.verbose:\n                lr = self.optimizer.param_groups[0]['lr']\n                timestamp = datetime.utcnow().isoformat()\n                self.log(f'\\n{timestamp}\\nLR: {lr}')\n\n            t = time.time()\n            summary_loss, final_scores = self.train_one_epoch(train_loader)\n\n            self.log(f'[RESULT]: Train. Epoch: {self.epoch}, summary_loss: {summary_loss.avg:.5f}, final_score: {final_scores.avg:.5f}, time: {(time.time() - t):.5f}')\n            self.save(f'{self.base_dir}/last-checkpoint.bin')\n\n            t = time.time()\n            summary_loss, final_scores = self.validation(validation_loader)\n\n            self.log(f'[RESULT]: Val. Epoch: {self.epoch}, summary_loss: {summary_loss.avg:.5f}, final_score: {final_scores.avg:.5f}, time: {(time.time() - t):.5f}')\n            if summary_loss.avg < self.best_summary_loss:\n                self.best_summary_loss = summary_loss.avg\n                self.model.eval()\n                self.save(f'{self.base_dir}/best-checkpoint-{str(self.epoch).zfill(3)}epoch.bin')\n                for path in sorted(glob(f'{self.base_dir}/best-checkpoint-*epoch.bin'))[:-3]:\n                    os.remove(path)\n\n            if self.config.validation_scheduler:\n                self.scheduler.step(metrics=summary_loss.avg)\n\n            self.epoch += 1\n\n    def validation(self, val_loader):\n        self.model.eval()\n        summary_loss = AverageMeter()\n        final_scores = RocAucMeter()\n        t = time.time()\n        for step, (images, targets) in enumerate(val_loader):\n            if self.config.verbose:\n                if step % self.config.verbose_step == 0:\n                    print(\n                        f'Val Step {step}/{len(val_loader)}, ' + \\\n                        f'summary_loss: {summary_loss.avg:.5f}, final_score: {final_scores.avg:.5f}, ' + \\\n                        f'time: {(time.time() - t):.5f}', end='\\r'\n                    )\n            with torch.no_grad():\n                targets = targets.to(self.device).float()\n                batch_size = images.shape[0]\n                images = images.to(self.device).float()\n                outputs = self.model(images)\n                loss = self.criterion(outputs, targets)\n                final_scores.update(targets, outputs)\n                summary_loss.update(loss.detach().item(), batch_size)\n\n        return summary_loss, final_scores\n\n    def train_one_epoch(self, train_loader):\n        self.model.train()\n        summary_loss = AverageMeter()\n        final_scores = RocAucMeter()\n        t = time.time()\n        for step, (images, targets) in enumerate(train_loader):\n            if self.config.verbose:\n                if step % self.config.verbose_step == 0:\n                    print(\n                        f'Train Step {step}/{len(train_loader)}, ' + \\\n                        f'summary_loss: {summary_loss.avg:.5f}, final_score: {final_scores.avg:.5f}, ' + \\\n                        f'time: {(time.time() - t):.5f}', end='\\r'\n                    )\n            \n            targets = targets.to(self.device).float()\n            images = images.to(self.device).float()\n            batch_size = images.shape[0]\n\n            self.optimizer.zero_grad()\n            outputs = self.model(images)\n            loss = self.criterion(outputs, targets)\n            loss.backward()\n            \n            final_scores.update(targets, outputs)\n            summary_loss.update(loss.detach().item(), batch_size)\n\n            self.optimizer.step()\n\n            if self.config.step_scheduler:\n                self.scheduler.step()\n\n        return summary_loss, final_scores\n    \n    def save(self, path):\n        self.model.eval()\n        torch.save({\n            'model_state_dict': self.model.state_dict(),\n            'optimizer_state_dict': self.optimizer.state_dict(),\n            'scheduler_state_dict': self.scheduler.state_dict(),\n            'best_summary_loss': self.best_summary_loss,\n            'epoch': self.epoch,\n        }, path)\n\n    def load(self, path):\n        checkpoint = torch.load(path)\n        self.model.load_state_dict(checkpoint['model_state_dict'])\n        self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n        self.scheduler.load_state_dict(checkpoint['scheduler_state_dict'])\n        self.best_summary_loss = checkpoint['best_summary_loss']\n        self.epoch = checkpoint['epoch'] + 1\n        \n    def log(self, message):\n        if self.config.verbose:\n            print(message)\n        with open(self.log_path, 'a+') as logger:\n            logger.write(f'{message}\\n')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:45.427094Z","iopub.execute_input":"2025-04-16T13:15:45.427406Z","iopub.status.idle":"2025-04-16T13:15:45.453941Z","shell.execute_reply.started":"2025-04-16T13:15:45.427380Z","shell.execute_reply":"2025-04-16T13:15:45.453186Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# EfficientNet","metadata":{}},{"cell_type":"code","source":"from efficientnet_pytorch import EfficientNet\n\ndef get_net():\n    net = EfficientNet.from_pretrained('efficientnet-b2')\n    net._fc = nn.Linear(in_features=1408, out_features=4, bias=True)\n    return net\n\nnet = get_net().cuda()","metadata":{"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:45.455198Z","iopub.execute_input":"2025-04-16T13:15:45.455439Z","iopub.status.idle":"2025-04-16T13:15:49.613795Z","shell.execute_reply.started":"2025-04-16T13:15:45.455417Z","shell.execute_reply":"2025-04-16T13:15:49.613087Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Config","metadata":{}},{"cell_type":"code","source":"class TrainGlobalConfig:\n    num_workers = 4\n    batch_size = 16 \n    n_epochs = 4\n    lr = 6.25e-05\n\n    # -------------------\n    verbose = True\n    verbose_step = 1\n    # -------------------\n\n    # --------------------\n    step_scheduler = False  # do scheduler.step after optimizer.step\n    validation_scheduler = True  # do scheduler.step after validation stage loss\n\n#     SchedulerClass = torch.optim.lr_scheduler.OneCycleLR\n#     scheduler_params = dict(\n#         max_lr=0.001,\n#         epochs=n_epochs,\n#         steps_per_epoch=int(len(train_dataset) / batch_size),\n#         pct_start=0.1,\n#         anneal_strategy='cos', \n#         final_div_factor=10**5\n#     )\n    \n    SchedulerClass = torch.optim.lr_scheduler.ReduceLROnPlateau\n    scheduler_params = dict(\n        mode='min',\n        factor=0.5,\n        patience=1,\n        verbose=False, \n        threshold=0.0001,\n        threshold_mode='abs',\n        cooldown=0, \n        min_lr=1e-8,\n        eps=1e-08\n    )\n    # --------------------","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:49.614837Z","iopub.execute_input":"2025-04-16T13:15:49.615100Z","iopub.status.idle":"2025-04-16T13:15:49.621211Z","shell.execute_reply.started":"2025-04-16T13:15:49.615077Z","shell.execute_reply":"2025-04-16T13:15:49.620329Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Class Balance \"on fly\" from [@CatalystTeam](https://github.com/catalyst-team/catalyst)","metadata":{}},{"cell_type":"code","source":"from catalyst.data.sampler import BalanceClassSampler\n\ndef run_training():\n    device = torch.device('cuda:0')\n\n    train_loader = torch.utils.data.DataLoader(\n        train_dataset,\n        sampler=BalanceClassSampler(labels=train_dataset.get_labels(), mode=\"downsampling\"),\n        batch_size=TrainGlobalConfig.batch_size,\n        pin_memory=False,\n        drop_last=True,\n        num_workers=TrainGlobalConfig.num_workers,\n    )\n    val_loader = torch.utils.data.DataLoader(\n        validation_dataset, \n        batch_size=TrainGlobalConfig.batch_size,\n        num_workers=TrainGlobalConfig.num_workers,\n        shuffle=False,\n        sampler=SequentialSampler(validation_dataset),\n        pin_memory=False,\n    )\n\n    fitter = Fitter(model=net, device=device, config=TrainGlobalConfig)\n#     fitter.load(f'{fitter.base_dir}/last-checkpoint.bin')\n    fitter.fit(train_loader, val_loader)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:49.623845Z","iopub.execute_input":"2025-04-16T13:15:49.624175Z","iopub.status.idle":"2025-04-16T13:15:54.445852Z","shell.execute_reply.started":"2025-04-16T13:15:49.624150Z","shell.execute_reply":"2025-04-16T13:15:54.445045Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Training\n\nI have used 1xV100 for training model, in kaggle kernel it works also. You can make fork and check it, but I would like to share with you my logs","metadata":{}},{"cell_type":"code","source":"# run_training()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:54.447860Z","iopub.execute_input":"2025-04-16T13:15:54.448244Z","iopub.status.idle":"2025-04-16T13:15:54.451968Z","shell.execute_reply.started":"2025-04-16T13:15:54.448195Z","shell.execute_reply":"2025-04-16T13:15:54.451090Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"file = open('../input/checkpoints/log.txt', 'r')\nfor line in file.readlines():\n    print(line[:-1])\nfile.close()","metadata":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:15:54.453433Z","iopub.execute_input":"2025-04-16T13:15:54.453758Z","iopub.status.idle":"2025-04-16T13:15:54.500850Z","shell.execute_reply.started":"2025-04-16T13:15:54.453725Z","shell.execute_reply":"2025-04-16T13:15:54.500078Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Inference","metadata":{}},{"cell_type":"code","source":"checkpoint = torch.load('../input/checkpoints/best-checkpoint-003epoch.bin')\n\nnet.load_state_dict(checkpoint['model_state_dict']);\nnet.eval();","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:16:12.653349Z","iopub.execute_input":"2025-04-16T13:16:12.653690Z","iopub.status.idle":"2025-04-16T13:16:12.806089Z","shell.execute_reply.started":"2025-04-16T13:16:12.653662Z","shell.execute_reply":"2025-04-16T13:16:12.805422Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"In checkpoint you can find states for optimizer and scheduler if you need","metadata":{}},{"cell_type":"code","source":"checkpoint.keys()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:16:16.928795Z","iopub.execute_input":"2025-04-16T13:16:16.929095Z","iopub.status.idle":"2025-04-16T13:16:16.934141Z","shell.execute_reply.started":"2025-04-16T13:16:16.929070Z","shell.execute_reply":"2025-04-16T13:16:16.933483Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class DatasetSubmissionRetriever(Dataset):\n\n    def __init__(self, image_names, transforms=None):\n        super().__init__()\n        self.image_names = image_names\n        self.transforms = transforms\n\n    def __getitem__(self, index: int):\n        image_name = self.image_names[index]\n        image = cv2.imread(f'{DATA_ROOT_PATH}/Test/{image_name}', cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n        if self.transforms:\n            sample = {'image': image}\n            sample = self.transforms(**sample)\n            image = sample['image']\n\n        return image_name, image\n\n    def __len__(self) -> int:\n        return self.image_names.shape[0]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:16:19.209651Z","iopub.execute_input":"2025-04-16T13:16:19.209956Z","iopub.status.idle":"2025-04-16T13:16:19.216844Z","shell.execute_reply.started":"2025-04-16T13:16:19.209930Z","shell.execute_reply":"2025-04-16T13:16:19.215865Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dataset = DatasetSubmissionRetriever(\n    image_names=np.array([path.split('/')[-1] for path in glob('../input/alaska2-image-steganalysis/Test/*.jpg')]),\n    transforms=get_valid_transforms(),\n)\n\n\ndata_loader = DataLoader(\n    dataset,\n    batch_size=8,\n    shuffle=False,\n    num_workers=2,\n    drop_last=False,\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:16:24.621480Z","iopub.execute_input":"2025-04-16T13:16:24.621824Z","iopub.status.idle":"2025-04-16T13:16:24.686901Z","shell.execute_reply.started":"2025-04-16T13:16:24.621797Z","shell.execute_reply":"2025-04-16T13:16:24.686189Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%%time\n\nresult = {'Id': [], 'Label': []}\nfor step, (image_names, images) in enumerate(data_loader):\n    print(step, end='\\r')\n    \n    y_pred = net(images.cuda())\n    y_pred = 1 - nn.functional.softmax(y_pred, dim=1).data.cpu().numpy()[:,0]\n    \n    result['Id'].extend(image_names)\n    result['Label'].extend(y_pred)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:16:27.476857Z","iopub.execute_input":"2025-04-16T13:16:27.477195Z","iopub.status.idle":"2025-04-16T13:17:46.461263Z","shell.execute_reply.started":"2025-04-16T13:16:27.477168Z","shell.execute_reply":"2025-04-16T13:17:46.460415Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = pd.DataFrame(result)\nsubmission.to_csv('submission.csv', index=False)\nsubmission.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:18:31.230977Z","iopub.execute_input":"2025-04-16T13:18:31.231274Z","iopub.status.idle":"2025-04-16T13:18:31.415589Z","shell.execute_reply.started":"2025-04-16T13:18:31.231247Z","shell.execute_reply":"2025-04-16T13:18:31.414729Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission['Label'].hist(bins=100);","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T13:18:35.317417Z","iopub.execute_input":"2025-04-16T13:18:35.317720Z","iopub.status.idle":"2025-04-16T13:18:35.582376Z","shell.execute_reply.started":"2025-04-16T13:18:35.317692Z","shell.execute_reply":"2025-04-16T13:18:35.581456Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Thank you for reading my kernel!","metadata":{}}]}