2010-07-27 17:57:58 +08:00
|
|
|
"""
|
2010-11-02 18:38:06 +08:00
|
|
|
==================
|
2010-07-27 17:57:58 +08:00
|
|
|
Pipeline Anova SVM
|
2010-11-02 18:38:06 +08:00
|
|
|
==================
|
2010-07-27 17:57:58 +08:00
|
|
|
|
2010-11-02 18:38:06 +08:00
|
|
|
Simple usage of Pipeline that runs successively a univariate
|
2019-03-07 18:22:49 +08:00
|
|
|
feature selection with anova and then a SVM of the selected features.
|
|
|
|
|
|
|
|
|
|
Using a sub-pipeline, the fitted coefficients can be mapped back into
|
|
|
|
|
the original feature space.
|
2010-07-27 17:57:58 +08:00
|
|
|
"""
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn import svm
|
2019-10-28 05:17:23 +08:00
|
|
|
from sklearn.datasets import make_classification
|
2020-06-16 19:19:08 +08:00
|
|
|
from sklearn.feature_selection import SelectKBest, f_classif
|
2013-12-19 06:37:03 +08:00
|
|
|
from sklearn.pipeline import make_pipeline
|
2017-05-12 20:21:40 +08:00
|
|
|
from sklearn.model_selection import train_test_split
|
|
|
|
|
from sklearn.metrics import classification_report
|
|
|
|
|
|
|
|
|
|
print(__doc__)
|
2010-07-27 17:57:58 +08:00
|
|
|
|
|
|
|
|
# import some data to play with
|
2019-10-28 05:17:23 +08:00
|
|
|
X, y = make_classification(
|
2012-12-25 20:16:05 +08:00
|
|
|
n_features=20, n_informative=3, n_redundant=0, n_classes=4,
|
|
|
|
|
n_clusters_per_class=2)
|
2010-07-27 17:57:58 +08:00
|
|
|
|
2017-05-12 20:21:40 +08:00
|
|
|
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
|
|
|
|
|
|
2010-07-27 18:46:31 +08:00
|
|
|
# ANOVA SVM-C
|
2011-08-04 21:50:19 +08:00
|
|
|
# 1) anova filter, take 3 best ranked features
|
2020-06-16 19:19:08 +08:00
|
|
|
anova_filter = SelectKBest(f_classif, k=3)
|
2010-07-27 18:46:31 +08:00
|
|
|
# 2) svm
|
2019-03-07 18:22:49 +08:00
|
|
|
clf = svm.LinearSVC()
|
2010-07-27 17:57:58 +08:00
|
|
|
|
2013-12-19 06:37:03 +08:00
|
|
|
anova_svm = make_pipeline(anova_filter, clf)
|
2017-05-12 20:21:40 +08:00
|
|
|
anova_svm.fit(X_train, y_train)
|
|
|
|
|
y_pred = anova_svm.predict(X_test)
|
|
|
|
|
print(classification_report(y_test, y_pred))
|
2019-03-07 18:22:49 +08:00
|
|
|
|
|
|
|
|
coef = anova_svm[:-1].inverse_transform(anova_svm['linearsvc'].coef_)
|
|
|
|
|
print(coef)
|