Show Sidebar Hide Sidebar

# Label Propagation Learning a Complex Structure in Scikit-learn

Example of LabelPropagation learning a complex internal structure to demonstrate “manifold learning”. The outer circle should be labeled “red” and the inner circle “blue”. Because both label groups lie inside their own distinct shape, we can see that the labels propagate correctly around the circle.

#### 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
from sklearn.semi_supervised import label_propagation
from sklearn.datasets import make_circles


### Calculations¶

In [3]:
# generate ring with inner box
n_samples = 200
X, y = make_circles(n_samples=n_samples, shuffle=False)
outer, inner = 0, 1
labels = -np.ones(n_samples)
labels[0] = outer
labels[-1] = inner


In [4]:
label_spread = label_propagation.LabelSpreading(kernel='knn', alpha=1.0)

Out[4]:
LabelSpreading(alpha=1.0, gamma=20, kernel='knn', max_iter=30, n_jobs=1,
n_neighbors=7, tol=0.001)

### Plot Output Labels¶

In [5]:
output_labels = label_spread.transduction_

p1 = go.Scatter(x=X[labels == outer, 0], y=X[labels == outer, 1],
mode='markers',
marker=dict(color='navy'),
name="outer labeled")

p2 = go.Scatter(x=X[labels == inner, 0], y=X[labels == inner, 1],
mode='markers',
marker=dict(color='cyan'),
name='inner labeled')

p3 = go.Scatter(x=X[labels == -1, 0], y=X[labels == -1, 1],
mode='markers',
marker=dict(color='orange'),
name='unlabeled')

layout = go.Layout(title="Raw data (2 classes=outer and inner)",
xaxis=dict(zeroline=False), yaxis=dict(zeroline=False))

fig = go.Figure(data=[p1, p2, p3], layout=layout)

In [6]:
py.iplot(fig)

Out[6]:
In [7]:
output_label_array = np.asarray(output_labels)
outer_numbers = np.where(output_label_array == outer)[0]
inner_numbers = np.where(output_label_array == inner)[0]

p1 = go.Scatter(x=X[outer_numbers, 0],
y=X[outer_numbers, 1],
mode='markers',
marker=dict(color='navy'),
name="outer learned")

p2 = go.Scatter(x=X[inner_numbers, 0],
y=X[inner_numbers, 1],
mode='markers',
marker=dict(color='cyan'),
name="inner learned")

layout = go.Layout(title="Labels learned with Label Spreading (KNN)",
xaxis=dict(zeroline=False), yaxis=dict(zeroline=False))

fig = go.Figure(data=[p1, p2], layout=layout)

In [8]:
py.iplot(fig)

Out[8]:

Authors:

      Clay Woolam <clay@woolam.org>

Andreas Mueller <amueller@ais.uni-bonn.de>



      BSD