In [2]:
from sklearn import datasets
newsgroups = datasets.fetch_20newsgroups(
subset='all',
categories=['alt.atheism', 'sci.space'])
In [17]:
print(newsgroups.data[0])
print(newsgroups.target)
In [34]:
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
data = vectorizer.fit_transform(newsgroups.data)
In [50]:
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFold
from sklearn.svm import SVC
grid = {'C': np.power(10.0, np.arange(-5, 6))}
cv = KFold(n_splits=5, shuffle=True, random_state=241)
clf = SVC(kernel='linear', random_state=241)
gs = GridSearchCV(clf, grid, scoring='accuracy', cv=cv)
gs.fit(data, newsgroups.target)
Out[50]:
In [52]:
gs.grid_scores_
Out[52]:
In [106]:
C = gs.best_params_.get('C')
print(C)
In [110]:
svm = SVC(kernel='linear', random_state=241, C=C)
svm.fit(data, newsgroups.target)
Out[110]:
In [113]:
import pandas as pd
words = vectorizer.get_feature_names()
coef = pd.DataFrame(svm.coef_.data, svm.coef_.indices)
In [134]:
top_words = coef[0].map(lambda w: abs(w)).sort_values(ascending=False).head(10).index.map(lambda i: words[i])
t = top_words.sort_values()
print(t)
In [135]:
print(",".join(t))