Show Sidebar Hide Sidebar

Sparsity Example Fitting only Features 1 and 2 in Scikit-learn

Features 1 and 2 of the diabetes-dataset are fitted and plotted below. It illustrates that although feature 2 has a strong coefficient on the full model, it does not give us much regarding y when compared to just feature 1

New to Plotly?¶

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!

Version¶

In [1]:
import sklearn
sklearn.__version__

Out[1]:
'0.18.1'

Imports¶

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

import numpy as np
from sklearn import datasets, linear_model


Calculations¶

In [3]:
diabetes = datasets.load_diabetes()
indices = (0, 1)

X_train = diabetes.data[:-20, indices]
X_test = diabetes.data[-20:, indices]
y_train = diabetes.target[:-20]
y_test = diabetes.target[-20:]

ols = linear_model.LinearRegression()
ols.fit(X_train, y_train)

Out[3]:
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

Plot Figure¶

In [4]:
def plot_figs(X_train, clf):

p1 = go.Scatter3d(x=X_train[:, 0], y=X_train[:, 1],
z=y_train,
mode='markers',
marker=dict(color='blue',
line=dict(color='black', width=1))
)
p2 = go.Surface(x=np.array([[-.1, -.1], [.15, .15]]),
y=np.array([[-.1, .15], [-.1, .15]]),
z=clf.predict(np.array([[-.1, -.1, .15, .15],
[-.1, .15, -.1, .15]]).T
).reshape((2, 2)),
showscale=False
)
fig = go.Figure(data=[p1, p2])
return fig


Generate the three different figures from different views¶

In [5]:
fig = plot_figs(X_train, ols)

camera = dict(
up=dict(x=0, y=0, z=1),
center=dict(x=0, y=0, z=0),
eye=dict(x=0.1, y=0.1, z=2.5)
)

fig['layout'].update(
scene=dict(camera=camera,
xaxis=dict(title='X_1', showticklabels=False),
yaxis=dict(title='X_2', showticklabels=False),
zaxis=dict(title='Y', showticklabels=False),
)
)

py.iplot(fig)

Out[5]:
In [6]:
fig = plot_figs(X_train, ols)

camera = dict(
up=dict(x=0, y=0, z=1),
center=dict(x=0, y=0, z=0),
eye=dict(x=2.5, y=0.1, z=0.1)
)

fig['layout'].update(
scene=dict(camera=camera,
xaxis=dict(title='X_1', showticklabels=False),
yaxis=dict(title='X_2', showticklabels=False),
zaxis=dict(title='Y', showticklabels=False),
)
)

py.iplot(fig)

Out[6]:
In [7]:
fig = plot_figs(X_train, ols)

camera = dict(
up=dict(x=0, y=0, z=1),
center=dict(x=0, y=0, z=0),
eye=dict(x=0.1, y=2.5, z=0.1)
)

fig['layout'].update(
scene=dict(camera=camera,
xaxis=dict(title='X_1', showticklabels=False),
yaxis=dict(title='X_2', showticklabels=False),
zaxis=dict(title='Y', showticklabels=False),
)
)

py.iplot(fig)

Out[7]:

Code source:

        GaĆ«l Varoquaux



Modified for documentation by Jaques Grobler

        BSD 3 clause