Show Sidebar Hide Sidebar

PCA example with Iris Data-set in Scikit-learn

Principal Component Analysis applied to the Iris dataset.

See here for more information on this dataset.

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

In [2]:
print(__doc__)

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

import numpy as np
import matplotlib.pyplot as plt

from sklearn import decomposition
from sklearn import datasets
Automatically created module for IPython interactive environment

Calculations

In [3]:
np.random.seed(5)

centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.load_iris()
X = iris.data
y = iris.target

pca = decomposition.PCA(n_components=3)
pca.fit(X)
X = pca.transform(X)

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
In [5]:
# Reorder the labels to have colors matching the cluster results
y = np.choose(y, [1, 2, 0]).astype(np.float)

trace = go.Scatter3d(x=X[:, 0], y=X[:, 1], z=X[:, 2], 
                     mode='markers',
                     marker=dict(color=y, 
                                 colorscale=matplotlib_to_plotly(plt.cm.spectral, 5),
                                 line=dict(color='black', width=1))
                     )

layout = go.Layout(scene=
                   dict(
                        xaxis=dict(ticks='', showticklabels=False),
                        yaxis=dict(ticks='', showticklabels=False),
                        zaxis=dict(ticks='', showticklabels=False),
                       )
                  )

fig = go.Figure(data=[trace], layout=layout)
In [6]:
py.iplot(fig)
Out[6]:

License

Code source:

        Gaƫl Varoquaux

License:

        BSD 3 clause
Still need help?
Contact Us

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