Skip to content

[MRG] Inherit LinearModels from _LearntSelectorMixin #4241

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

Closed
Closed
Show file tree
Hide file tree
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
36 changes: 22 additions & 14 deletions sklearn/feature_selection/from_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from ..utils.validation import NotFittedError, check_is_fitted


class _LearntSelectorMixin(TransformerMixin):
class _LearntSelectorMixin(object):
# Note because of the extra threshold parameter in transform, this does
# not naturally extend from SelectorMixin
"""Transformer mixin selecting features based on importance weights.
Expand All @@ -27,21 +27,24 @@ def transform(self, X, threshold=None):

Parameters
----------
X : array or scipy sparse matrix of shape [n_samples, n_features]
X : array or scipy sparse matrix of shape (n_samples, n_features)
The input samples.

threshold : string, float or None, optional (default=None)
The threshold value to use for feature selection. Features whose
importance is greater or equal are kept while the others are
discarded. If "median" (resp. "mean"), then the threshold value is
the median (resp. the mean) of the feature importances. A scaling
factor (e.g., "1.25*mean") may also be used. If None and if
available, the object attribute ``threshold`` is used. Otherwise,
"mean" is used by default.
threshold : string or float, optional
The threshold value to use for feature selection. Features
whose importance is greater or equal are kept while the others
are discarded.

1. If the penalty used is "l1", then the threshold value
is 1e-5 times the maximum coefficient.
2. The default threshold used otherwise is that which is
provided in the object, if not present than the mean is used.
3. The threshold provided can be a float, "mean", "median"
or multiplied by a scaling factor, such as ("1.25*mean").

Returns
-------
X_r : array of shape [n_samples, n_selected_features]
X_r : array of shape (n_samples, n_selected_features)
The input samples with only the selected features.
"""
check_is_fitted(self, ('coef_', 'feature_importances_'),
Expand All @@ -68,11 +71,16 @@ def transform(self, X, threshold=None):

# Retrieve threshold
if threshold is None:
if hasattr(self, "penalty") and self.penalty == "l1":
threshold = getattr(self, "threshold", None)

if threshold is None:
# Lasso has a l1 penalty but no penalty param.
if (hasattr(self, "penalty") and self.penalty == "l1" or
'Lasso' in self.__class__.__name__):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about ElasticNet?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should it default to median for ENet?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant that even Non-transformers, can have transform methods.

IMO, that's a contradiction, effectively. By implementing fit() and
transform(), they implement the Transformer API, and are thus transformers.
The common tests should be explicitly non-mutually-exclusive between
predictors and transformers. What sorts of tests were failing?

Having said that, I'm not sure I agree with this design and might rather
see this style of feature selection come through a wrapping meta-estimator
than a mixin.

On 12 February 2015 at 17:40, Manoj Kumar notifications@github.com wrote:

In sklearn/feature_selection/from_model.py
#4241 (comment)
:

@@ -68,11 +71,16 @@ def transform(self, X, threshold=None):

     # Retrieve threshold
     if threshold is None:
  •        if hasattr(self, "penalty") and self.penalty == "l1":
    
  •        threshold = getattr(self, "threshold", None)
    
  •    if threshold is None:
    
  •        # Lasso has a l1 penalty but no penalty param.
    
  •        if (hasattr(self, "penalty") and self.penalty == "l1" or
    
  •            'Lasso' in self.**class**.**name**):
    

Should it default to median for ENet?


Reply to this email directly or view it on GitHub
https://github.com/scikit-learn/scikit-learn/pull/4241/files#r24561488.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm. Yes that seems a better idea.

However, sorry if this question seems dumb, but is it worth writing a separate meta-estimator, to just do a masking of X corresponding to coefs, below a certain threshold value?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I see work has already been done in deprecating _LearntSelectorMixin and having a SelectfromModel estimator. How far is it from being merged?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't mean to comment on this line of code. @maheshakya tried implementing a meta-estimator version at #3011. But there are arguments in both directions.

# the natural default threshold is 0 when l1 penalty was used
threshold = getattr(self, "threshold", 1e-5)
threshold = 1e-5 * np.max(importances)
else:
threshold = getattr(self, "threshold", "mean")
threshold = "mean"

if isinstance(threshold, six.string_types):
if "*" in threshold:
Expand Down
19 changes: 17 additions & 2 deletions sklearn/feature_selection/tests/test_from_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@

from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_array_equal

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
from sklearn.linear_model import (
LogisticRegression, SGDClassifier, Lasso, LassoCV)
from sklearn.svm import LinearSVC

iris = load_iris()
Expand Down Expand Up @@ -41,3 +42,17 @@ def test_invalid_input():
clf.fit(iris.data, iris.target)
assert_raises(ValueError, clf.transform, iris.data, "gobbledigook")
assert_raises(ValueError, clf.transform, iris.data, ".5 * gobbledigook")


def test_transform_elastic_net_lasso():
"""Test that default threshold in Lasso Models ~= 0"""
rng = np.random.RandomState(0)
X, y = rng.rand(5, 5), rng.rand(5)
coef = rng.rand(5)
coef[[1, 2]] = 0.0
for model in [LassoCV(), Lasso()]:
model.fit(X, y)

# Rewrite coefficients just to check that transform works.
model.coef_ = coef
assert_array_equal(model.transform(X), X[:, [0, 3, 4]])
4 changes: 3 additions & 1 deletion sklearn/linear_model/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from ..externals import six
from ..externals.joblib import Parallel, delayed
from ..base import BaseEstimator, ClassifierMixin, RegressorMixin
from ..feature_selection.from_model import _LearntSelectorMixin
from ..utils import as_float_array, check_array
from ..utils.extmath import safe_sparse_dot
from ..utils.sparsefuncs import mean_variance_axis, inplace_column_scale
Expand Down Expand Up @@ -113,7 +114,8 @@ def center_data(X, y, fit_intercept, normalize=False, copy=True,
return X, y, X_mean, y_mean, X_std


class LinearModel(six.with_metaclass(ABCMeta, BaseEstimator)):
class LinearModel(six.with_metaclass(ABCMeta, BaseEstimator),
_LearntSelectorMixin):
"""Base class for Linear Models"""

@abstractmethod
Expand Down
3 changes: 2 additions & 1 deletion sklearn/linear_model/coordinate_descent.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from ..externals.joblib import Parallel, delayed
from ..externals import six
from ..externals.six.moves import xrange
from ..feature_selection.from_model import _LearntSelectorMixin
from ..utils.extmath import safe_sparse_dot
from ..utils.validation import check_is_fitted
from ..utils import ConvergenceWarning
Expand Down Expand Up @@ -935,7 +936,7 @@ def _path_residuals(X, y, train, test, path, path_params, alphas=None,
return this_mses


class LinearModelCV(six.with_metaclass(ABCMeta, LinearModel)):
class LinearModelCV(six.with_metaclass(ABCMeta, LinearModel), _LearntSelectorMixin):
"""Base class for iterative model fitting along a regularization path"""

@abstractmethod
Expand Down