-
Notifications
You must be signed in to change notification settings - Fork 705
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
Load model did not work correctly as DFMModel did not inherit #5
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,107 +16,135 @@ | |
# See the License for the specific language governing permissions | ||
# and limitations under the License. | ||
|
||
import numpy as np | ||
import math | ||
|
||
import torch | ||
from sklearn.decomposition import PCA | ||
from torch import Tensor, nn | ||
|
||
from anomalib.core.model.dynamic_module import DynamicBufferModule | ||
from anomalib.core.model.pca import PCA | ||
|
||
|
||
class SingleclassGaussian: | ||
class SingleClassGaussian(DynamicBufferModule): | ||
""" | ||
Model Gaussian distribution over a set of points | ||
""" | ||
|
||
def __init__(self): | ||
self.mean_vec = None | ||
self.u_mat = None | ||
self.sigma_mat = None | ||
super().__init__() | ||
self.register_buffer("mean_vec", Tensor()) | ||
self.register_buffer("u_mat", Tensor()) | ||
self.register_buffer("sigma_mat", Tensor()) | ||
|
||
def fit(self, dataset): | ||
self.mean_vec: Tensor | ||
self.u_mat: Tensor | ||
self.sigma_mat: Tensor | ||
|
||
def fit(self, dataset: Tensor) -> None: | ||
""" | ||
Fit a Gaussian model to dataset X. | ||
Covariance matrix is not calculated directly using: | ||
C = X.X^T | ||
Instead, it is represented in terms of the Singular Value Decomposition of X: | ||
X = U.S.V^T | ||
Hence, | ||
C = U.S^2.U^T | ||
This simplifies the calculation of the log-likelihood without requiring full matrix inversion. | ||
Covariance matrix is not calculated directly using: | ||
C = X.X^T | ||
Instead, it is represented in terms of the Singular Value Decomposition of X: | ||
X = U.S.V^T | ||
Hence, | ||
C = U.S^2.U^T | ||
This simplifies the calculation of the log-likelihood without requiring full matrix inversion. | ||
|
||
Args: | ||
dataset: Input dataset to fit the model. | ||
dataset: torch.Tensor: | ||
|
||
Returns: | ||
|
||
dataset (Tensor): Input dataset to fit the model. | ||
""" | ||
|
||
num_samples = dataset.shape[1] | ||
self.mean_vec = torch.mean(dataset, dim=1) | ||
data_centered = (dataset - self.mean_vec.reshape(-1, 1)) / torch.sqrt(torch.Tensor([num_samples])) | ||
data_centered = (dataset - self.mean_vec.reshape(-1, 1)) / math.sqrt(num_samples) | ||
self.u_mat, self.sigma_mat, _ = torch.linalg.svd(data_centered, full_matrices=False) | ||
|
||
def score_samples(self, features): | ||
def score_samples(self, features: Tensor) -> Tensor: | ||
""" | ||
Compute the NLL (negative log likelihood) scores | ||
|
||
Args: | ||
x: semantic features on which density modeling is performed. | ||
features (Tensor): semantic features on which density modeling is performed. | ||
|
||
Returns: | ||
nll: numpy array of scores | ||
nll (Tensor): Torch tensor of scores | ||
|
||
""" | ||
features_transformed = torch.matmul(features - self.mean_vec, self.u_mat / self.sigma_mat) | ||
nll = torch.sum(features_transformed * features_transformed, dim=1) + 2 * np.sum(np.log(self.sigma_mat)) | ||
nll = torch.sum(features_transformed * features_transformed, dim=1) + 2 * torch.sum(torch.log(self.sigma_mat)) | ||
return nll | ||
|
||
def forward(self, dataset: Tensor) -> None: | ||
""" | ||
Provides the same functionality as `fit`. Transforms the input dataset based on singular values calculated | ||
earlier. | ||
|
||
Args: | ||
dataset (Tensor): Input dataset | ||
""" | ||
self.fit(dataset) | ||
|
||
|
||
class DFMModel: | ||
class DFMModel(nn.Module): | ||
""" | ||
Model for the DFM algorithm | ||
|
||
Args: | ||
n_comps (float, optional): Ratio from which number of components for PCA are calculated. Defaults to 0.97. | ||
score_type (str, optional): Scoring type. Options are `fre` and `nll`. Defaults to "fre". | ||
""" | ||
|
||
def __init__(self, n_comps: float = 0.97, score_type: str = "fre"): | ||
super().__init__() | ||
self.n_components = n_comps | ||
self.pca_model = PCA(n_components=self.n_components) | ||
self.gaussian_model = SingleclassGaussian() | ||
self.gaussian_model = SingleClassGaussian() | ||
self.score_type = score_type | ||
|
||
def fit(self, dataset: torch.Tensor): | ||
def fit(self, dataset: Tensor) -> None: | ||
""" | ||
Fit a pca transformation and a Gaussian model to dataset | ||
|
||
Args: | ||
dataset: Input dataset to fit the model. | ||
dataset: torch.Tensor: | ||
|
||
Returns: | ||
|
||
dataset (Tensor): Input dataset to fit the model. | ||
""" | ||
|
||
selected_features = dataset.cpu().numpy() | ||
selected_features = dataset | ||
samet-akcay marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.pca_model.fit(selected_features) | ||
features_reduced = torch.Tensor(self.pca_model.transform(selected_features)) | ||
features_reduced = self.pca_model.transform(selected_features) | ||
samet-akcay marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.gaussian_model.fit(features_reduced.T) | ||
|
||
def score(self, sem_feats: torch.Tensor) -> np.array: | ||
def score(self, sem_feats: Tensor) -> Tensor: | ||
""" | ||
Compute the PCA-based feature reconstruction error (FRE) scores and | ||
the Gaussian density-based NLL scores | ||
|
||
Args: | ||
sem_feats: semantic features on which PCA and density modeling is performed. | ||
sem_feats (torch.Tensor): semantic features on which PCA and density modeling is performed. | ||
|
||
Returns: | ||
score: numpy array of scores | ||
score (Tensor): numpy array of scores | ||
|
||
""" | ||
feats_orig = sem_feats.cpu().numpy() | ||
feats_orig = sem_feats | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Similarly, this could be |
||
feats_projected = self.pca_model.transform(feats_orig) | ||
if self.score_type == "nll": | ||
score = self.gaussian_model.score_samples(feats_projected) | ||
elif self.score_type == "fre": | ||
feats_reconstructed = self.pca_model.inverse_transform(feats_projected) | ||
score = np.sum(np.square(feats_orig - feats_reconstructed), axis=1) | ||
score = torch.sum(torch.square(feats_orig - feats_reconstructed), dim=1) | ||
else: | ||
raise ValueError(f"unsupported score type: {self.score_type}") | ||
|
||
return score | ||
|
||
def forward(self, dataset: Tensor) -> None: | ||
""" | ||
Provides the same functionality as `fit`. Transforms the input dataset based on singular values calculated | ||
earlier. | ||
|
||
Args: | ||
dataset (Tensor): Input dataset | ||
""" | ||
self.fit(dataset) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should we move this to
anomalib/core/model/single_class_gaussian.py
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If it's used in multiple algos, then I'd agree. If this is the only algo, then it could stay here for now
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think there are several other classes in
core/model
that are also only used in one algo.KDE
is only used by DFKDE andMultivariateGaussian
is only used by PADIM. So for consistency I would be in favor of movingSingleClassGaussian
there as well. But if you disagree I'm also fine with keeping it here.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When I was working on patchcore, I've moved all patchcore related models under patchcore directory.
If we want to keep them in one place, we could then move patchcore stuff there too.
In addition, I think we need to move them from
anomalib.core.models
toanomalib.models.utils
oranomalib.utils.models
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In that case let's create a ticket for this.