训练sklearn LogisticRegression分类器,没有所有可能的标签

Ale*_*ure 4 python machine-learning scikit-learn

我正在尝试使用scikit-learn 0.12.1来:

  1. 训练LogisticRegression分类器
  2. 在持有的验证数据上评估分类
  3. 将新数据提供给此分类器并检索每个观察的5个最可能的标签

除了一个特点之外,Sklearn使所有这一切变得非常容易.无法保证每个可能的标签都会出现在用于适合我的分类器的数据中.有数百种可能的标签,其中一些标签没有出现在可用的培训数据中.

这导致2个问题:

  1. 当标签矢量化器出现在验证数据中时,它不会识别以前看不见的标签.通过将贴标机安装到一组可能的标签上可以很容易地解决这个问题,但这会加剧问题2.
  2. LogisticRegression分类器的predict_proba方法的输出是[n_samples,n_classes]数组,其中n_classes 包含训练数据中看到的类.这意味着在predict_proba数组上运行argsort不再提供直接映射到标签矢量化器词汇表的值.

我的问题是,强制分类器识别全部可能类的最佳方法是什么,即使其中一些类没有出现在训练数据中?显然,它无法了解它从未见过数据的标签,但0在我的情况下是完全可用的.

Fre*_*Foo 8

这是一个解决方法.确保您有一个所有类的列表all_classes.然后,如果clf是你的LogisticRegression分类器,

from itertools import repeat

# determine the classes that were not present in the training set;
# the ones that were are listed in clf.classes_.
classes_not_trained = set(clf.classes_).symmetric_difference(all_classes)

# the order of classes in predict_proba's output matches that in clf.classes_.
prob = clf.predict_proba(test_samples)
for row in prob:
    prob_per_class = (zip(clf.classes_, prob)
                    + zip(classes_not_trained, repeat(0.)))
Run Code Online (Sandbox Code Playgroud)

生成(cls, prob)一对对列表.