scikit-learn/svm - 在 'predict_proba' 之后获取概率和相关标签

scikit-learn/svm - fetch probabilities and associated labels after 'predict_proba'

我正在使用 scikit-learn SVM 进行文本分类并遵循指南 here。但是我很困惑如何使用 predict_proba 方法来获取概率,与正确的标签相关联并获取前 3 个。

vectorizer = HashingVectorizer()
clf = svm.SVC(probability=True,class_weight='balanced')

test_data = [...]

test_vectors = vectorizer.transform(test_data)
predicted = clf.predict_proba(test_vectors)
for doc, pred in zip(test_labels, predicted):
    print('%r => %s' % (doc, test_labels[pred]))  

在 运行 上面的代码中我得到了这个异常:

TypeError: only integer arrays with one element can be converted to an index

这是可以理解的,因为 test_labels 是一个概率数组,但我不确定如何获取关联的标签和概率。

这就是我最终所做的,并且对我很有效。希望这对某人有帮助:

    clf = cPickle.load(...)  
    test_data, test_labels = load_testfiles(_testpath) 

    for td in zip(test_data,test_labels):
        X = vectorizer.transform([td[0]])
        label = td[1]
        res = clf.predict_proba(X)[0]
        # sd = np.std(res)
        # max = np.amax(res)
        # min = np.amin(res)
        # mean = np.mean(res)
        # median = np.median(res)
        print("test--->actual=",label,"pred=",res)