如何使用scikit-learn和matplotlib绘制不平衡数据集的SVC分类?

tum*_*eed 5 nlp artificial-intelligence machine-learning svm scikit-learn

我有一个文本分类任务,包含2599个文档和5个标签,从1到5.文档是

label | texts
----------
5     |1190
4     |839
3     |239
1     |204
2     |127
Run Code Online (Sandbox Code Playgroud)

所有人都准备好将这些文本数据分类为非常低的性能,并且还会收到有关定义不明确的指标的警告:

Accuracy: 0.461057692308

score: 0.461057692308

precision: 0.212574195636

recall: 0.461057692308

  'precision', 'predicted', average, warn_for)
 confussion matrix:
[[  0   0   0   0 153]
  'precision', 'predicted', average, warn_for)
 [  0   0   0   0  94]
 [  0   0   0   0 194]
 [  0   0   0   0 680]
 [  0   0   0   0 959]]

 clasification report:
             precision    recall  f1-score   support

          1       0.00      0.00      0.00       153
          2       0.00      0.00      0.00        94
          3       0.00      0.00      0.00       194
          4       0.00      0.00      0.00       680
          5       0.46      1.00      0.63       959

avg / total       0.21      0.46      0.29      2080
Run Code Online (Sandbox Code Playgroud)

很明显,这是因为我有一个不平衡的数据集这一事实,所以我发现这篇论文的作者提出了几个方法来处理这个问题:

问题是,对于不平衡的数据集,学习的边界太靠近正实例.我们需要以一种将边界推离正面实例的方式偏向SVM.Veropoulos等[14]建议对正(C +)类和负(C - )类使用不同的误差成本

我知道这可能非常复杂,但是SVC提供了几个超参数,所以我的问题是:有没有办法偏离SVC的方式使用提供SVC分类器的超参数来推动边界远离可能的实例?我知道这可能是一个困难的问题,但欢迎任何帮助,谢谢你提前.

from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
tfidf_vect= TfidfVectorizer(use_idf=True, smooth_idf=True, sublinear_tf=False, ngram_range=(2,2))
from sklearn.cross_validation import train_test_split, cross_val_score

import pandas as pd
df = pd.read_csv('/path/of/the/file.csv',
                     header=0, sep=',', names=['id', 'text', 'label'])



reduced_data = tfidf_vect.fit_transform(df['text'].values)
y = df['label'].values



from sklearn.decomposition.truncated_svd import TruncatedSVD
svd = TruncatedSVD(n_components=5)
reduced_data = svd.fit_transform(reduced_data)

from sklearn import cross_validation
X_train, X_test, y_train, y_test = cross_validation.train_test_split(reduced_data,
                                                    y, test_size=0.33)

#with no weights:

from sklearn.svm import SVC
clf = SVC(kernel='linear', class_weight={1: 10})
clf.fit(reduced_data, y)
prediction = clf.predict(X_test)

w = clf.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(-5, 5)
yy = a * xx - clf.intercept_[0] / w[1]


# get the separating hyperplane using weighted classes
wclf = SVC(kernel='linear', class_weight={1: 10})
wclf.fit(reduced_data, y)

ww = wclf.coef_[0]
wa = -ww[0] / ww[1]
wyy = wa * xx - wclf.intercept_[0] / ww[1]

# plot separating hyperplanes and samples
import matplotlib.pyplot as plt
h0 = plt.plot(xx, yy, 'k-', label='no weights')
h1 = plt.plot(xx, wyy, 'k--', label='with weights')
plt.scatter(reduced_data[:, 0], reduced_data[:, 1], c=y, cmap=plt.cm.Paired)
plt.legend()

plt.axis('tight')
plt.show()
Run Code Online (Sandbox Code Playgroud)

但我一无所获,我无法理解发生了什么,这是情节:

加权与正常

然后:

#Let's show some metrics[unweighted]:
from sklearn.metrics.metrics import precision_score, \
    recall_score, confusion_matrix, classification_report, accuracy_score
print '\nAccuracy:', accuracy_score(y_test, prediction)
print '\nscore:', clf.score(X_train, y_train)
print '\nrecall:', recall_score(y_test, prediction)
print '\nprecision:', precision_score(y_test, prediction)
print '\n clasification report:\n', classification_report(y_test, prediction)
print '\n confussion matrix:\n',confusion_matrix(y_test, prediction)

#Let's show some metrics[weighted]:
print 'weighted:\n'

from sklearn.metrics.metrics import precision_score, \
    recall_score, confusion_matrix, classification_report, accuracy_score
print '\nAccuracy:', accuracy_score(y_test, prediction)
print '\nscore:', wclf.score(X_train, y_train)
print '\nrecall:', recall_score(y_test, prediction)
print '\nprecision:', precision_score(y_test, prediction)
print '\n clasification report:\n', classification_report(y_test, prediction)
print '\n confussion matrix:\n',confusion_matrix(y_test, prediction)
Run Code Online (Sandbox Code Playgroud)

这是我使用的数据.我怎样才能解决这个问题并以正确的方式绘制这个问题?先谢谢你们!

从这个问题的答案我删除这一行:

#
# from sklearn.decomposition.truncated_svd import TruncatedSVD
# svd = TruncatedSVD(n_components=5)
# reduced_data = svd.fit_transform(reduced_data)


#
# w = clf.coef_[0]
# a = -w[0] / w[1]
# xx = np.linspace(-10, 10)
# yy = a * xx - clf.intercept_[0] / w[1]

# ww = wclf.coef_[0]
# wa = -ww[0] / ww[1]
# wyy = wa * xx - wclf.intercept_[0] / ww[1]
#
# # plot separating hyperplanes and samples
# import matplotlib.pyplot as plt
# h0 = plt.plot(xx, yy, 'k-', label='no weights')
# h1 = plt.plot(xx, wyy, 'k--', label='with weights')
# plt.scatter(reduced_data[:, 0], reduced_data[:, 1], c=y, cmap=plt.cm.Paired)
# plt.legend()
#
# plt.axis('tight')
# plt.show()

This where the results:

Accuracy: 0.787878787879

score: 0.779437105112

recall: 0.787878787879

precision: 0.827705441238
Run Code Online (Sandbox Code Playgroud)

此指标得到改善.我如何绘制这个结果,以便有一个像文档一样的好例子.我想看看两架超平面的行为?.多谢你们!

Mak*_*ich 2

如果我正确理解您的输入,您将得到:

1190 个标记文本(共 5 个) 1409 个标记文本(共 1-4 个)

您可以尝试进行顺序分类。首先将所有 5 个标签威胁为 1,其他标签威胁为 0。为此任务训练一个分类器

其次,从数据集中删除所有 5 个示例。训练分类器对 1-4 个标签进行分类。

分类后运行第一个分类器,如果返回 0 - 运行第二个分类器以获得最终标签。

虽然我不认为这个分布是真正倾斜和不平衡的(它应该像 5 的 90%、10% - 其余的都是真正倾斜的,所以向 SVC 引入偏差可能会很有趣)。因此,我认为您可能想尝试一些其他分类算法,因为看起来您的选择不适合此任务。或者也许你需要在 SVC 中使用不同的内核(我假设你使用线性内核,尝试不同的东西 - RBF 或多项式也许)。