2015-05-12 162 views
1

关于SVMs的文档意味着存在一个名为'classes_'的属性,它有望揭示模型如何在内部表示类。识别sklearn模型的类

我想获得这些信息,以便解释像'predict_proba'这样的函数的输出,该函数可以为多个样本生成类的概率。希望知道(完全随机选择的值,只是为了举例说明)

model.classes_ 
>> [1, 2, 4] 

手段,我可​​以假设

model.predict_proba([[1.2312, 0.23512, 6.], [3.7655, 8.2353, 0.86323]]) 
>> [[0.032, 0.143, 0.825], [0.325, 0.143, 0.532]] 

装置,该概率转换为相同的数量级的类,即对于第一组特征:

probability of class 1: 0.032 
probability of class 2: 0.143 
probability of class 4: 0.825 

但是在SVM上调用'classes_'会导致错误。有没有一种好的方法来获取这些信息?我无法想象在训练完模型后无法再访问它。

编辑: 我建立我的模型是多还是少这样的方式:

from sklearn.svm import SVC 
from sklearn.grid_search import GridSearchCV 
from sklearn.pipeline import Pipeline, FeatureUnion 


pipeline = Pipeline([ 
    ('features', FeatureUnion(transformer_list[ ... ])), 
    ('svm', SVC(probability=True)) 
]) 
parameters = { ... } 
grid_search = GridSearchCV(
    pipeline, 
    parameters 
) 

grid_search.fit(get_data(), get_labels()) 
clf = [elem for elem in grid_search.estimator.steps if elem[0] == 'svm'][0][1] 

print(clf) 
>> SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, 
    kernel='rbf', max_iter=-1, probability=True, random_state=None, 
    shrinking=True, tol=0.001, verbose=False) 
print(clf.classes_) 
>> Traceback (most recent call last): 
    File "path/to/script.py", line 284, in <module> 
    File "path/to/script.py", line 181, in re_train 
    print(clf.classes_) 
AttributeError: 'SVC' object has no attribute 'classes_' 

回答

2

,你正在寻找它的不合身的管道grid_search.estimatorclasses_属性仅在拟合后才存在,因为分类器需要看到y

你想要的是使用最佳参数设置进行训练的估算器,即grid_search.best_estimator_

下面的工作:

CLF = grid_search.best_estimator_.named_steps [ 'SVM'] 打印(clf.classes_)

[和classes_不正是你想象的那样。

+0

谢谢,它现在可以工作=) – Arne

1

有在sklearn一类的领域,这可能意味着你调用了错误的模型,看下面的例子中,我们可以看到,有类看classes_场时:

>>> import numpy as np 
>>> from sklearn.svm import SVC 
>>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) 
>>> y = np.array([1, 1, 2, 2]) 
>>> clf = SVC(probability=True) 
>>> clf.fit(X, y) 
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, 
    kernel='rbf', max_iter=-1, probability=True, random_state=None, 
    shrinking=True, tol=0.001, verbose=False) 
>>> print clf.classes_ 
[1 2] 
>>> print clf.predict([[-0.8, -1]]) 
[1] 
>>> print clf.predict_proba([[-0.8, -1]]) 
[[ 0.92419129 0.07580871]] 
+0

我明白了。也许我的问题是,我的模型隐藏在GridSearchCV中。我更新了更多信息的初始文章,以及更具体的错误消息。 – Arne