class_weights 参数允许您提高或降低此误报率。让我用一个日常例子来说明它是如何工作的。假设您拥有一家夜总会,并且您在两个限制条件下运营:
- 您希望尽可能多的人进入俱乐部(付费客户)
- 您不希望任何未成年人进入,因为这会给您带来国家麻烦
平均而言,(比如说)试图进入俱乐部的人中只有 5% 的人是未成年人。你面临着一个选择:宽容还是严格。前者将使您的利润增加多达 5%,但您面临着昂贵诉讼的风险。后者将不可避免地意味着一些刚刚超过法定年龄的人将被拒绝入境,这也会花费你的钱。您想调整宽大与严格的relative cost。注意:您无法直接控制有多少未成年人进入俱乐部,但您可以控制保镖的严格程度。
这里有一点 Python 说明,当您更改相对重要性时会发生什么。
from collections import Counter
import numpy as np
from sklearn.datasets import load_iris
from sklearn.svm import LinearSVC
data = load_iris()
# remove a feature to make the problem harder
# remove the third class for simplicity
X = data.data[:100, 0:1]
y = data.target[:100]
# shuffle data
indices = np.arange(y.shape[0])
np.random.shuffle(indices)
X = X[indices, :]
y = y[indices]
for i in range(1, 20):
clf = LinearSVC(class_weight={0: 1, 1: i})
clf = clf.fit(X[:50, :], y[:50])
print i, Counter(clf.predict(X[50:]))
# print clf.decision_function(X[50:])
哪些输出
1 Counter({1: 22, 0: 28})
2 Counter({1: 31, 0: 19})
3 Counter({1: 39, 0: 11})
4 Counter({1: 43, 0: 7})
5 Counter({1: 43, 0: 7})
6 Counter({1: 44, 0: 6})
7 Counter({1: 44, 0: 6})
8 Counter({1: 44, 0: 6})
9 Counter({1: 47, 0: 3})
10 Counter({1: 47, 0: 3})
11 Counter({1: 47, 0: 3})
12 Counter({1: 47, 0: 3})
13 Counter({1: 47, 0: 3})
14 Counter({1: 47, 0: 3})
15 Counter({1: 47, 0: 3})
16 Counter({1: 47, 0: 3})
17 Counter({1: 48, 0: 2})
18 Counter({1: 48, 0: 2})
19 Counter({1: 48, 0: 2})
请注意分类为0 的数据点数量是如何减少的,而1 类的相对权重会增加。假设您有计算资源和时间来训练和评估 10 个分类器,您可以绘制每个分类器的准确率和召回率,并得到如下图(无耻地从互联网上窃取)。然后,您可以使用它来确定 class_weights 的正确值对于您的用例是什么。