Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Synthetic anomaly for testing and validation #634

Merged
merged 110 commits into from
Dec 14, 2022
Merged
Changes from 1 commit
Commits
Show all changes
110 commits
Select commit Hold shift + click to select a range
ee1cfce
move sample generation to datamodule instead of dataset
djdameln Sep 9, 2022
ec5199e
move sample generation from init to setup
djdameln Sep 12, 2022
9f0a35e
remove inference stage and add base classes
djdameln Sep 13, 2022
dea176f
replace dataset classes with AnomalibDataset
djdameln Sep 13, 2022
62a04f8
move setup to base class, create samples as class method
djdameln Sep 13, 2022
e91afad
update docstrings
djdameln Sep 13, 2022
df4a805
refactor btech to new format
djdameln Sep 14, 2022
c225a83
allow training with no anomalous data
djdameln Sep 14, 2022
ac0dc8a
remove MVTec name from comment
djdameln Sep 15, 2022
5d90209
raise NotImplementedError in base class
djdameln Sep 15, 2022
c1e6724
allow both png and bmp images for btech
djdameln Sep 15, 2022
2d70d89
use label_index to check if dataset contains anomalous images
djdameln Sep 16, 2022
f5f17db
refactor getitem in dataset class
djdameln Sep 16, 2022
f02065f
use iloc for indexing
djdameln Sep 16, 2022
9cba9da
move dataloader getters to base class
djdameln Sep 16, 2022
5b3e841
refactor to add validate stage in setup
djdameln Sep 16, 2022
f652227
implement alternative datamodules solution
djdameln Sep 21, 2022
0e565a4
small improvements
djdameln Sep 21, 2022
297195a
improve design
djdameln Oct 7, 2022
94cabb7
remove unused constructor arguments
djdameln Oct 7, 2022
1ee8a96
adapt btech to new design
djdameln Oct 7, 2022
7fc5483
add prepare_data method for mvtec
djdameln Oct 7, 2022
8a9a30c
solve merge conflicts
djdameln Oct 7, 2022
1ac7c65
implement more generic random splitting function
djdameln Oct 10, 2022
965ea94
update docstrings for folder module
djdameln Oct 10, 2022
2a9f6f8
ensure type consistency when performing operations on dataset
djdameln Oct 10, 2022
84997b9
change imports
djdameln Oct 10, 2022
f21c652
change variable names
djdameln Oct 10, 2022
ab7d0ff
replace pass with NotImplementedError
djdameln Oct 10, 2022
d7e47a9
allow training on folder without test images
djdameln Oct 11, 2022
da851c6
use relative path for normal_test_dir
djdameln Oct 11, 2022
f3e38ba
fix dataset tests
djdameln Oct 11, 2022
f4719f2
update validation set parameter in configs
djdameln Oct 11, 2022
e25a587
change default argument
djdameln Oct 11, 2022
1170ca3
Merge branch 'main' into da/datamodules-alternative
djdameln Oct 11, 2022
fb84cd1
use setter for samples
djdameln Oct 12, 2022
cfa4f52
hint options for val_split_mode
djdameln Oct 12, 2022
624e522
update assert message and docstring
djdameln Oct 12, 2022
0bd77f9
revert name change dataset vs datamodule
djdameln Oct 12, 2022
6bed98f
typing and docstrings
djdameln Oct 12, 2022
fc34f8e
remove samples argument from dataset constructor
djdameln Oct 12, 2022
1482c13
val/test -> eval
djdameln Oct 12, 2022
e168163
remove Split.Full from enum
djdameln Oct 13, 2022
5071dcf
sort samples when setting
djdameln Oct 13, 2022
e175d7d
update warn message
djdameln Oct 13, 2022
03773b0
formatting
djdameln Oct 13, 2022
3910c32
use setter when creating samples in dataset classes
djdameln Oct 13, 2022
894ef12
add tests for new dataset class
djdameln Oct 13, 2022
44009e2
add test case for label aware random split
djdameln Oct 13, 2022
012ed47
update parameter name in inferencers
djdameln Oct 14, 2022
62b176e
move _setup implementation to base class
djdameln Oct 14, 2022
7e957b6
address codacy issues
djdameln Oct 14, 2022
25f503d
fix pylint issues
djdameln Oct 14, 2022
1245928
codacy
djdameln Oct 14, 2022
d9bd6e0
Merge branch 'main' into da/datamodules-alternative
djdameln Oct 14, 2022
0459a0d
update example dataset config in docs
djdameln Oct 14, 2022
30dc45a
fix test
djdameln Oct 14, 2022
85c475a
move base classes to separate files (avoid circular import)
djdameln Oct 14, 2022
0552c1a
add synthetic dataset class
djdameln Oct 14, 2022
bf4f537
move augmenter to data directory
djdameln Oct 14, 2022
cc32896
add base classes
djdameln Oct 14, 2022
23d4766
update docstring
djdameln Oct 14, 2022
b06fc63
Merge branch 'da/datamodules-alternative' into da/synthetic-validatio…
djdameln Oct 14, 2022
05ba31d
use synthetic dataset in base datamodule
djdameln Oct 14, 2022
e8d7998
fix imports
djdameln Oct 14, 2022
26b6b83
clean up synthetic anomaly dataset implementation
djdameln Oct 17, 2022
c32fee9
fix mistake in augmenter
djdameln Oct 17, 2022
e120434
change default split ratio
djdameln Oct 17, 2022
14ee645
remove accidentally added file
djdameln Oct 17, 2022
9c4e7bf
validation_split_mode -> val_split_mode
djdameln Oct 18, 2022
e5d22aa
Merge branch 'da/datamodules-alternative' into da/synthetic-validatio…
djdameln Oct 18, 2022
067d601
update docs
djdameln Oct 19, 2022
c84c99c
Update anomalib/data/base/dataset.py
djdameln Oct 21, 2022
b680d44
get length from self.samples
djdameln Oct 21, 2022
95c37b0
assert unique indices
djdameln Oct 21, 2022
3e77014
check is_setup for individual datasets
djdameln Oct 21, 2022
ede213a
remove assert in __getitem_\
djdameln Oct 21, 2022
f5e2d24
Update anomalib/data/btech.py
djdameln Oct 21, 2022
d9e1369
clearer assert message
djdameln Oct 21, 2022
2e6bc60
clarify list inversion in comment
djdameln Oct 21, 2022
af0cd99
comments and typing
djdameln Oct 21, 2022
d508786
Merge branch 'da/datamodules-alternative' of https://github.com/openv…
djdameln Oct 21, 2022
c85713c
Merge branch 'main' into da/datamodules-alternative
djdameln Oct 21, 2022
5ee8480
validate contents of samples dataframe before setting
djdameln Oct 21, 2022
a5e876a
add file paths check
djdameln Oct 21, 2022
c490e30
add seed to random_split function
djdameln Oct 21, 2022
4808287
fix expected columns
djdameln Oct 24, 2022
10bbf9c
fix typo
djdameln Oct 24, 2022
81d3ca3
add seed parameter to datamodules
djdameln Oct 28, 2022
b372dd1
set global seed in test entrypoint
djdameln Oct 28, 2022
e07a12c
add NONE option to valsplitmode
djdameln Oct 28, 2022
ffdb47c
clarify setup behaviour in docstring
djdameln Oct 28, 2022
9523ad0
merge latest changes to datamodules
djdameln Nov 4, 2022
622f1b9
merge feature branch
djdameln Nov 4, 2022
79e09e9
Merge branch 'feature/datamodules' into da/synthetic-validation-set
djdameln Nov 28, 2022
9fe6da3
Merge branch 'feature/datamodules' into da/synthetic-validation-set
djdameln Dec 5, 2022
63801a2
add logging message
djdameln Dec 5, 2022
d482cec
Merge branch 'feature/datamodules' into da/synthetic-validation-set
djdameln Dec 5, 2022
74cbc0a
use val_split_ratio for synthetic validation set
djdameln Dec 6, 2022
090cec2
pathlib
djdameln Dec 6, 2022
5f16140
merge feature branch
djdameln Dec 6, 2022
2a8df7b
make synthetic anomaly available for test set
djdameln Dec 9, 2022
ea00442
update configs
djdameln Dec 9, 2022
dfd2d80
add tests
djdameln Dec 9, 2022
ce43e09
simplify test set splitting logic
djdameln Dec 9, 2022
8b2d356
update docstring
djdameln Dec 12, 2022
a126af1
add missing licence
djdameln Dec 12, 2022
b2879c8
split_normal_and_anomalous -> split_by_label
djdameln Dec 12, 2022
532ff8b
VideoAnomalib -> AnomalibVideo
djdameln Dec 12, 2022
b1d7eb1
merge feature branch
djdameln Dec 14, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add tests
djdameln committed Dec 9, 2022
commit dfd2d80266698758bb96c696ad5fa1dd7a98c619
69 changes: 62 additions & 7 deletions tests/pre_merge/datasets/test_datamodule.py
Original file line number Diff line number Diff line change
@@ -37,7 +37,7 @@ def make_avenue_data_module(task="classification", batch_size=1, val_split_mode=
return data_module


def make_mvtec_data_module(task="classification", batch_size=1, val_split_mode="from_test"):
def make_mvtec_data_module(task="classification", batch_size=1, test_split_mode="from_dir", val_split_mode="from_test"):
data_module = MVTec(
root=get_dataset_path(dataset="MVTec"),
category="leather",
@@ -46,14 +46,15 @@ def make_mvtec_data_module(task="classification", batch_size=1, val_split_mode="
eval_batch_size=batch_size,
num_workers=0,
task=task,
test_split_mode=test_split_mode,
val_split_mode=val_split_mode,
)
data_module.prepare_data()
data_module.setup()
return data_module


def make_btech_data_module(task="classification", batch_size=1, val_split_mode="from_test"):
def make_btech_data_module(task="classification", batch_size=1, test_split_mode="from_dir", val_split_mode="from_test"):
"""Create BTech Data Module."""
data_module = BTech(
root=get_dataset_path(dataset="BTech"),
@@ -63,27 +64,38 @@ def make_btech_data_module(task="classification", batch_size=1, val_split_mode="
eval_batch_size=batch_size,
num_workers=0,
task=task,
test_split_mode=test_split_mode,
val_split_mode=val_split_mode,
)
data_module.prepare_data()
data_module.setup()
return data_module


def make_folder_data_module(task="classification", batch_size=1, val_split_mode="from_test"):
def make_folder_data_module(
task="classification",
batch_size=1,
test_split_mode="from_dir",
val_split_mode="from_test",
normal_dir="good",
abnormal_dir="broken_large",
normal_test_dir="good_test",
):
"""Create Folder Data Module."""
root = get_dataset_path(dataset="bottle")
data_module = Folder(
root=root,
normal_dir="good",
abnormal_dir="broken_large",
normal_dir=normal_dir,
abnormal_dir=abnormal_dir,
normal_test_dir=normal_test_dir,
mask_dir=os.path.join(root, "ground_truth/broken_large"),
normal_split_ratio=0.2,
image_size=(256, 256),
train_batch_size=batch_size,
eval_batch_size=batch_size,
num_workers=8,
task=task,
test_split_mode=test_split_mode,
val_split_mode=val_split_mode,
)
data_module.setup()
@@ -116,8 +128,8 @@ def make_ucsdped_data_module(task="classification", batch_size=1, val_split_mode

@pytest.fixture(autouse=True)
def make_data_module():
def make(dataset="folder", task="classification", batch_size=1, val_split_mode="from_test"):
return DATASETS[dataset](task=task, batch_size=batch_size, val_split_mode=val_split_mode)
def make(dataset="folder", **kwargs):
return DATASETS[dataset](**kwargs)

return make

@@ -271,3 +283,46 @@ def test_image_size(self, input_size, effective_image_size, category="shapes", p
data_module = get_datamodule(configurable_parameters)
data_module.setup()
assert next(iter(data_module.train_dataloader()))["image"].shape[-2:] == effective_image_size


class TestSubsetSplitting:
@pytest.mark.parametrize("dataset", ["folder", "mvtec", "btech"])
# @pytest.mark.parametrize("dataset", ["folder"])
@pytest.mark.parametrize("test_split_mode", ("from_dir", "synthetic"))
@pytest.mark.parametrize("val_split_mode", ("from_test", "synthetic"))
def test_non_overlapping_splits(self, make_data_module, dataset, test_split_mode, val_split_mode):
"""Tests if train, test and val splits are non-overlapping."""
data_module = make_data_module(dataset, test_split_mode=test_split_mode, val_split_mode=val_split_mode)
train_samples = data_module.train_data.samples
val_samples = data_module.val_data.samples
test_samples = data_module.test_data.samples
assert len(set(train_samples.image_path).intersection(set(test_samples.image_path))) == 0
assert len(set(val_samples.image_path).intersection(set(test_samples.image_path))) == 0

@pytest.mark.parametrize("dataset", ["folder", "mvtec", "btech"])
# @pytest.mark.parametrize("dataset", ["folder"])
@pytest.mark.parametrize("test_split_mode", ("from_dir", "synthetic"))
def test_equal_splits(self, make_data_module, dataset, test_split_mode):
"""Tests if test and and val splits are equal and non-overlapping with train when val_split_mode == same_as_test."""
data_module = make_data_module(dataset, test_split_mode=test_split_mode, val_split_mode="same_as_test")
train_samples = data_module.train_data.samples
val_samples = data_module.val_data.samples
test_samples = data_module.test_data.samples
assert len(set(train_samples.image_path).intersection(set(test_samples.image_path))) == 0
assert len(set(val_samples.image_path).intersection(set(test_samples.image_path))) == len(val_samples)

@pytest.mark.parametrize("test_split_mode", ("from_dir", "synthetic"))
def test_normal_test_dir_omitted(self, make_data_module, test_split_mode):
"""The test set should always contain normal samples even when no normal_test_dir ir provided."""
data_module = make_data_module(dataset="folder", test_split_mode=test_split_mode, normal_test_dir=None)
assert data_module.test_data.has_normal

def test_abnormal_dir_omitted_from_dir(self, make_data_module):
"""The test set should not contain anomalous samples if no abnormal_dir provided and split mode is from_dir."""
data_module = make_data_module(dataset="folder", test_split_mode="from_dir", abnormal_dir=None)
assert not data_module.test_data.has_anomalous

def test_abnormal_dir_omitted_synthetic(self, make_data_module):
"""The test set should contain anomalous samples if no abnormal_dir provided and split mode is synthetic."""
data_module = make_data_module(dataset="folder", test_split_mode="synthetic", abnormal_dir=None)
assert data_module.test_data.has_anomalous
93 changes: 93 additions & 0 deletions tests/pre_merge/datasets/test_synthetic_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""Tests for synthetic anomalous dataset."""
import os
from copy import copy, deepcopy
from pathlib import Path

import pytest

from anomalib.data import TaskType
from anomalib.data.folder import FolderDataset
from anomalib.data.synthetic import SyntheticAnomalyDataset
from anomalib.pre_processing import PreProcessor
from tests.helpers.dataset import get_dataset_path


def get_folder_dataset():
"""Create Folder Dataset."""
root = get_dataset_path(dataset="bottle")
pre_process = PreProcessor(image_size=(256, 256))
dataset = FolderDataset(
task="segmentation",
pre_process=pre_process,
root=root,
normal_dir="good",
abnormal_dir="broken_large",
mask_dir=os.path.join(root, "ground_truth/broken_large"),
split="train",
)
dataset.setup()

return dataset


@pytest.fixture(autouse=True)
def make_synthetic_dataset():
"""Create synthetic anomaly dataset from folder dataset."""

def make():
folder_dataset = get_folder_dataset()
synthetic_dataset = SyntheticAnomalyDataset.from_dataset(folder_dataset)
return synthetic_dataset

return make


@pytest.fixture(autouse=True)
def synthetic_dataset_from_samples():
"""Create synthetic anomaly dataset by passing a samples dataframe."""
folder_dataset = get_folder_dataset()
pre_process = PreProcessor(image_size=(256, 256))
synthetic_dataset = SyntheticAnomalyDataset(
task=folder_dataset.task, pre_process=pre_process, source_samples=folder_dataset.samples
)
return synthetic_dataset


def test_create_synthetic_dataset(make_synthetic_dataset):
"""Tests if the image and mask files listed in the synthetic dataset exist."""
synthetic_dataset = make_synthetic_dataset()
assert all(Path(path).exists() for path in synthetic_dataset.samples.image_path)
assert all(Path(path).exists() for path in synthetic_dataset.samples.mask_path)


def test_create_from_dataset(synthetic_dataset_from_samples):
"""Tests if the image and mask files listed in the synthetic dataset exist, when instantiated from samples df."""
synthetic_dataset = synthetic_dataset_from_samples
assert all(Path(path).exists() for path in synthetic_dataset.samples.image_path)
assert all(Path(path).exists() for path in synthetic_dataset.samples.mask_path)


def test_cleanup(make_synthetic_dataset):
"""Tests if the temporary directory is cleaned up when the instance is deleted."""
synthetic_dataset = make_synthetic_dataset()
root = synthetic_dataset.root
del synthetic_dataset
assert not root.exists()


def test_copy(make_synthetic_dataset):
"""Tests if the dataset is copied correctly, and files still exist after original instance is deleted."""
synthetic_dataset = make_synthetic_dataset()
synthetic_dataset_cp = copy(synthetic_dataset)
assert all(synthetic_dataset.samples == synthetic_dataset_cp.samples)
del synthetic_dataset
assert synthetic_dataset_cp.root.exists()


def test_deepcopy(make_synthetic_dataset):
"""Tests if the dataset is deep-copied correctly, and files still exist after original instance is deleted."""
synthetic_dataset = make_synthetic_dataset()
synthetic_dataset_cp = deepcopy(synthetic_dataset)
assert all(synthetic_dataset.samples == synthetic_dataset_cp.samples)
del synthetic_dataset
assert synthetic_dataset_cp.root.exists()