9951 explained code solutions for 126 technologies


python-scikit-learnHow to use K fold cross validation


from sklearn import datasets, linear_model
from sklearn.model_selection import cross_val_score
diabetes = datasets.load_diabetes()
X = diabetes.data[:150]
y = diabetes.target[:150]
lasso = linear_model.Lasso()

cvs = cross_val_score(lasso, X, y, cv=3)ctrl + c
from sklearn import

import module from scikit-learn

datasets.load_diabetes

loads sample diabetes database

linear_model.Lasso

creates Lasso model

cross_val_score(

evaluates a score by cross-validation

lasso

model to use for cross-validation

cv=3

number of folds (3 in our case) to use


Usage example

from sklearn import datasets, linear_model
from sklearn.model_selection import cross_val_score
diabetes = datasets.load_diabetes()
X = diabetes.data[:150]
y = diabetes.target[:150]
lasso = linear_model.Lasso()

cvs = cross_val_score(lasso, X, y, cv=3)
print(cvs)
output
[0.3315057  0.08022103 0.03531816]