Show Sidebar Hide Sidebar

Pixel Importances with a Parallel Forest of Trees in Scikit-learn

This example shows the use of forests of trees to evaluate the importance of the pixels in an image classification task (faces). The hotter the pixel, the more important.

The code below also illustrates how the construction and the computation of the predictions can be parallelized within multiple jobs.

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¶

This tutorial imports fetch_olivetti_faces and ExtraTreesClassifier.

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

from time import time
import matplotlib.pyplot as plt

from sklearn.datasets import fetch_olivetti_faces
from sklearn.ensemble import ExtraTreesClassifier


Calculations¶

In [3]:
# Number of cores to use to perform parallel fitting of the forest model
n_jobs = 1

data = fetch_olivetti_faces()
X = data.images.reshape((len(data.images), -1))
y = data.target

mask = y < 5  # Limit to 5 classes

# Build a forest and compute the pixel importances
print("Fitting ExtraTreesClassifier on faces data with %d cores..." % n_jobs)
t0 = time()
forest = ExtraTreesClassifier(n_estimators=1000,
max_features=128,
n_jobs=n_jobs,
random_state=0)

forest.fit(X, y)
print("done in %0.3fs" % (time() - t0))
importances = forest.feature_importances_
importances = importances.reshape(data.images[0].shape)

Fitting ExtraTreesClassifier on faces data with 1 cores...
done in 2.753s


Plot Pixel Importances¶

In [4]:
trace = go.Heatmap(z=importances,
colorscale='Hot',
showscale=False)

layout = go.Layout(title="Pixel importances with forests of trees",
yaxis=dict(autorange='reversed'))

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

py.iplot(fig)

Out[4]:
Still need help?