Skip to content
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: 36 additions & 0 deletions sklearn/linear_model/coordinate_descent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,7 @@ def fit(self, X, y):

self.l1_ratio_ = best_l1_ratio
self.alpha_ = best_alpha

if self.alphas is None:
self.alphas_ = np.asarray(alphas)
if n_l1_ratio == 1:
Expand All @@ -1168,6 +1169,10 @@ def fit(self, X, y):
else:
self.alphas_ = np.asarray(alphas[0])

self.mse_path_ = np.squeeze(all_mse_paths)
self.best_score_ = best_mse
self.best_params_ = {'alpha': best_alpha, 'l1_ratio': best_l1_ratio}

# Refit the model with the parameters selected
common_params = dict((name, value)
for name, value in self.get_params().items()
Expand All @@ -1184,6 +1189,7 @@ def fit(self, X, y):
self.intercept_ = model.intercept_
self.dual_gap_ = model.dual_gap_
self.n_iter_ = model.n_iter_
self.best_estimator_ = model
return self


Expand Down Expand Up @@ -1295,6 +1301,20 @@ class LassoCV(LinearModelCV, RegressorMixin):
number of iterations run by the coordinate descent solver to reach
the specified tolerance for the optimal alpha.

``best_estimator_`` : estimator
Estimator that was chosen by the search, i.e. estimator
which gave the lowest mean squared error on the left out data. The
estimator will be of type ElasticNet.

``best_score_`` : float
Score of ``best_estimator_`` on the left out data
(i.e. best mean squared error). Note that by default GridSearchCV
computes ``best_score_`` based on the R^2, not the mean squared error,
which will account for differences between the two.

``best_params_`` : dict
Parameter setting that gave the best results on the left out data.

Notes
-----
See examples/linear_model/lasso_path_with_crossvalidation.py
Expand All @@ -1310,6 +1330,8 @@ class LassoCV(LinearModelCV, RegressorMixin):
LassoLars
Lasso
LassoLarsCV
ElasticNetCV
ElasticNet
"""
path = staticmethod(lasso_path)

Expand Down Expand Up @@ -1442,6 +1464,19 @@ class ElasticNetCV(LinearModelCV, RegressorMixin):
number of iterations run by the coordinate descent solver to reach
the specified tolerance for the optimal alpha.

``best_estimator_`` : estimator
Estimator that was chosen by the search, i.e. estimator
which gave the lowest mean squared error on the left out data.

``best_score_`` : float
Score of ``best_estimator_`` on the left out data
(i.e. best mean squared error). Note that by default GridSearchCV
computes ``best_score_`` based on the R^2, not the mean squared error,
which will account for differences between the two.

``best_params_`` : dict
Parameter setting that gave the best results on the left out data.

Notes
-----
See examples/linear_model/lasso_path_with_crossvalidation.py
Expand Down Expand Up @@ -1471,6 +1506,7 @@ class ElasticNetCV(LinearModelCV, RegressorMixin):
--------
enet_path
ElasticNet
LassoCV

"""
path = staticmethod(enet_path)
Expand Down
34 changes: 33 additions & 1 deletion sklearn/linear_model/least_angle.py
Original file line number Diff line number Diff line change
Expand Up @@ -1034,9 +1034,18 @@ class LarsCV(Lars):
n_iter_ : array-like or int
the number of iterations run by Lars with the optimal alpha.

``best_score_`` : float
Best cross validation score on the left out data
(i.e. best mean squared error). Note that by default GridSearchCV
computes ``best_score_`` based on the R^2, not the mean squared error,
which will account for differences between the two.

``best_params_`` : dict
Parameter setting that gave the best results on the left out data.

See also
--------
lars_path, LassoLars, LassoLarsCV
lars_path, LassoLars, LassoLarsCV, Lasso, LassoCV
"""

method = 'lar'
Expand Down Expand Up @@ -1119,11 +1128,14 @@ def fit(self, X, y):
# Select the alpha that minimizes left-out error
i_best_alpha = np.argmin(mse_path.mean(axis=-1))
best_alpha = all_alphas[i_best_alpha]
best_mse = mse_path[i_best_alpha]

# Store our parameters
self.alpha_ = best_alpha
self.cv_alphas_ = all_alphas
self.cv_mse_path_ = mse_path
self.best_score_ = best_mse
self.best_params_ = {'alpha': best_alpha}

# Now compute the full model
# it will call a lasso internally when self if LassoLarsCV
Expand Down Expand Up @@ -1235,6 +1247,15 @@ class LassoLarsCV(LarsCV):
n_iter_ : array-like or int
the number of iterations run by Lars with the optimal alpha.

``best_score_`` : float
Best cross validation score on the left out data
(i.e. best mean squared error). Note that by default GridSearchCV
computes ``best_score_`` based on the R^2, not the mean squared error,
which will account for differences between the two.

``best_params_`` : dict
Parameter setting that gave the best results on the left out data.

Notes
-----

Expand Down Expand Up @@ -1338,6 +1359,15 @@ class LassoLarsIC(LassoLars):
alphas. The alpha which has the smallest information criteria
is chosen.

``best_score_`` : float

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think we don't need the ticks here any more.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@amueller More detail on this, please ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I suppose that Andreas Mueller should answer this but it seems what he meant is the ticks `` are not needed. It is to bold the text., but now it is done by default for the attributes. Hope it helps

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@maniteja123 , yeah. Made sense. thanks!

Best cross validation score on the left out data
(i.e. best mean squared error). Note that by default GridSearchCV
computes ``best_score_`` based on the R^2, not the mean squared error,
which will account for differences between the two.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't like the last part of the sentence. The difference between which two? GridSearchCV with a different score? I would just remove the "which will accout" part.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[on all three docstrings]


``best_params_`` : dict
Parameter setting that gave the best results on the left out data.

Examples
--------
>>> from sklearn import linear_model
Expand Down Expand Up @@ -1441,4 +1471,6 @@ def fit(self, X, y, copy_X=True):
self.alpha_ = alphas_[n_best]
self.coef_ = coef_path_[:, n_best]
self._set_intercept(Xmean, ymean, Xstd)
self.best_score_ = mean_squared_error
self.best_params_ = {'alpha': self.alpha_}
return self
36 changes: 36 additions & 0 deletions sklearn/linear_model/tests/test_coordinate_descent.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import TempMemmap

from sklearn.cross_validation import KFold

from sklearn.grid_search import GridSearchCV

from sklearn.linear_model.coordinate_descent import Lasso, \
LassoCV, ElasticNet, ElasticNetCV, MultiTaskLasso, MultiTaskElasticNet, \
MultiTaskElasticNetCV, MultiTaskLassoCV, lasso_path, enet_path
Expand Down Expand Up @@ -674,3 +678,35 @@ def test_lasso_non_float_y():
clf_float = model(fit_intercept=False)
clf_float.fit(X, y_float)
assert_array_equal(clf.coef_, clf_float.coef_)


def test_lasso_cv_best_score():
X, y, X_test, y_test = build_dataset(n_features=20)
grid_cv = GridSearchCV(
Lasso(), {'alpha': [0.1, 1., 10.]}, scoring='mean_squared_error',
cv=KFold(3)
).fit(X, y)
lasso_cv = LassoCV(alphas=[0.1, 1., 10.], cv=KFold(3)).fit(X, y)
assert_equal(lasso_cv.best_score_, -1 * grid_cv.best_score_)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the -1 makes me die a little inside.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

You have to become a bit more pragmatic

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't find user-suprising behaviors to be pragmatic.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@amueller simply awful, I totally agree with you.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

At the risk of not looking at the source code before hand, how does gridsearch know if its the error or accuracy?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this is a sort-of long-standing api issue... #5023 we're gonna decide this sprint which way to go I think.
[GridSearchCV currently always maximizes, and the scorer flips the sign of mse]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I did not read the entire issue yet, but MLlib solves it by having an explicit flag, apache/spark#8290

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Yeah they introduced that in the last release. That was the way I initially did it, then we changed it to flipping the sign. We'll have a discussion tomorrow.



def test_elasticnet_cv_best_score():
X, y, X_test, y_test = build_dataset(n_features=20)
grid_cv = GridSearchCV(
ElasticNet(),
{'alpha': [0.1, 1., 10.], 'l1_ratio': [0.1, 0.5, 0.9, 0.95, 0.99]},
scoring='mean_squared_error', cv=KFold(3)
).fit(X, y)
enet_cv = ElasticNetCV(alphas=[0.1, 1., 10.], cv=KFold(3)).fit(X, y)
assert_equal(enet_cv.best_score_, -1 * grid_cv.best_score_)


def test_lasso_cv_l1ratio():
X, y, X_test, y_test = build_dataset(n_features=20)
lasso_cv = LassoCV().fit(X, y)
assert_equal(lasso_cv.best_params_['l1_ratio'], 1)


if __name__ == '__main__':
import nose
nose.runmodule()
6 changes: 4 additions & 2 deletions sklearn/linear_model/tests/test_ridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,8 +537,10 @@ def test_class_weights_cv():


def test_ridgecv_store_cv_values():
# Test _RidgeCV's store_cv_values attribute.
rng = rng = np.random.RandomState(42)
"""
Test _RidgeCV's store_cv_values attribute.
"""
rng = np.random.RandomState(42)

n_samples = 8
n_features = 5
Expand Down