Show Sidebar Hide Sidebar

Mean-Shift Clustering Algorithm in Scikit-learn

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!

Version

In [1]:
import sklearn
sklearn.__version__
Out[1]:
'0.18'

Imports

This tutorial imports MeanShift, estimate_bandwidth, make_blobs.

In [2]:
print(__doc__)

import plotly.plotly as py
import plotly.graph_objs as go
import plotly

import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets.samples_generator import make_blobs
Automatically created module for IPython interactive environment

Calculations

Generate sample data.

In [3]:
centers = [[1, 1], [-1, -1], [1, -1]]
X, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)

Compute clustering with MeanShift.

In [4]:
# The following bandwidth can be automatically detected using
bandwidth = estimate_bandwidth(X, quantile=0.2, n_samples=500)

ms = MeanShift(bandwidth=bandwidth, bin_seeding=True)
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_

labels_unique = np.unique(labels)
n_clusters_ = len(labels_unique)

print("number of estimated clusters : %d" % n_clusters_)
number of estimated clusters : 3

Plot Results

In [5]:
colors = ['blue','green','red','cyan','magenta']
cluster = [ ] 
for k, col in zip(range(n_clusters_), colors):
    my_members = labels == k
    cluster_center = cluster_centers[k]
    trace = go.Scatter(x=X[my_members, 0], y=X[my_members, 1], 
                       mode='markers', showlegend=False, 
                       marker= dict(color=col, size=10,))
    
    trace1 = go.Scatter(x=[cluster_center[0]], y=[cluster_center[1]], 
                        mode='markers',  showlegend=False,
                        marker=dict(color=col, size=20,
                               line=dict(color = 'black',
                                           width = 1)))
    cluster.append(trace)
    cluster.append(trace1)
    
layout = go.Layout(title = 'Estimated number of clusters: %d' % n_clusters_,
                   xaxis = dict(showgrid = False, zeroline = False),
                   yaxis = dict(showgrid = False, zeroline = False),)

fig = go.Figure(data = cluster, layout = layout)
py.iplot(fig)
Out[5]:

Reference

Dorin Comaniciu and Peter Meer, “Mean Shift: A robust approach toward feature space analysis”. IEEE Transactions on Pattern Analysis and Machine Intelligence. 2002. pp. 603-619.

Still need help?
Contact Us

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