hiad 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hiad/__init__.py +0 -0
- hiad/datasets/__init__.py +0 -0
- hiad/datasets/patch_dataset.py +77 -0
- hiad/datasets/syn_dataset.py +95 -0
- hiad/detectors/__init__.py +8 -0
- hiad/detectors/base.py +345 -0
- hiad/detectors/destseg/__init__.py +0 -0
- hiad/detectors/destseg/model/__init__.py +1 -0
- hiad/detectors/destseg/model/destseg.py +91 -0
- hiad/detectors/destseg/model/losses.py +33 -0
- hiad/detectors/destseg/model/metrics.py +314 -0
- hiad/detectors/destseg/model/model_utils.py +249 -0
- hiad/detectors/fastflow/__init__.py +0 -0
- hiad/detectors/fastflow/constants.py +29 -0
- hiad/detectors/fastflow/fastflow.py +133 -0
- hiad/detectors/hr_destseg.py +355 -0
- hiad/detectors/hr_fastflow.py +226 -0
- hiad/detectors/hr_padim.py +200 -0
- hiad/detectors/hr_patchcore.py +251 -0
- hiad/detectors/hr_rdpp.py +232 -0
- hiad/detectors/hr_realnet.py +347 -0
- hiad/detectors/hr_vitad.py +268 -0
- hiad/detectors/padim/__init__.py +0 -0
- hiad/detectors/padim/backbones.py +146 -0
- hiad/detectors/padim/utils.py +33 -0
- hiad/detectors/patchcore/__init__.py +0 -0
- hiad/detectors/patchcore/backbones.py +59 -0
- hiad/detectors/patchcore/common.py +452 -0
- hiad/detectors/patchcore/sampler.py +199 -0
- hiad/detectors/patchcore/utils.py +34 -0
- hiad/detectors/rdpp/__init__.py +0 -0
- hiad/detectors/rdpp/de_resnet.py +390 -0
- hiad/detectors/rdpp/resnet.py +619 -0
- hiad/detectors/rdpp/utils/__init__.py +0 -0
- hiad/detectors/rdpp/utils/utils_test.py +41 -0
- hiad/detectors/rdpp/utils/utils_train.py +121 -0
- hiad/detectors/realnet/__init__.py +0 -0
- hiad/detectors/realnet/models/__init__.py +0 -0
- hiad/detectors/realnet/models/afs/__init__.py +1 -0
- hiad/detectors/realnet/models/afs/afs.py +134 -0
- hiad/detectors/realnet/models/backbones/__init__.py +1 -0
- hiad/detectors/realnet/models/backbones/backbone.py +51 -0
- hiad/detectors/realnet/models/backbones/feature_extraction.py +560 -0
- hiad/detectors/realnet/models/initializer.py +77 -0
- hiad/detectors/realnet/models/model_helper.py +68 -0
- hiad/detectors/realnet/models/recon/__init__.py +2 -0
- hiad/detectors/realnet/models/recon/recon.py +287 -0
- hiad/detectors/realnet/models/recon/simple_recon.py +116 -0
- hiad/detectors/realnet/models/rrs/__init__.py +1 -0
- hiad/detectors/realnet/models/rrs/rrs.py +133 -0
- hiad/detectors/realnet/models/sdas/__init__.py +0 -0
- hiad/detectors/realnet/models/sdas/create_models.py +81 -0
- hiad/detectors/realnet/models/sdas/model_utils.py +402 -0
- hiad/detectors/realnet/models/sdas/unets.py +473 -0
- hiad/detectors/realnet/utils/__init__.py +0 -0
- hiad/detectors/realnet/utils/categories.py +97 -0
- hiad/detectors/realnet/utils/criterion_helper.py +149 -0
- hiad/detectors/realnet/utils/dist_helper.py +26 -0
- hiad/detectors/realnet/utils/eval_helper.py +239 -0
- hiad/detectors/realnet/utils/misc_helper.py +128 -0
- hiad/detectors/realnet/utils/optimizer_helper.py +12 -0
- hiad/detectors/realnet/utils/visualize.py +69 -0
- hiad/detectors/vitad/__init__.py +0 -0
- hiad/detectors/vitad/config.py +68 -0
- hiad/detectors/vitad/loss/__init__.py +20 -0
- hiad/detectors/vitad/loss/base_loss.py +343 -0
- hiad/detectors/vitad/loss/cls_loss.py +60 -0
- hiad/detectors/vitad/loss/gan_loss.py +172 -0
- hiad/detectors/vitad/model/__init__.py +1 -0
- hiad/detectors/vitad/model/vitad.py +463 -0
- hiad/detectors/vitad/optim/__init__.py +74 -0
- hiad/detectors/vitad/optim/scheduler.py +93 -0
- hiad/detectors/vitad/util/__init__.py +0 -0
- hiad/detectors/vitad/util/net.py +85 -0
- hiad/syn/__init__.py +1 -0
- hiad/syn/syn.py +325 -0
- hiad/syn/utils.py +29 -0
- hiad/task/__init__.py +1 -0
- hiad/task/task.py +348 -0
- hiad/task/utils.py +93 -0
- hiad/trainer/__init__.py +1 -0
- hiad/trainer/trainer.py +345 -0
- hiad/utils/__init__.py +0 -0
- hiad/utils/base.py +184 -0
- hiad/utils/device.py +414 -0
- hiad/utils/metrics.py +136 -0
- hiad/utils/metrics_gpu.py +172 -0
- hiad/utils/pro.py +344 -0
- hiad/utils/split_and_gather.py +400 -0
- hiad-0.1.0.dist-info/LICENSE +201 -0
- hiad-0.1.0.dist-info/METADATA +38 -0
- hiad-0.1.0.dist-info/RECORD +94 -0
- hiad-0.1.0.dist-info/WHEEL +5 -0
- hiad-0.1.0.dist-info/top_level.txt +1 -0
hiad/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
import torch
|
|
3
|
+
from torchvision import transforms
|
|
4
|
+
from torch.utils.data import Dataset
|
|
5
|
+
import numpy
|
|
6
|
+
|
|
7
|
+
from hiad.utils.split_and_gather import LRPatch
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PatchDataset(Dataset):
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
patches: List[LRPatch],
|
|
15
|
+
training: bool,
|
|
16
|
+
task_name: str,
|
|
17
|
+
normalize_mean: List[float] = None,
|
|
18
|
+
normalize_std: List[float] = None,
|
|
19
|
+
**kwargs,
|
|
20
|
+
):
|
|
21
|
+
|
|
22
|
+
super().__init__()
|
|
23
|
+
self.patches = patches
|
|
24
|
+
self.training = training
|
|
25
|
+
self.task_name = task_name
|
|
26
|
+
|
|
27
|
+
if normalize_mean is None:
|
|
28
|
+
normalize_mean = [0.485, 0.456, 0.406]
|
|
29
|
+
|
|
30
|
+
if normalize_std is None:
|
|
31
|
+
normalize_std = [0.229, 0.224, 0.225]
|
|
32
|
+
|
|
33
|
+
self.transform_img = [
|
|
34
|
+
transforms.ToTensor(),
|
|
35
|
+
transforms.Normalize(mean=normalize_mean, std=normalize_std),
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
self.transform_mask = [
|
|
39
|
+
transforms.ToTensor()
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
self.transform_img = transforms.Compose(self.transform_img)
|
|
43
|
+
self.transform_mask = transforms.Compose(self.transform_mask)
|
|
44
|
+
|
|
45
|
+
def __getitem__(self, idx):
|
|
46
|
+
|
|
47
|
+
patch = self.patches[idx]
|
|
48
|
+
image = patch.image.astype(numpy.uint8)
|
|
49
|
+
image = self.transform_img(image)
|
|
50
|
+
|
|
51
|
+
if patch.mask is not None:
|
|
52
|
+
mask = self.transform_mask(patch.mask.astype(numpy.uint8)).squeeze(0)
|
|
53
|
+
mask [mask!=0] = 1
|
|
54
|
+
else:
|
|
55
|
+
mask = torch.zeros(image.shape[1:])
|
|
56
|
+
|
|
57
|
+
item = {
|
|
58
|
+
"image": image,
|
|
59
|
+
"mask": mask,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if patch.clsname is not None:
|
|
63
|
+
item.update({"clsname": patch.clsname})
|
|
64
|
+
|
|
65
|
+
if patch.label is not None:
|
|
66
|
+
item.update({"label": patch.label})
|
|
67
|
+
|
|
68
|
+
if patch.low_resolution_images is not None:
|
|
69
|
+
for i, (low_resolution_image, low_resolution_index) in enumerate(zip(patch.low_resolution_images, patch.low_resolution_indexes)):
|
|
70
|
+
low_resolution_image = low_resolution_image.astype(numpy.uint8)
|
|
71
|
+
low_resolution_image = self.transform_img(low_resolution_image)
|
|
72
|
+
item[f'low_resolution_image_{i}'] = low_resolution_image
|
|
73
|
+
item[f'low_resolution_index_{i}'] = str(low_resolution_index)
|
|
74
|
+
return item
|
|
75
|
+
|
|
76
|
+
def __len__(self):
|
|
77
|
+
return len(self.patches)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
import torch
|
|
3
|
+
from torchvision import transforms
|
|
4
|
+
from torch.utils.data import Dataset
|
|
5
|
+
import numpy
|
|
6
|
+
|
|
7
|
+
from hiad.syn import BaseAnomalySynthesizer
|
|
8
|
+
from hiad.utils.split_and_gather import LRPatch
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AnomalySynDataset(Dataset):
|
|
12
|
+
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
patches: List[LRPatch],
|
|
16
|
+
synthesizer: BaseAnomalySynthesizer,
|
|
17
|
+
training: bool,
|
|
18
|
+
task_name: str,
|
|
19
|
+
normalize_mean: List[float] = None,
|
|
20
|
+
normalize_std: List[float] = None,
|
|
21
|
+
**kwargs,
|
|
22
|
+
):
|
|
23
|
+
|
|
24
|
+
self.patches = patches
|
|
25
|
+
self.synthesizer = synthesizer
|
|
26
|
+
self.training = training
|
|
27
|
+
self.task_name = task_name
|
|
28
|
+
|
|
29
|
+
if normalize_mean is None:
|
|
30
|
+
normalize_mean = [0.485, 0.456, 0.406]
|
|
31
|
+
|
|
32
|
+
if normalize_std is None:
|
|
33
|
+
normalize_std = [0.229, 0.224, 0.225]
|
|
34
|
+
|
|
35
|
+
self.transform_img = [
|
|
36
|
+
transforms.ToTensor(),
|
|
37
|
+
transforms.Normalize(mean=normalize_mean, std=normalize_std),
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
self.transform_mask = [
|
|
41
|
+
transforms.ToTensor()
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
self.transform_img = transforms.Compose(self.transform_img)
|
|
45
|
+
self.transform_mask = transforms.Compose(self.transform_mask)
|
|
46
|
+
super().__init__()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def __getitem__(self, idx):
|
|
50
|
+
items = {}
|
|
51
|
+
patch = self.patches[idx]
|
|
52
|
+
image = patch.image.astype(numpy.uint8)
|
|
53
|
+
image = self.transform_img(image)
|
|
54
|
+
items.update({'gt_image': image})
|
|
55
|
+
|
|
56
|
+
if patch.low_resolution_images is not None:
|
|
57
|
+
for i, (low_resolution_image, low_resolution_index) in enumerate(
|
|
58
|
+
zip(patch.low_resolution_images, patch.low_resolution_indexes)):
|
|
59
|
+
low_resolution_image = low_resolution_image.astype(numpy.uint8)
|
|
60
|
+
low_resolution_image = self.transform_img(low_resolution_image)
|
|
61
|
+
items[f'gt_low_resolution_image_{i}'] = low_resolution_image
|
|
62
|
+
items[f'gt_low_resolution_index_{i}'] = str(low_resolution_index)
|
|
63
|
+
|
|
64
|
+
anomaly_patch = self.synthesizer.anomaly_synthesize(patch)
|
|
65
|
+
image = self.transform_img(anomaly_patch.image.astype(numpy.uint8))
|
|
66
|
+
items.update({'image': image})
|
|
67
|
+
|
|
68
|
+
if anomaly_patch.low_resolution_images is not None:
|
|
69
|
+
for i, (low_resolution_image, low_resolution_index) in enumerate(
|
|
70
|
+
zip(anomaly_patch.low_resolution_images, anomaly_patch.low_resolution_indexes)):
|
|
71
|
+
low_resolution_image = low_resolution_image.astype(numpy.uint8)
|
|
72
|
+
low_resolution_image = self.transform_img(low_resolution_image)
|
|
73
|
+
items[f'low_resolution_image_{i}'] = low_resolution_image
|
|
74
|
+
items[f'low_resolution_index_{i}'] = str(low_resolution_index)
|
|
75
|
+
|
|
76
|
+
if anomaly_patch.mask is not None:
|
|
77
|
+
mask = self.transform_mask(anomaly_patch.mask.astype(numpy.uint8)).squeeze(0)
|
|
78
|
+
mask [mask!=0] = 1
|
|
79
|
+
else:
|
|
80
|
+
mask = torch.zeros(image.shape[1:])
|
|
81
|
+
|
|
82
|
+
items.update({
|
|
83
|
+
"mask": mask
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
if patch.clsname is not None:
|
|
87
|
+
items.update({"clsname": patch.clsname})
|
|
88
|
+
|
|
89
|
+
if patch.label is not None:
|
|
90
|
+
items.update({"label": patch.label})
|
|
91
|
+
|
|
92
|
+
return items
|
|
93
|
+
|
|
94
|
+
def __len__(self):
|
|
95
|
+
return len(self.patches)
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from .base import BaseDetector
|
|
2
|
+
from .hr_patchcore import HRPatchCore
|
|
3
|
+
from .hr_fastflow import HRFastFlow
|
|
4
|
+
from .hr_vitad import HRVitAD
|
|
5
|
+
from .hr_realnet import HRRealNet
|
|
6
|
+
from .hr_destseg import HRDesTSeg
|
|
7
|
+
from .hr_rdpp import HRRDPP
|
|
8
|
+
from .hr_padim import HRPaDiM
|
hiad/detectors/base.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import List
|
|
3
|
+
import numpy as np
|
|
4
|
+
from torch.utils.data import DataLoader
|
|
5
|
+
import numpy
|
|
6
|
+
import torch
|
|
7
|
+
import torch.nn.functional as F
|
|
8
|
+
import cv2
|
|
9
|
+
import scipy.ndimage as ndimage
|
|
10
|
+
import copy
|
|
11
|
+
from tqdm import tqdm
|
|
12
|
+
|
|
13
|
+
from hiad.utils.base import get_avg_score
|
|
14
|
+
from hiad.utils.split_and_gather import HRImageIndex, LRPatch
|
|
15
|
+
from hiad.datasets.patch_dataset import PatchDataset
|
|
16
|
+
|
|
17
|
+
class BaseDetector(ABC):
|
|
18
|
+
|
|
19
|
+
def __init__(self, patch_size, device, fusion_weights = None, logger = None, seed =0, early_stop_epochs = -1, **kwargs):
|
|
20
|
+
r"""
|
|
21
|
+
Base class for detectors. New detectors can be created by inheriting from this class.
|
|
22
|
+
Args:
|
|
23
|
+
patch_size (int or list): Resolution of image patches.
|
|
24
|
+
device (torch.Device): Model load device.
|
|
25
|
+
fusion_weights (list): Fusion weights for feature fusion. If None, a set of equal fusion weights will be used.
|
|
26
|
+
logger (logging.Logger): Logger object
|
|
27
|
+
seed (int): random seed.
|
|
28
|
+
early_stop_epochs (int): Controls early stopping for detector: if a detector shows no performance improvement on the validation set for N epochs, training will be stopped.
|
|
29
|
+
If -1, Early stopping will be disabled.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
if isinstance(patch_size, int):
|
|
33
|
+
self.patch_size = [patch_size, patch_size]
|
|
34
|
+
else:
|
|
35
|
+
self.patch_size = patch_size
|
|
36
|
+
self.seed = seed
|
|
37
|
+
self.logger = logger
|
|
38
|
+
self.device = device
|
|
39
|
+
self.early_stop_epochs = early_stop_epochs
|
|
40
|
+
self.early_stop_cur = self.early_stop_epochs
|
|
41
|
+
self.fusion_weights = fusion_weights
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def embedding(self, input_tensor: torch.Tensor ) -> List[torch.Tensor]:
|
|
45
|
+
r"""
|
|
46
|
+
This method encodes image patches into feature representations (feature extraction).
|
|
47
|
+
|
|
48
|
+
Args
|
|
49
|
+
input_tensor (torch.Tensor): Input image patch tensor. Shape: (B,3,H,W)
|
|
50
|
+
return:
|
|
51
|
+
Returns a list of extracted features (multi-scale features). Shape: ([B,C1,H1,W1], [B,C2,H2,W2], ..., [B,Cn,Hn,Wn])
|
|
52
|
+
"""
|
|
53
|
+
raise NotImplementedError
|
|
54
|
+
|
|
55
|
+
@abstractmethod
|
|
56
|
+
def train_step(self,
|
|
57
|
+
train_dataloader: DataLoader,
|
|
58
|
+
task_name: str,
|
|
59
|
+
checkpoint_path: str,
|
|
60
|
+
val_dataloader: DataLoader = None,
|
|
61
|
+
evaluators=None,
|
|
62
|
+
) -> bool:
|
|
63
|
+
r"""
|
|
64
|
+
This method defines the training procedure of the model.
|
|
65
|
+
|
|
66
|
+
Args
|
|
67
|
+
train_dataloader (torch.utils.data.DataLoader): DataLoader used for training; the format of the returned data is defined by `create_dataset`.
|
|
68
|
+
task_name (str): Task Name.
|
|
69
|
+
checkpoint_path: Path for saving model checkpoints.
|
|
70
|
+
val_dataloader (torch.utils.data.DataLoader): DataLoader used for validation; the format of the returned data is defined by `create_dataset`.
|
|
71
|
+
If no validation configuration is provided, this value will be None.
|
|
72
|
+
evaluators: Evaluation method used for validation.
|
|
73
|
+
The `val_step` method provides a built-in implementation of the validation procedure.
|
|
74
|
+
You can perform validation using the code below; `best_metrics` include the historically best validation scores.
|
|
75
|
+
best_metrics = {}
|
|
76
|
+
best_metrics = self.val_step(val_dataloader, evaluators, checkpoint_path, best_metrics)
|
|
77
|
+
|
|
78
|
+
return:
|
|
79
|
+
Returns a boolean: True if the checkpoint has been saved; False if not, which will trigger the `trainer` to perform the save.
|
|
80
|
+
"""
|
|
81
|
+
raise NotImplementedError
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@abstractmethod
|
|
85
|
+
def inference_step(self,
|
|
86
|
+
test_dataloader: DataLoader,
|
|
87
|
+
task_name: str):
|
|
88
|
+
r"""
|
|
89
|
+
This method defines the inference (test) procedure of the model.
|
|
90
|
+
|
|
91
|
+
Args
|
|
92
|
+
test_dataloader (torch.utils.data.DataLoader): DataLoader used for testing; the format of the returned data is defined by `create_dataset`.
|
|
93
|
+
task_name (str): Task Name.
|
|
94
|
+
|
|
95
|
+
return:
|
|
96
|
+
Returns a list of numpy.ndarray, where each array corresponds to the detection results of an individual sample.
|
|
97
|
+
Shape: ([H,W],..., [H,W]), where H and W is the height and width of the image.
|
|
98
|
+
"""
|
|
99
|
+
raise NotImplementedError
|
|
100
|
+
|
|
101
|
+
@abstractmethod
|
|
102
|
+
def save_checkpoint(self,
|
|
103
|
+
checkpoint_path: str
|
|
104
|
+
):
|
|
105
|
+
r"""
|
|
106
|
+
save checkpoint
|
|
107
|
+
Args
|
|
108
|
+
checkpoint_path (str): Path of checkpoint
|
|
109
|
+
"""
|
|
110
|
+
raise NotImplementedError
|
|
111
|
+
|
|
112
|
+
@abstractmethod
|
|
113
|
+
def load_checkpoint(self, checkpoint_path: str):
|
|
114
|
+
r"""
|
|
115
|
+
load checkpoint
|
|
116
|
+
Args
|
|
117
|
+
checkpoint_path (str): Path of checkpoint
|
|
118
|
+
"""
|
|
119
|
+
raise NotImplementedError
|
|
120
|
+
|
|
121
|
+
@torch.no_grad()
|
|
122
|
+
def val_step(self,
|
|
123
|
+
val_dataloader,
|
|
124
|
+
evaluators,
|
|
125
|
+
checkpoint_path,
|
|
126
|
+
best_metrics):
|
|
127
|
+
r"""
|
|
128
|
+
This method defines the basic validation procedure.
|
|
129
|
+
|
|
130
|
+
Args
|
|
131
|
+
val_dataloader (torch.utils.data.DataLoader): DataLoader used for validation; the format of the returned data is defined by `create_dataset`.
|
|
132
|
+
evaluators: Evaluation method used for validation.
|
|
133
|
+
checkpoint_path: Path for saving model checkpoints.
|
|
134
|
+
best_metrics: the best historical metrics
|
|
135
|
+
|
|
136
|
+
return:
|
|
137
|
+
best_metrics: updated best metrics
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
pred_masks = self.inference_step(val_dataloader, task_name='val')
|
|
141
|
+
pred_masks = numpy.stack(pred_masks)
|
|
142
|
+
self.max_anomaly_score, self.min_anomaly_score = numpy.max(pred_masks), numpy.min(pred_masks)
|
|
143
|
+
pred_masks = self.patch_post_processing(pred_masks)
|
|
144
|
+
gt_labels = [patch.label for patch in val_dataloader.dataset.patches]
|
|
145
|
+
gt_masks = []
|
|
146
|
+
for patch in val_dataloader.dataset.patches:
|
|
147
|
+
if patch.mask is not None:
|
|
148
|
+
mask = copy.deepcopy(patch.mask)
|
|
149
|
+
mask[mask != 0] = 1
|
|
150
|
+
else:
|
|
151
|
+
mask = numpy.zeros(pred_masks.shape[1:]).astype(float)
|
|
152
|
+
gt_masks.append(mask)
|
|
153
|
+
gt_masks = numpy.stack(gt_masks)
|
|
154
|
+
pred_labels = self.get_image_score(pred_masks)
|
|
155
|
+
scores = {}
|
|
156
|
+
for evaluator_fn in evaluators:
|
|
157
|
+
scores.update(evaluator_fn(prediction_masks=pred_masks,
|
|
158
|
+
gt_masks=gt_masks,
|
|
159
|
+
prediction_scores=pred_labels,
|
|
160
|
+
gt_labels=gt_labels,
|
|
161
|
+
device = self.device))
|
|
162
|
+
|
|
163
|
+
for key in scores:
|
|
164
|
+
self.logger.info(f'{key} is: {scores[key]:.4f}')
|
|
165
|
+
|
|
166
|
+
if best_metrics == {}:
|
|
167
|
+
best_metrics = scores
|
|
168
|
+
for key in scores:
|
|
169
|
+
self.logger.info(f'--->new best {key} is: {scores[key]:.4f}')
|
|
170
|
+
self.save_checkpoint(checkpoint_path)
|
|
171
|
+
else:
|
|
172
|
+
if 'image_auroc' in scores:
|
|
173
|
+
if scores['image_auroc'] > best_metrics['image_auroc']:
|
|
174
|
+
best_metrics = scores
|
|
175
|
+
for key in scores:
|
|
176
|
+
self.logger.info(f'--->new best {key} is: {scores[key]:.4f}')
|
|
177
|
+
self.save_checkpoint(checkpoint_path)
|
|
178
|
+
self.early_stop_cur = self.early_stop_epochs
|
|
179
|
+
elif scores['image_auroc'] == best_metrics['image_auroc'] and get_avg_score(scores) > get_avg_score(best_metrics):
|
|
180
|
+
best_metrics = scores
|
|
181
|
+
for key in scores:
|
|
182
|
+
self.logger.info(f'--->new best {key} is: {scores[key]:.4f}')
|
|
183
|
+
self.save_checkpoint(checkpoint_path)
|
|
184
|
+
self.early_stop_cur = self.early_stop_epochs
|
|
185
|
+
else:
|
|
186
|
+
self.early_stop_cur -= 1
|
|
187
|
+
else:
|
|
188
|
+
if get_avg_score(scores) > get_avg_score(best_metrics):
|
|
189
|
+
best_metrics = scores
|
|
190
|
+
for key in scores:
|
|
191
|
+
self.logger.info(f'--->new best {key} is: {scores[key]:.4f}')
|
|
192
|
+
self.save_checkpoint(checkpoint_path)
|
|
193
|
+
self.early_stop_cur = self.early_stop_epochs
|
|
194
|
+
else:
|
|
195
|
+
self.early_stop_cur -= 1
|
|
196
|
+
if self.early_stop_cur >= 0:
|
|
197
|
+
self.logger.info(f'Early stop cur is: {self.early_stop_cur}')
|
|
198
|
+
if self.early_stop_cur == 0:
|
|
199
|
+
self.logger.info(f'Early stop !!')
|
|
200
|
+
return best_metrics
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@staticmethod
|
|
204
|
+
def post_processing(patch_segmentations: numpy.ndarray,
|
|
205
|
+
thumbnail_segmentations: numpy.ndarray = None,
|
|
206
|
+
is_normalize = False, gaussian_filter = True):
|
|
207
|
+
r"""
|
|
208
|
+
This method aggregates high-resolution and low-resolution detection results and performs post-processing.
|
|
209
|
+
Args
|
|
210
|
+
patch_segmentations (numpy.ndarray): High-resolution detection scores. Shape [B,H,W]
|
|
211
|
+
thumbnail_segmentations (numpy.ndarray): Low-resolution detection scores. Shape [B,H_low,W_low]
|
|
212
|
+
is_normalize: Normalize or not
|
|
213
|
+
gaussian_filter: Gaussian Filter or not
|
|
214
|
+
return:
|
|
215
|
+
FINAL detection scores. Shape [B,H,W]
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
if thumbnail_segmentations is not None:
|
|
219
|
+
thumbnail_segmentations = F.interpolate(torch.tensor(thumbnail_segmentations).unsqueeze(1),
|
|
220
|
+
size=(patch_segmentations.shape[1], patch_segmentations.shape[2]),
|
|
221
|
+
mode="bilinear",
|
|
222
|
+
align_corners=False).squeeze(1).numpy()
|
|
223
|
+
segmentations = np.where(patch_segmentations >= thumbnail_segmentations,
|
|
224
|
+
patch_segmentations,
|
|
225
|
+
thumbnail_segmentations)
|
|
226
|
+
else:
|
|
227
|
+
segmentations = patch_segmentations
|
|
228
|
+
|
|
229
|
+
if is_normalize:
|
|
230
|
+
segmentations = cv2.normalize(segmentations, None, 0, 1, cv2.NORM_MINMAX)
|
|
231
|
+
|
|
232
|
+
if not gaussian_filter:
|
|
233
|
+
return segmentations
|
|
234
|
+
else:
|
|
235
|
+
segmentations = [ndimage.gaussian_filter(segmentation, sigma = 4) for segmentation in tqdm(segmentations, desc = 'Gaussian Filter')]
|
|
236
|
+
return np.stack(segmentations)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def patch_post_processing(self, patch_anomaly_score, eps = 1e-4):
|
|
240
|
+
if self.min_anomaly_score is None or self.max_anomaly_score is None:
|
|
241
|
+
return patch_anomaly_score
|
|
242
|
+
patch_anomaly_score = (patch_anomaly_score - self.min_anomaly_score) / (
|
|
243
|
+
self.max_anomaly_score - self.min_anomaly_score + eps)
|
|
244
|
+
return numpy.clip(patch_anomaly_score, 0, 1)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def create_dataset(self, patches: List[LRPatch], training: bool, task_name: str):
|
|
248
|
+
|
|
249
|
+
r"""
|
|
250
|
+
This method defines how data is loaded for the model by constructing a `Dataset` to create a `DataLoader` object.
|
|
251
|
+
Args
|
|
252
|
+
patches (List[LRPatch]): A set of low-resolution Patch objects.
|
|
253
|
+
training (boolean): True if training, else False.
|
|
254
|
+
task_name (str): Task Name
|
|
255
|
+
return:
|
|
256
|
+
return a torch.utils.data.Dataset object
|
|
257
|
+
"""
|
|
258
|
+
dataset = PatchDataset(patches = patches, training = training, task_name = task_name)
|
|
259
|
+
return dataset
|
|
260
|
+
|
|
261
|
+
@torch.no_grad()
|
|
262
|
+
def get_multi_resolution_fusion_embeddings(self, data) -> List[torch.Tensor]:
|
|
263
|
+
r"""
|
|
264
|
+
This method can obtain multi-resolution fusion features for patches. It is only available when `embedding` method is defined.
|
|
265
|
+
Args:
|
|
266
|
+
data: The data produced by iterating over the `DataLoader`;
|
|
267
|
+
its specific format is defined by the `Dataset` created via `create_dataset` method.
|
|
268
|
+
return:
|
|
269
|
+
Returns a list of fusion features (multi-scale features). Shape: ([B,C1,H1,W1], [B,C2,H2,W2], ..., [B,Cn,Hn,Wn]) same as 'embedding' method
|
|
270
|
+
|
|
271
|
+
"""
|
|
272
|
+
image = data['image'].to(self.device)
|
|
273
|
+
embeddings = self.embedding(image)
|
|
274
|
+
low_resolution_image_keys = [key for key in data if key.startswith('low_resolution_image')]
|
|
275
|
+
|
|
276
|
+
if len(low_resolution_image_keys) == 0:
|
|
277
|
+
return embeddings
|
|
278
|
+
else:
|
|
279
|
+
if self.fusion_weights is not None:
|
|
280
|
+
assert len(self.fusion_weights) == len(low_resolution_image_keys) + 1, "fusion_weights must be the same length as ds_factor."
|
|
281
|
+
fusion_weights = [weight / sum(self.fusion_weights) for weight in self.fusion_weights]
|
|
282
|
+
else:
|
|
283
|
+
fusion_weights = [1 / (len(low_resolution_image_keys) + 1)] * (len(low_resolution_image_keys)+1)
|
|
284
|
+
|
|
285
|
+
embeddings = [[embedding * fusion_weights[0]] for embedding in embeddings]
|
|
286
|
+
|
|
287
|
+
low_resolution_image_keys.sort(key = lambda item: int(item.split('_')[-1]))
|
|
288
|
+
|
|
289
|
+
for rs_index, low_resolution_image_key in enumerate(low_resolution_image_keys):
|
|
290
|
+
low_resolution_image = data[low_resolution_image_key].to(self.device)
|
|
291
|
+
low_resolution_index = data[low_resolution_image_key.replace('image', 'index')]
|
|
292
|
+
low_resolution_embeddings = self.embedding(low_resolution_image)
|
|
293
|
+
|
|
294
|
+
for i, low_resolution_embedding in enumerate(low_resolution_embeddings):
|
|
295
|
+
downsampling_embedding = []
|
|
296
|
+
for feature, index in zip(low_resolution_embedding, low_resolution_index):
|
|
297
|
+
feature_stride_H, feature_stride_W = self.patch_size[1] / feature.shape[1], self.patch_size[0] / feature.shape[2]
|
|
298
|
+
index = HRImageIndex.from_str(index)
|
|
299
|
+
x_start = index.x / feature_stride_W
|
|
300
|
+
y_start = index.y / feature_stride_H
|
|
301
|
+
x_end = x_start + index.width / feature_stride_W
|
|
302
|
+
y_end = y_start + index.height / feature_stride_H
|
|
303
|
+
downsampling_embedding.append(feature[:, int(y_start) : int(y_end), int(x_start) : int(x_end)])
|
|
304
|
+
try:
|
|
305
|
+
downsampling_embedding = torch.stack(downsampling_embedding)
|
|
306
|
+
except:
|
|
307
|
+
first_embedding = downsampling_embedding[0]
|
|
308
|
+
downsampling_embedding = [F.interpolate(feat.unsqueeze(0), size=(first_embedding.shape[-2], first_embedding.shape[-1]), mode='bilinear').squeeze(0)
|
|
309
|
+
for feat in downsampling_embedding[1:]]
|
|
310
|
+
|
|
311
|
+
downsampling_embedding = [first_embedding] + downsampling_embedding
|
|
312
|
+
downsampling_embedding = torch.stack(downsampling_embedding)
|
|
313
|
+
|
|
314
|
+
embeddings[i].append(fusion_weights[rs_index+1] * F.interpolate(
|
|
315
|
+
downsampling_embedding,
|
|
316
|
+
size=(embeddings[i][-1].shape[-2], embeddings[i][-1].shape[-1]),
|
|
317
|
+
mode="bilinear",
|
|
318
|
+
align_corners=False,
|
|
319
|
+
))
|
|
320
|
+
|
|
321
|
+
embeddings = [torch.sum(torch.stack(embedding), dim=0, keepdim=False) for embedding in embeddings]
|
|
322
|
+
return embeddings
|
|
323
|
+
|
|
324
|
+
def feature_dimensions(self):
|
|
325
|
+
_input = torch.ones([1, 3, self.patch_size[1], self.patch_size[0]]).to(self.device)
|
|
326
|
+
embeddings = self.embedding(_input)
|
|
327
|
+
return [embedding.shape[1] for embedding in embeddings]
|
|
328
|
+
|
|
329
|
+
@staticmethod
|
|
330
|
+
def get_image_score(segmentations, pool_size=16, batch_size = 32):
|
|
331
|
+
r"""
|
|
332
|
+
This method defines the process of obtaining image-level anomaly detection scores.
|
|
333
|
+
Args
|
|
334
|
+
segmentations (torch.Tensor): pixel-level detection scores. Shape: [B,H,W]
|
|
335
|
+
return:
|
|
336
|
+
return image-level detection score. Shape: [B]
|
|
337
|
+
"""
|
|
338
|
+
N, H, W = segmentations.shape
|
|
339
|
+
preds = torch.tensor(segmentations[:, None, ...])
|
|
340
|
+
preds = preds.split(batch_size, dim=0)
|
|
341
|
+
preds = [(
|
|
342
|
+
F.avg_pool2d(pred.cuda(), (pool_size, pool_size), stride=1).cpu().numpy()
|
|
343
|
+
) for pred in preds]
|
|
344
|
+
preds = np.concatenate(preds, axis=0)
|
|
345
|
+
return preds.reshape(N, -1).max(axis=1)
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from . import destseg, losses, model_utils
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import timm
|
|
2
|
+
import torch
|
|
3
|
+
import torch.nn as nn
|
|
4
|
+
import torch.nn.functional as F
|
|
5
|
+
|
|
6
|
+
from .model_utils import ASPP, BasicBlock, l2_normalize, make_layer
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TeacherNet(nn.Module):
|
|
10
|
+
def __init__(self):
|
|
11
|
+
super().__init__()
|
|
12
|
+
self.encoder = timm.create_model(
|
|
13
|
+
"resnet18",
|
|
14
|
+
pretrained=True,
|
|
15
|
+
features_only=True,
|
|
16
|
+
out_indices=[2, 3],
|
|
17
|
+
)
|
|
18
|
+
# freeze teacher model
|
|
19
|
+
for param in self.parameters():
|
|
20
|
+
param.requires_grad = False
|
|
21
|
+
|
|
22
|
+
def forward(self, x):
|
|
23
|
+
self.eval()
|
|
24
|
+
x2, x3 = self.encoder(x)
|
|
25
|
+
return (x2, x3)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class StudentNet(nn.Module):
|
|
29
|
+
def __init__(self, ed=True):
|
|
30
|
+
super().__init__()
|
|
31
|
+
self.ed = ed
|
|
32
|
+
if self.ed:
|
|
33
|
+
self.decoder_layer4 = make_layer(BasicBlock, 512, 512, 2)
|
|
34
|
+
self.decoder_layer3 = make_layer(BasicBlock, 512, 256, 2)
|
|
35
|
+
self.decoder_layer2 = make_layer(BasicBlock, 256, 128, 2)
|
|
36
|
+
# self.decoder_layer1 = make_layer(BasicBlock, 128, 64, 2)
|
|
37
|
+
|
|
38
|
+
for m in self.modules():
|
|
39
|
+
if isinstance(m, nn.Conv2d):
|
|
40
|
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
|
41
|
+
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
|
|
42
|
+
nn.init.constant_(m.weight, 1)
|
|
43
|
+
nn.init.constant_(m.bias, 0)
|
|
44
|
+
|
|
45
|
+
self.encoder = timm.create_model(
|
|
46
|
+
"resnet18",
|
|
47
|
+
pretrained=False,
|
|
48
|
+
features_only=True,
|
|
49
|
+
out_indices=[1, 2, 3, 4],
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
def forward(self, x):
|
|
53
|
+
x1, x2, x3, x4 = self.encoder(x)
|
|
54
|
+
if not self.ed:
|
|
55
|
+
return (x2, x3)
|
|
56
|
+
x = x4
|
|
57
|
+
b4 = self.decoder_layer4(x)
|
|
58
|
+
b3 = F.interpolate(b4, size=x3.size()[2:], mode="bilinear", align_corners=False)
|
|
59
|
+
b3 = self.decoder_layer3(b3)
|
|
60
|
+
b2 = F.interpolate(b3, size=x2.size()[2:], mode="bilinear", align_corners=False)
|
|
61
|
+
b2 = self.decoder_layer2(b2)
|
|
62
|
+
# b1 = F.interpolate(b2, size=x1.size()[2:], mode="bilinear", align_corners=False)
|
|
63
|
+
# b1 = self.decoder_layer1(b1)
|
|
64
|
+
return (b2, b3)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class SegmentationNet(nn.Module):
|
|
68
|
+
def __init__(self, inplanes=384):
|
|
69
|
+
super().__init__()
|
|
70
|
+
self.res = make_layer(BasicBlock, inplanes, 256, 2)
|
|
71
|
+
|
|
72
|
+
for m in self.modules():
|
|
73
|
+
if isinstance(m, nn.Conv2d):
|
|
74
|
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
|
75
|
+
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
|
|
76
|
+
nn.init.constant_(m.weight, 1)
|
|
77
|
+
nn.init.constant_(m.bias, 0)
|
|
78
|
+
|
|
79
|
+
self.head = nn.Sequential(
|
|
80
|
+
ASPP(256, 256, [6, 12, 18]),
|
|
81
|
+
nn.Conv2d(256, 256, 3, padding=1, bias=False),
|
|
82
|
+
nn.BatchNorm2d(256),
|
|
83
|
+
nn.ReLU(inplace=True),
|
|
84
|
+
nn.Conv2d(256, 1, 1),
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def forward(self, x):
|
|
88
|
+
x = self.res(x)
|
|
89
|
+
x = self.head(x)
|
|
90
|
+
x = torch.sigmoid(x)
|
|
91
|
+
return x
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn.functional as F
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def cosine_similarity_loss(output_de_st_list):
|
|
6
|
+
loss = 0
|
|
7
|
+
for instance in output_de_st_list:
|
|
8
|
+
_, _, h, w = instance.shape
|
|
9
|
+
loss += torch.sum(instance) / (h * w)
|
|
10
|
+
return loss
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def focal_loss(inputs, targets, alpha=-1, gamma=4, reduction="mean"):
|
|
14
|
+
inputs = inputs.float()
|
|
15
|
+
targets = targets.float()
|
|
16
|
+
ce_loss = F.binary_cross_entropy(inputs, targets, reduction="none")
|
|
17
|
+
p_t = inputs * targets + (1 - inputs) * (1 - targets)
|
|
18
|
+
loss = ce_loss * ((1 - p_t) ** gamma)
|
|
19
|
+
|
|
20
|
+
if alpha >= 0:
|
|
21
|
+
alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
|
|
22
|
+
loss = alpha_t * loss
|
|
23
|
+
|
|
24
|
+
if reduction == "mean":
|
|
25
|
+
loss = loss.mean()
|
|
26
|
+
elif reduction == "sum":
|
|
27
|
+
loss = loss.sum()
|
|
28
|
+
|
|
29
|
+
return loss
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def l1_loss(inputs, targets, reduction="mean"):
|
|
33
|
+
return F.l1_loss(inputs, targets, reduction=reduction)
|