Skip to content

Fix ImportanceWeightedScorer compatibility with deep learning models #232

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

Merged
merged 3 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
12 changes: 10 additions & 2 deletions skada/deep/tests/test_deep_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from skada.metrics import (
CircularValidation,
DeepEmbeddedValidation,
ImportanceWeightedScorer,
MixValScorer,
PredictionEntropyScorer,
SoftNeighborhoodDensity,
Expand All @@ -28,6 +29,7 @@
SoftNeighborhoodDensity(),
CircularValidation(),
MixValScorer(),
ImportanceWeightedScorer(),
],
)
def test_generic_scorer_on_deepmodel(scorer, da_dataset):
Expand Down Expand Up @@ -93,12 +95,18 @@ def test_generic_scorer(scorer, da_dataset):
assert np.all(~np.isnan(scores)), "all scores are computed"


def test_dev_cnn_features_nd(da_dataset):
@pytest.mark.parametrize(
"scorer",
[
DeepEmbeddedValidation(),
ImportanceWeightedScorer(),
],
)
def test_dev_cnn_features_nd(scorer, da_dataset):
X, y, sample_domain = da_dataset.pack_train(as_sources=["s"], as_targets=["t"])
X = np.repeat(X[..., np.newaxis], repeats=5, axis=-1) # Make it batched 2D data
X = X.astype(np.float32)

scorer = DeepEmbeddedValidation()
_, n_channels, input_size = X.shape
y_source, _ = source_target_split(y, sample_domain=sample_domain)
n_classes = len(np.unique(y_source))
Expand Down
46 changes: 30 additions & 16 deletions skada/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,6 @@ def _fit(self, X_source, X_target):
weight_estimator = KernelDensity()
self.weight_estimator_source_ = clone(weight_estimator)
self.weight_estimator_target_ = clone(weight_estimator)
X_source = X_source.reshape(X_source.shape[0], -1)
X_target = X_target.reshape(X_target.shape[0], -1)
self.weight_estimator_source_.fit(X_source)
self.weight_estimator_target_.fit(X_target)
return self
Expand All @@ -173,11 +171,14 @@ def _score(self, estimator, X, y, sample_domain=None, **params):
X_source, X_target, y_source, _ = source_target_split(
X, y, sample_domain=sample_domain
)
X_source = X_source.reshape(X_source.shape[0], -1)
X_target = X_target.reshape(X_target.shape[0], -1)
self._fit(X_source, X_target)
ws = self.weight_estimator_source_.score_samples(X_source)
wt = self.weight_estimator_target_.score_samples(X_source)

# Reshape to 2D vectors
X_source_reshaped = X_source.reshape(X_source.shape[0], -1)
X_target_reshaped = X_target.reshape(X_target.shape[0], -1)

self._fit(X_source_reshaped, X_target_reshaped)
ws = self.weight_estimator_source_.score_samples(X_source_reshaped)
wt = self.weight_estimator_target_.score_samples(X_source_reshaped)
weights = np.exp(wt - ws)

if weights.sum() != 0:
Expand All @@ -186,15 +187,28 @@ def _score(self, estimator, X, y, sample_domain=None, **params):
warnings.warn("All weights are zero. Using uniform weights.")
weights = np.ones_like(weights) / len(weights)

return self._sign * scorer(
estimator,
X_source,
y_source,
sample_domain=sample_domain[sample_domain >= 0],
sample_weight=weights,
allow_source=True,
**params,
)
if not isinstance(estimator, BaseEstimator):
# Deep estimators dont accept allow_source parameter
score = scorer(
estimator,
X_source,
y_source,
sample_domain=sample_domain[sample_domain >= 0],
sample_weight=weights,
**params,
)
else:
score = scorer(
estimator,
X_source,
y_source,
sample_domain=sample_domain[sample_domain >= 0],
sample_weight=weights,
allow_source=True,
**params,
)

return self._sign * score


class PredictionEntropyScorer(_BaseDomainAwareScorer):
Expand Down
Loading