Show Sidebar Hide Sidebar

# Swiss Roll Reduction with LLE in Scikit-learn

An illustration of Swiss Roll reduction with locally linear embedding

#### 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
from plotly import tools

import numpy as np
import matplotlib.pyplot as plt
from sklearn import manifold, datasets


### Calculations¶

In [3]:
X, color = datasets.samples_generator.make_swiss_roll(n_samples=1500)

print("Computing LLE embedding")
X_r, err = manifold.locally_linear_embedding(X, n_neighbors=12,
n_components=2)
print("Done. Reconstruction error: %g" % err)

Computing LLE embedding
Done. Reconstruction error: 1.3218e-07


### Plot Results¶

In [4]:
def matplotlib_to_plotly(cmap, pl_entries):
h = 1.0/(pl_entries-1)
pl_colorscale = []

for k in range(pl_entries):
C = map(np.uint8, np.array(cmap(k*h)[:3])*255)
pl_colorscale.append([k*h, 'rgb'+str((C[0], C[1], C[2]))])

return pl_colorscale

cmap = matplotlib_to_plotly(plt.cm.Spectral, 4)


### Original Data¶

In [5]:
try:
p1 = go.Scatter3d(x=X[:, 0], y=X[:, 1], z=X[:, 2],
mode='markers',
marker=dict(color=color,
colorscale=cmap,
showscale=False,
line=dict(color='black', width=1)))

except:
p1 = go.Scatter(x=X[:, 0], y=X[:, 2],
mode='markers',
marker=dict(color=color,
colorscale=cmap,
showscale=False,
line=dict(color='black', width=1)))

layout=dict(title='Original Data',
margin=dict(l=10, r=10,
t=30, b=10)
)
fig = go.Figure(data=[p1], layout=layout)

In [6]:
py.iplot(fig)

Out[6]:

### Projected Data¶

In [7]:
p2 = go.Scatter(x=X_r[:, 0], y=X_r[:, 1],
mode='markers',
marker=dict(color=color,
colorscale=cmap,
showscale=False,
line=dict(color='black', width=1)))
layout=dict(title='Projected Data',
xaxis=dict(zeroline=False, showgrid=False),
yaxis=dict(zeroline=False, showgrid=False),
)
fig = go.Figure(data=[p2], layout=layout)

In [8]:
py.iplot(fig)

Out[8]:

Author:

    Fabian Pedregosa -- <fabian.pedregosa@inria.fr>



    BSD 3 clause (C) INRIA 2011