Skip to content

Commit

Permalink
Fixed linting errors (#914)
Browse files Browse the repository at this point in the history
* Fixed mypy errors

* Minor refactoring
  • Loading branch information
RobertSamoilescu authored Dec 11, 2024
1 parent dd77a2a commit 474853b
Show file tree
Hide file tree
Showing 10 changed files with 20 additions and 20 deletions.
6 changes: 3 additions & 3 deletions alibi_detect/cd/keops/learned_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def score(self, x: Union[np.ndarray, list]) -> Tuple[float, float, float]:

idx_threshold = int(self.p_val * len(mmd2_permuted))
distance_threshold = torch.sort(mmd2_permuted, descending=True).values[idx_threshold]
return p_val.numpy().item(), mmd2.numpy().item(), distance_threshold.numpy()
return p_val.numpy().item(), mmd2.numpy().item(), distance_threshold.numpy().item()

def _mmd2(self, x_all: Union[list, torch.Tensor], perms: List[torch.Tensor], m: int, n: int) \
-> Tuple[torch.Tensor, torch.Tensor]:
Expand Down Expand Up @@ -341,5 +341,5 @@ def trainer(
optimizer.step() # type: ignore
if verbose == 1:
loss_ma = loss_ma + (loss.item() - loss_ma) / (step + 1)
dl.set_description(f'Epoch {epoch + 1}/{epochs}')
dl.set_postfix(dict(loss=loss_ma))
dl.set_description(f'Epoch {epoch + 1}/{epochs}') # type: ignore[union-attr]
dl.set_postfix(dict(loss=loss_ma)) # type: ignore[union-attr]
2 changes: 1 addition & 1 deletion alibi_detect/cd/keops/mmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,4 +182,4 @@ def score(self, x: Union[np.ndarray, list]) -> Tuple[float, float, float]:
# compute distance threshold
idx_threshold = int(self.p_val * len(mmd2_permuted))
distance_threshold = torch.sort(mmd2_permuted, descending=True).values[idx_threshold]
return p_val.numpy().item(), mmd2.numpy().item(), distance_threshold.numpy()
return p_val.numpy().item(), mmd2.numpy().item(), distance_threshold.numpy().item()
2 changes: 1 addition & 1 deletion alibi_detect/cd/pytorch/context_aware.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def score(self, # type: ignore[override]
idx_threshold = int(self.p_val * len(permuted_stats))
distance_threshold = torch.sort(permuted_stats, descending=True).values[idx_threshold]

return p_val.numpy().item(), stat.numpy().item(), distance_threshold.numpy(), coupling
return p_val.numpy().item(), stat.numpy().item(), distance_threshold.numpy().item(), coupling

def _cmmd(self, K: torch.Tensor, L: torch.Tensor, bools: torch.Tensor, L_held: torch.Tensor = None) \
-> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
Expand Down
6 changes: 3 additions & 3 deletions alibi_detect/cd/pytorch/learned_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def score(self, x: Union[np.ndarray, list]) -> Tuple[float, float, float]:

idx_threshold = int(self.p_val * len(mmd2_permuted))
distance_threshold = torch.sort(mmd2_permuted, descending=True).values[idx_threshold]
return p_val.numpy().item(), mmd2.numpy().item(), distance_threshold.numpy()
return p_val.numpy().item(), mmd2.numpy().item(), distance_threshold.numpy().item()

@staticmethod
def trainer(
Expand Down Expand Up @@ -256,5 +256,5 @@ def trainer(
optimizer.step() # type: ignore
if verbose == 1:
loss_ma = loss_ma + (loss.item() - loss_ma) / (step + 1)
dl.set_description(f'Epoch {epoch + 1}/{epochs}')
dl.set_postfix(dict(loss=loss_ma))
dl.set_description(f'Epoch {epoch + 1}/{epochs}') # type: ignore[union-attr]
dl.set_postfix(dict(loss=loss_ma)) # type: ignore[union-attr]
2 changes: 1 addition & 1 deletion alibi_detect/cd/pytorch/lsdd.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,4 @@ def score(self, x: Union[np.ndarray, list]) -> Tuple[float, float, float]:

idx_threshold = int(self.p_val * len(lsdd_permuted))
distance_threshold = torch.sort(lsdd_permuted, descending=True).values[idx_threshold]
return float(p_val.cpu()), float(lsdd.cpu().numpy()), distance_threshold.cpu().numpy()
return p_val.cpu().item(), lsdd.cpu().numpy().item(), distance_threshold.cpu().numpy().item()
2 changes: 1 addition & 1 deletion alibi_detect/cd/pytorch/mmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,4 @@ def score(self, x: Union[np.ndarray, list]) -> Tuple[float, float, float]:
# compute distance threshold
idx_threshold = int(self.p_val * len(mmd2_permuted))
distance_threshold = torch.sort(mmd2_permuted, descending=True).values[idx_threshold]
return p_val.numpy().item(), mmd2.numpy().item(), distance_threshold.numpy()
return p_val.numpy().item(), mmd2.numpy().item(), distance_threshold.numpy().item()
8 changes: 5 additions & 3 deletions alibi_detect/models/pytorch/embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ def hidden_state_embedding(hidden_states: torch.Tensor, layers: List[int],
-------
Tensor with embeddings.
"""
hs = [hidden_states[layer][:, 0:1, :] if use_cls else hidden_states[layer] for layer in layers]
hs = torch.cat(hs, dim=1) # type: ignore
y = hs.mean(dim=1) if reduce_mean else hs # type: ignore
hs = torch.cat(
[hidden_states[layer][:, 0:1, :] if use_cls else hidden_states[layer] for layer in layers],
dim=1
)
y = hs.mean(dim=1) if reduce_mean else hs
return y


Expand Down
4 changes: 2 additions & 2 deletions alibi_detect/models/pytorch/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,5 @@ def trainer(
optimizer.step() # type: ignore
if verbose == 1:
loss_ma = loss_ma + (loss.item() - loss_ma) / (step + 1)
dl.set_description(f'Epoch {epoch + 1}/{epochs}')
dl.set_postfix(dict(loss_ma=loss_ma))
dl.set_description(f'Epoch {epoch + 1}/{epochs}') # type: ignore[union-attr]
dl.set_postfix(dict(loss_ma=loss_ma)) # type: ignore[union-attr]
6 changes: 2 additions & 4 deletions alibi_detect/od/pytorch/svm.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,14 +143,13 @@ def fit( # type: ignore[override]
- converged: `bool` indicating whether training converged.
- n_iter: number of iterations performed.
"""
x_nys = self.nystroem.fit(x_ref).transform(x_ref)
x_nys = self.nystroem.fit(x_ref).transform(x_ref).cpu().numpy()
self.svm = SGDOneClassSVM(
tol=tol,
max_iter=max_iter,
verbose=verbose,
nu=self.nu
)
x_nys = x_nys.cpu().numpy()
self.svm = self.svm.fit(x_nys)
self._set_fitted()
return {
Expand Down Expand Up @@ -194,8 +193,7 @@ def score(self, x: torch.Tensor) -> torch.Tensor:
Raised if method called and detector has not been fit.
"""
self.check_fitted()
x_nys = self.nystroem.transform(x)
x_nys = x_nys.cpu().numpy()
x_nys = self.nystroem.transform(x).cpu().numpy()
coef_ = self.svm.coef_ / (self.svm.coef_ ** 2).sum()
x_nys = self.svm._validate_data(x_nys, accept_sparse="csr", reset=False)
result = safe_sparse_dot(x_nys, coef_.T, dense_output=True).ravel()
Expand Down
2 changes: 1 addition & 1 deletion alibi_detect/utils/perturbation.py
Original file line number Diff line number Diff line change
Expand Up @@ -895,7 +895,7 @@ def jpeg_compression(x: np.ndarray, strength: float, xrange: tuple = None) -> np
if xrange[0] != 0 or xrange[1] != 255:
x = (x - xrange[0]) / (xrange[1] - xrange[0]) * 255

x = Image.fromarray(x.astype('uint8'), mode='RGB')
x = Image.fromarray(x.astype('uint8'), mode='RGB') # type: ignore[assignment]
output = BytesIO()
x.save(output, 'JPEG', quality=strength) # type: ignore[attr-defined] # TODO: allow redefinition
x_image = Image.open(output)
Expand Down

0 comments on commit 474853b

Please sign in to comment.