scikit-learn/examples/svm/plot_svm_anova.py

59 lines
2.0 KiB
Python
Raw Normal View History

"""
=================================================
SVM-Anova: SVM with univariate feature selection
=================================================
2015-12-16 03:18:19 +08:00
This example shows how to perform univariate feature selection before running a
SVC (support vector classifier) to improve the classification scores.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets, feature_selection
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
2011-12-17 05:55:42 +08:00
###############################################################################
# Import some data to play with
digits = datasets.load_digits()
y = digits.target
2010-09-06 05:05:06 +08:00
# Throw away data, to be in the curse of dimension settings
y = y[:200]
X = digits.data[:200]
n_samples = len(y)
2010-09-06 05:05:06 +08:00
X = X.reshape((n_samples, -1))
# add 200 non-informative features
2011-12-17 05:55:42 +08:00
X = np.hstack((X, 2 * np.random.random((n_samples, 200))))
2011-12-17 05:55:42 +08:00
###############################################################################
# Create a feature-selection transform and an instance of SVM that we
# combine together to have an full-blown estimator
transform = feature_selection.SelectPercentile(feature_selection.f_classif)
2012-05-05 20:56:19 +08:00
clf = Pipeline([('anova', transform), ('svc', svm.SVC(C=1.0))])
2011-12-17 05:55:42 +08:00
###############################################################################
# Plot the cross-validation score as a function of percentile of features
score_means = list()
2011-12-17 05:55:42 +08:00
score_stds = list()
2010-09-06 05:05:06 +08:00
percentiles = (1, 3, 6, 10, 15, 20, 30, 40, 60, 80, 100)
for percentile in percentiles:
clf.set_params(anova__percentile=percentile)
2015-12-03 02:09:56 +08:00
# 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())
plt.errorbar(percentiles, score_means, np.array(score_stds))
plt.title(
'Performance of the SVM-Anova varying the percentile of features selected')
plt.xlabel('Percentile')
plt.ylabel('Prediction rate')
plt.axis('tight')
plt.show()