Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predicted values of each fold in K-Fold Cross Validation in sklearn

I have performed 10-fold cross validation on a dataset that I have using python sklearn,

result = cross_val_score(best_svr, X, y, cv=10, scoring='r2')
print(result.mean())

I have been able to get the mean value of the r2 score as the final result. I want to know if there is a way to print out the predicted values for each fold( in this case 10 sets of values).

like image 990
Krishi H Avatar asked Aug 07 '18 04:08

Krishi H


2 Answers

I believe you are looking for the cross_val_predict function.

like image 52
jh314 Avatar answered Sep 27 '22 17:09

jh314


A late answer, just to add to @jh314, cross_val_predict does return all the predictions, but we do not know which fold each prediction belongs to. To do that, we need to provide the folds, instead of an integer:

import seaborn as sns
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_predict, StratifiedKFold 

iris = sns.load_dataset('iris')
X=iris.iloc[:,:4]
y=(iris['species'] == "versicolor").astype('int')

rfc = RandomForestClassifier()
skf = StratifiedKFold(n_splits=10,random_state=111,shuffle=True)

pred = cross_val_predict(rfc, X, y, cv=skf)

And now we iterate through the Kfold object and pull out the predictions corresponding to each fold:

fold_pred = [pred[j] for i, j in skf.split(X,y)]
fold_pred

[array([0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0]),
 array([0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0]),
 array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1]),
 array([0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]),
 array([0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0]),
 array([0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0]),
 array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]),
 array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]),
 array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0]),
 array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0])]
like image 34
StupidWolf Avatar answered Sep 27 '22 17:09

StupidWolf