Show Sidebar Hide Sidebar

Cross Validated Predictions in Scikit-learn

How to make Cross Validated Predictions in Python with Plotly.

Cross-Validation is a technique used in model selection to better estimate the test error of a predictive model. The idea behind cross-validation is to create a number of partitions of sample observations, known as the validation sets, from the training data set. This example shows how to use cross_val_predict to visualize prediction errors.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!


The tutorial below imports cross_val_predict and linear_model.

In [1]:
import plotly.plotly as py
import plotly.graph_objs as go 

from sklearn import datasets
from sklearn.cross_validation import cross_val_predict
from sklearn import linear_model


In [2]:
lr = linear_model.LinearRegression()
boston = datasets.load_boston()
y =

# cross_val_predict returns an array of the same size as `y` where each entry
# is a prediction obtained by cross validated:

predicted = cross_val_predict(lr,, y, cv=10)

Plotting Cross Validated Predictions

In [3]:
trace1 = go.Scatter(x=y, y=predicted, mode='markers',
                    marker = dict(size=8,
                                  color='rgb(0, 0, 255)',
                                    color='rgb(0, 0, 0)'))
trace2 = go.Scatter(x=[y.min(), y.max()],y=[y.min(), y.max()],
                    line = dict(color=('rgb(0, 0, 0)'),
                                width=5, dash='dash')
layout = go.Layout(showlegend=False,
                    range = [-10,60],

fig = go.Figure(data = [trace1,trace2], layout = layout)
py.iplot(fig, filename="c-v-predict")
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.