Show Sidebar Hide Sidebar

SVM-Anova SVM with Univariate Feature Selection in Scikit-learn

This example shows how to perform univariate feature selection before running a SVC (support vector classifier) to improve the classification scores.

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.1'

Imports

This tutorial imports Pipeline and cross_val_score.

In [2]:
print(__doc__)

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

import numpy as np
from sklearn import svm, datasets, feature_selection
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
Automatically created module for IPython interactive environment

Calculations

Import some data to play with

In [3]:
digits = datasets.load_digits()
y = digits.target
# Throw away data, to be in the curse of dimension settings
y = y[:200]
X = digits.data[:200]
n_samples = len(y)
X = X.reshape((n_samples, -1))
# add 200 non-informative features
X = np.hstack((X, 2 * np.random.random((n_samples, 200))))

Create a feature-selection transform and an instance of SVM that we combine together to have an full-blown estimator

In [4]:
transform = feature_selection.SelectPercentile(feature_selection.f_classif)

clf = Pipeline([('anova', transform), ('svc', svm.SVC(C=1.0))])

Plot Results

In [7]:
score_means = list()
score_stds = list()
percentiles = (1, 3, 6, 10, 15, 20, 30, 40, 60, 80, 100)

for percentile in percentiles:
    clf.set_params(anova__percentile=percentile)
    # Compute cross-validation score using 1 CPU
    this_scores = cross_val_score(clf, X, y, n_jobs=1)
    score_means.append(this_scores.mean())
    score_stds.append(this_scores.std())

p1 = go.Scatter(x=percentiles, y=score_means, 
                mode='lines',
                error_y = dict(visible=True, 
                              arrayminus=np.array(score_stds)))

layout = go.Layout(title=
                   'Performance of the SVM-Anova varying the percentile of features selected',
                   xaxis=dict(title='Percentile'),
                   yaxis=dict(title='Prediction rate'))
fig = go.Figure(data=[p1], layout=layout)
In [6]:
py.iplot(fig)
Out[6]:
Still need help?
Contact Us

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