LoginSignup
0
1

More than 1 year has passed since last update.

ValueError: Classification metrics can't handle a mix of multilabel-indicator and binary targetsの解決法が分からないから書いた。

Last updated at Posted at 2021-07-09

経緯

2値分類をするディープラーニングの結果(確率結果)に対して混同行列を作りたくて、sklearnのcofusion_matrixを使ったけど、

error
ValueError: Classification metrics can't handle a mix of multilabel-indicator and binary targets

errorが出た、、
原因はテストデータの正解ラベルと推論結果の形式が違うからだと思う。

#テストデータ:one-hot
[[0.1.]
 [0.1.]
   :  
 [1.0.]
 [1.0.]]

#推論結果:確率
[[0.011592121794819832,0.9884079098701477]
                   :
 [0.9900621175765991,0.009937929920852184]]

いろいろ調べて試してみたけどよく分からんし、練習がてら自分で作ってみようと思いました!!

作ったやつ

テストデータは0と1の画像各100枚で、0の画像は正解ラベルが0、1の画像は正解ラベルが1と想定してます。また、分類時の閾値は0.5にしてます。評価しているのは0の画像です。

コード
y_pred = model.predict(X_test)  #テスト

label = Y_test.reshape(-1,1)  #one-hotにする前の正解ラベルをn行1列に変換
result = np.concatenate([label,y_pred], 1)   #正解ラベルと結果を結合->n行3列
np.savetxt("result.txt", result, fmt = "%s", delimiter = " " )  #保存

map = np.array([[0,0],[0,0]])
result = pd.read_csv("result.txt", sep = " ", header = None, dtype = "float32") #ファイルを開く
result = np.array(result)
for col in result:  #ファイルを1行ずつ読み込み
    if col[1] > 0.5:      #predict_0>0.5    
       if col[0] == 0:    #label_0=predict_0
          map[0,0] += 1   
       else:              #label_1=predict_0
          map[0,1] += 1
    if col[2] > 0.5:      #predict_1>0.5
       if col[0] == 1:    #label_1=predict_1
          map[1,1] += 1    
       else:              #label_0=predict_1   
          map[1,0] += 1

print(map)
print("test accuracy:",(map[0,0]+map[1,1])/(map[0,0]+map[1,1]+map[1,0]+map[0,1]))
print("test precision:", (map[0,0])/(map[0,0]+map[0,1]))
print("test recall:", (map[0,0])/(map[0,0]+map[1,0]))
出力
[[99 5]
 [1 95]]
test accuracy:0.97
test precision:0.95192308
test recall:0.99

本当はもっと簡単なやり方あるんだろうけど。。。
よかったら教えてください!!!

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1