Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scikit-learn cross validation, negative values with mean squared error

When I use the following code with Data matrix X of size (952,144) and output vector y of size (952), mean_squared_error metric returns negative values, which is unexpected. Do you have any idea?

from sklearn.svm import SVR
from sklearn import cross_validation as CV

reg = SVR(C=1., epsilon=0.1, kernel='rbf')
scores = CV.cross_val_score(reg, X, y, cv=10, scoring='mean_squared_error')

all values in scores are then negative.

like image 416
ahmethungari Avatar asked Jan 29 '14 22:01

ahmethungari


People also ask

Can MSE result in a negative value?

A standard Mean Squared Error function cannot be negative. The lowest possible value is 0, when there is no output error from any example input.

Can cross validation scores be negative?

If your target is ordered in the dataframe, such as from smallest to largest, you might get a bad fit, resulting in a negative score. Shuffling the data will fix that by causing you to build a model that represents a random sample of your data.

What is Neg_mean_squared_error?

All scorer objects follow the convention that higher return values are better than lower return values. Thus metrics which measure the distance between the model and the data, like metrics. mean_squared_error , are available as neg_mean_squared_error which return the negated value of the metric.


3 Answers

Trying to close this out, so am providing the answer that David and larsmans have eloquently described in the comments section:

Yes, this is supposed to happen. The actual MSE is simply the positive version of the number you're getting.

The unified scoring API always maximizes the score, so scores which need to be minimized are negated in order for the unified scoring API to work correctly. The score that is returned is therefore negated when it is a score that should be minimized and left positive if it is a score that should be maximized.

This is also described in sklearn GridSearchCV with Pipeline.

like image 105
AN6U5 Avatar answered Sep 28 '22 19:09

AN6U5


You can fix it by changing scoring method to "neg_mean_squared_error" as you can see below:

from sklearn.svm import SVR
from sklearn import cross_validation as CV

reg = SVR(C=1., epsilon=0.1, kernel='rbf')
scores = CV.cross_val_score(reg, X, y, cv=10, scoring='neg_mean_squared_error')
like image 24
Otacílio Maia Avatar answered Sep 28 '22 19:09

Otacílio Maia


To see what are available scoring keys use:

import sklearn
print(sklearn.metrics.SCORERS.keys())

You can either use 'r2' or 'neg_mean_squared_error'. There are lots of options based on your requirement.

like image 25
MD Rijwan Avatar answered Sep 29 '22 19:09

MD Rijwan