简体   繁体   English

Keras-精度和召回率大于1(多种分类)

[英]Keras - Precision and Recall is greater than 1 (Multi classification)

I am working on a multi classification problem using CNN's in keras. 我正在使用在keras中使用CNN的多分类问题。 My precision and recall score is always over 1 which does not make any sense at all. 我的精确度和召回力得分总是超过1,这根本没有任何意义。 Attached below is my code, what am I doing wrong? 以下是我的代码,我在做什么错?

def recall(y_true, y_pred):
     true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
     possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
     recall = true_positives / (possible_positives + K.epsilon())
     return recall

def precision(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    return precision

model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy',recall,precision])

I was able to figure this out. 我能够弄清楚这一点。 The above code works perfectly once you one-hot encode all the categorical labels. 一旦对所有分类标签进行一次编码,上述代码就可以完美地工作。 Also, make sure you do NOT have sparse_categorical_crossentropy as your loss function, and instead just use categorical_crossentropy. 另外,请确保没有sparse_categorical_crossentropy作为损失函数,而仅使用categorical_crossentropy。

If you wish to convert your categorical values to one-hot encoded values in Keras, you can just use this code: 如果您希望将分类值转换为Keras中的一键编码值,则可以使用以下代码:

from keras.utils import to_categorical
y_train = to_categorical(y_train)

The reason you have to do the above is noted in Keras documentation: Keras文档中指出了您必须执行上述操作的原因:

"when using the categorical_crossentropy loss, your targets should be in categorical format (eg if you have 10 classes, the target for each sample should be a 10-dimensional vector that is all-zeros except for a 1 at the index corresponding to the class of the sample). In order to convert integer targets into categorical targets, you can use the Keras utility to_categorical" “当使用categorical_crossentropy损失时,您的目标应采用分类格式(例如,如果您有10个类别,则每个样本的目标应是全零的10维向量,但与该类别对应的索引处为1除外为了将整数目标转换为分类目标,可以使用Keras实用程序to_categorical“

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM