|
| 1 | +"""Custom Tabular Data Module. |
| 2 | +
|
| 3 | +This script creates a custom Lightning DataModule from a table or tabular file |
| 4 | +containing image paths and labels. |
| 5 | +
|
| 6 | +Example: |
| 7 | + Create a Tabular datamodule:: |
| 8 | +
|
| 9 | + >>> from anomalib.data import Tabular |
| 10 | + >>> samples = { |
| 11 | + ... "image_path": ["images/image1.png", "images/image2.png", "images/image3.png", ... ], |
| 12 | + ... "label_index": [LabelName.NORMAL, LabelName.NORMAL, LabelName.ABNORMAL, ... ], |
| 13 | + ... "split": [Split.TRAIN, Split.TRAIN, Split.TEST, ... ], |
| 14 | + ... } |
| 15 | + >>> datamodule = Tabular( |
| 16 | + ... name="custom", |
| 17 | + ... samples=samples, |
| 18 | + ... root="./datasets/custom", |
| 19 | + ... ) |
| 20 | +""" |
| 21 | + |
| 22 | +# Copyright (C) 2025 Intel Corporation |
| 23 | +# SPDX-License-Identifier: Apache-2.0 |
| 24 | + |
| 25 | +from pathlib import Path |
| 26 | +from typing import IO |
| 27 | + |
| 28 | +import pandas as pd |
| 29 | +from torchvision.transforms.v2 import Transform |
| 30 | + |
| 31 | +from anomalib.data.datamodules.base.image import AnomalibDataModule |
| 32 | +from anomalib.data.datasets.image.tabular import TabularDataset |
| 33 | +from anomalib.data.utils import Split, TestSplitMode, ValSplitMode |
| 34 | + |
| 35 | + |
| 36 | +class Tabular(AnomalibDataModule): |
| 37 | + """Tabular DataModule. |
| 38 | +
|
| 39 | + Args: |
| 40 | + name (str): Name of the dataset. Used for logging/saving. |
| 41 | + samples (dict | list | DataFrame): Pandas ``DataFrame`` or compatible ``list`` |
| 42 | + or ``dict`` containing the dataset information. |
| 43 | + root (str | Path | None): Root folder containing normal and abnormal |
| 44 | + directories. Defaults to ``None``. |
| 45 | + normal_split_ratio (float): Ratio to split normal training images for |
| 46 | + test set when no normal test images exist. |
| 47 | + Defaults to ``0.2``. |
| 48 | + train_batch_size (int): Training batch size. |
| 49 | + Defaults to ``32``. |
| 50 | + eval_batch_size (int): Validation/test batch size. |
| 51 | + Defaults to ``32``. |
| 52 | + num_workers (int): Number of workers for data loading. |
| 53 | + Defaults to ``8``. |
| 54 | + train_augmentations (Transform | None): Augmentations to apply dto the training images |
| 55 | + Defaults to ``None``. |
| 56 | + val_augmentations (Transform | None): Augmentations to apply to the validation images. |
| 57 | + Defaults to ``None``. |
| 58 | + test_augmentations (Transform | None): Augmentations to apply to the test images. |
| 59 | + Defaults to ``None``. |
| 60 | + augmentations (Transform | None): General augmentations to apply if stage-specific |
| 61 | + augmentations are not provided. |
| 62 | + test_split_mode (TestSplitMode): Method to obtain test subset. |
| 63 | + Defaults to ``TestSplitMode.FROM_DIR``. |
| 64 | + test_split_ratio (float): Fraction of train images for testing. |
| 65 | + Defaults to ``0.2``. |
| 66 | + val_split_mode (ValSplitMode): Method to obtain validation subset. |
| 67 | + Defaults to ``ValSplitMode.FROM_TEST``. |
| 68 | + val_split_ratio (float): Fraction of images for validation. |
| 69 | + Defaults to ``0.5``. |
| 70 | + seed (int | None): Random seed for splitting. |
| 71 | + Defaults to ``None``. |
| 72 | +
|
| 73 | + Example: |
| 74 | + Create and setup a tabular datamodule:: |
| 75 | +
|
| 76 | + >>> from anomalib.data import Tabular |
| 77 | + >>> samples = { |
| 78 | + ... "image_path": ["images/image1.png", "images/image2.png", "images/image3.png", ... ], |
| 79 | + ... "label_index": [LabelName.NORMAL, LabelName.NORMAL, LabelName.ABNORMAL, ... ], |
| 80 | + ... "split": [Split.TRAIN, Split.TRAIN, Split.TEST, ... ], |
| 81 | + ... } |
| 82 | + >>> datamodule = Tabular( |
| 83 | + ... name="custom", |
| 84 | + ... samples=samples, |
| 85 | + ... root="./datasets/custom", |
| 86 | + ... ) |
| 87 | + >>> datamodule.setup() |
| 88 | +
|
| 89 | + Get a batch from train dataloader:: |
| 90 | +
|
| 91 | + >>> batch = next(iter(datamodule.train_dataloader())) |
| 92 | + >>> batch.keys() |
| 93 | + dict_keys(['image', 'label', 'mask', 'image_path', 'mask_path']) |
| 94 | +
|
| 95 | + Get a batch from test dataloader:: |
| 96 | +
|
| 97 | + >>> batch = next(iter(datamodule.test_dataloader())) |
| 98 | + >>> batch.keys() |
| 99 | + dict_keys(['image', 'label', 'mask', 'image_path', 'mask_path']) |
| 100 | + """ |
| 101 | + |
| 102 | + def __init__( |
| 103 | + self, |
| 104 | + name: str, |
| 105 | + samples: dict | list | pd.DataFrame, |
| 106 | + root: str | Path | None = None, |
| 107 | + normal_split_ratio: float = 0.2, |
| 108 | + train_batch_size: int = 32, |
| 109 | + eval_batch_size: int = 32, |
| 110 | + num_workers: int = 8, |
| 111 | + train_augmentations: Transform | None = None, |
| 112 | + val_augmentations: Transform | None = None, |
| 113 | + test_augmentations: Transform | None = None, |
| 114 | + augmentations: Transform | None = None, |
| 115 | + test_split_mode: TestSplitMode | str = TestSplitMode.FROM_DIR, |
| 116 | + test_split_ratio: float = 0.2, |
| 117 | + val_split_mode: ValSplitMode | str = ValSplitMode.FROM_TEST, |
| 118 | + val_split_ratio: float = 0.5, |
| 119 | + seed: int | None = None, |
| 120 | + ) -> None: |
| 121 | + self._name = name |
| 122 | + self.root = root |
| 123 | + self._unprocessed_samples = samples |
| 124 | + test_split_mode = TestSplitMode(test_split_mode) |
| 125 | + val_split_mode = ValSplitMode(val_split_mode) |
| 126 | + super().__init__( |
| 127 | + train_batch_size=train_batch_size, |
| 128 | + eval_batch_size=eval_batch_size, |
| 129 | + num_workers=num_workers, |
| 130 | + train_augmentations=train_augmentations, |
| 131 | + val_augmentations=val_augmentations, |
| 132 | + test_augmentations=test_augmentations, |
| 133 | + augmentations=augmentations, |
| 134 | + test_split_mode=test_split_mode, |
| 135 | + test_split_ratio=test_split_ratio, |
| 136 | + val_split_mode=val_split_mode, |
| 137 | + val_split_ratio=val_split_ratio, |
| 138 | + seed=seed, |
| 139 | + ) |
| 140 | + |
| 141 | + self.normal_split_ratio = normal_split_ratio |
| 142 | + |
| 143 | + def _setup(self, _stage: str | None = None) -> None: |
| 144 | + self.train_data = TabularDataset( |
| 145 | + name=self.name, |
| 146 | + samples=self._unprocessed_samples, |
| 147 | + split=Split.TRAIN, |
| 148 | + root=self.root, |
| 149 | + ) |
| 150 | + |
| 151 | + self.test_data = TabularDataset( |
| 152 | + name=self.name, |
| 153 | + samples=self._unprocessed_samples, |
| 154 | + split=Split.TEST, |
| 155 | + root=self.root, |
| 156 | + ) |
| 157 | + |
| 158 | + @property |
| 159 | + def name(self) -> str: |
| 160 | + """Get name of the datamodule. |
| 161 | +
|
| 162 | + Returns: |
| 163 | + Name of the datamodule. |
| 164 | + """ |
| 165 | + return self._name |
| 166 | + |
| 167 | + @classmethod |
| 168 | + def from_file( |
| 169 | + cls: type["Tabular"], |
| 170 | + name: str, |
| 171 | + file_path: str | Path | IO[str] | IO[bytes], |
| 172 | + file_format: str = "csv", |
| 173 | + pd_kwargs: dict | None = None, |
| 174 | + **kwargs, |
| 175 | + ) -> "Tabular": |
| 176 | + """Create Tabular Datamodule from file. |
| 177 | +
|
| 178 | + Args: |
| 179 | + name (str): Name of the dataset. This is used to name the datamodule, |
| 180 | + especially when logging/saving. |
| 181 | + file_path (str | Path | file-like): Path or file-like object to tabular |
| 182 | + file containing the datset information. |
| 183 | + file_format (str): File format supported by a pd.read_* method, such |
| 184 | + as ``csv``, ``parquet`` or ``json``. |
| 185 | + Defaults to ``csv``. |
| 186 | + pd_kwargs (dict | None): Keyword argument dictionary for the pd.read_* method. |
| 187 | + Defaults to ``None``. |
| 188 | + kwargs (dict): Additional keyword arguments for the Tabular Datamodule class. |
| 189 | +
|
| 190 | + Returns: |
| 191 | + Tabular: Tabular Datamodule |
| 192 | + """ |
| 193 | + pd_kwargs = pd_kwargs or {} |
| 194 | + samples = getattr(pd, f"read_{file_format}")(file_path, **pd_kwargs) |
| 195 | + return cls(name, samples, **kwargs) |
0 commit comments