代码之家  ›  专栏  ›  技术社区  ›  Widhi

混淆矩阵返回单个矩阵

  •  -1
  • Widhi  · 技术社区  · 7 年前

    我发现scikit混淆矩阵有问题。

    我在KFold中使用混淆矩阵,然后当yu true和yu pred是100%正确时,混淆矩阵返回单个数字。这使得我的混淆矩阵变量崩溃了,因为我在每个折叠中添加了混淆矩阵的结果。有人能解决这个问题吗?

    model = MultinomialNB()
    kf = KFold(n_splits=10)
    cf = np.array([[0, 0], [0, 0]])
    for train_index, test_index in kf.split(x):
        x_train, x_test = x[train_index], x[test_index]
        y_train, y_test = y[train_index], y[test_index]
        model.fit(x_train, y_train)
        y_pred = model.predict(x_test)
        cf += confusion_matrix(y_test, y_pred)
    

    谢谢您

    2 回复  |  直到 7 年前
        1
  •  2
  •   Bonlenfum    7 年前

    最干净的方法可能是将所有可能类的列表作为 labels

    from sklearn.metrics import confusion_matrix                                      
    import numpy as np                                                                
    
    y_test = np.array([1,1,1,1,1,0,0])                                                
    y_pred = np.array([0,1,1,1,1,0,0])                                                
    
    labels = np.unique(y_test)                                                        
    
    cf = np.array([[0, 0], [0, 0]])                                                   
    
    for indices in [ [0,1,2,3], [1,2,3] , [1,2,3,4,5,6]]:                             
        cm1= confusion_matrix(y_test[indices], y_pred[indices])                       
        cm2= confusion_matrix(y_test[indices], y_pred[indices], labels=labels)        
        print (cm1.shape == (2,2), cm2.shape == (2,2))                                
    

    在第一个子集中,两个类都出现了;但是在第二个子集中,只有一个类出现了,因此cm1矩阵的大小不是(2,2)(结果是(1,1))。但是请注意,通过指示 ,总是可以的。

    如果您已经知道标签只能是0或1,您可以只分配labels=[0,1],但是使用 np.unique

        2
  •  0
  •   J. Doe    7 年前

    你可以先检查一下 pred_values 都等于 true_values 00 11 混淆矩阵值 (或 pred\ U值

    X = pd.DataFrame({'f1': [1]*10 + [0]*10,
                      'f2': [3]*10 + [10]*10}).values
    y = np.array([1]*10 + [0]*10)
    model = MultinomialNB()
    kf = KFold(n_splits=5)
    cf = np.array([[0, 0], [0, 0]])
    for train_index, test_index in kf.split(X):
        x_train, x_test = X[train_index], X[test_index]
        y_train, y_test = y[train_index], y[test_index]
        model.fit(x_train, y_train)
        y_pred = model.predict(x_test)
        if all(y_test == y_pred): # if perfect prediction
            cf[0][0] += sum(y_pred == 0) # increment by number of 0 values
            cf[1][1] += sum(y_pred == 1) # increment by number of 1 values
        else:
            cf += confusion_matrix(y_test, y_pred) # else add cf values
    

    的结果 print(cf)

    >> [10  0]
       [0  10]
    

    小心点 过度装配