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

Aligned CD train-test functionality #624

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Changes from all commits
Commits
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
24 changes: 16 additions & 8 deletions pyod/models/cd.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
"""Cook's distance outlier detection (CD)
"""

# Author: D Kulik
# Author: Daniel Kulik
# License: BSD 2 clause

import copy

import numpy as np
from sklearn.linear_model import LinearRegression
Expand Down Expand Up @@ -46,7 +47,7 @@ def _Cooks_dist(X, y, model):
mse = np.dot(residuals, residuals) / df

# Compute Cook's distance
if (mse != 0) or (mse != np.nan):
if (mse != 0) & (mse != np.nan):
residuals_studentized = residuals / np.sqrt(mse) / np.sqrt(
1 - leverage)
distance_ = residuals_studentized ** 2 / X.shape[1]
Expand All @@ -60,7 +61,7 @@ def _Cooks_dist(X, y, model):
return distance_


def _process_distances(X, model):
def _process_distances(X, models):
"""Calculated the mean Cook's distances for
each feature

Expand All @@ -79,8 +80,8 @@ def _process_distances(X, model):
"""

distances_ = []
model_list = []
for i in range(X.shape[1]):
mod = model

# Extract new X and y inputs
exp = np.delete(X.copy(), i, axis=1)
Expand All @@ -89,7 +90,14 @@ def _process_distances(X, model):
exp = exp.reshape(-1, 1) if exp.ndim == 1 else exp

# Fit the model
mod.fit(exp, resp)
if len(models)==1:
mod = copy.deepcopy(models[0])
mod.fit(exp, resp)

else:
mod = models[i]

model_list.append(mod)

# Get Cook's Distance
distance_ = _Cooks_dist(exp, resp, mod)
Expand All @@ -98,7 +106,7 @@ def _process_distances(X, model):

distances_ = np.nanmean(distances_, axis=0)

return distances_
return distances_, model_list


class CD(BaseDetector):
Expand Down Expand Up @@ -167,7 +175,7 @@ def fit(self, X, y=None):
self._set_n_classes(y)

# Get Cook's distance
distances_ = _process_distances(X, self.model)
distances_, self._models = _process_distances(X, [self.model])

self.decision_scores_ = distances_

Expand Down Expand Up @@ -197,6 +205,6 @@ def decision_function(self, X):
X = check_array(X)

# Get Cook's distance
distances_ = _process_distances(X, self.model)
distances_, _ = _process_distances(X, self._models)

return distances_
Loading