Keras-精度和召回率大于1(多种分类) [英] Keras - Precision and Recall is greater than 1 (Multi classification)

查看:351
本文介绍了Keras-精度和召回率大于1(多种分类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用keras中的CNN处理多分类问题.我的精确度和召回率总超过1,根本没有任何意义.以下是我的代码,我在做什么错了?

I am working on a multi classification problem using CNN's in keras. My precision and recall score is always over 1 which does not make any sense at all. 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])

推荐答案

我能够弄清楚这一点.一旦对所有分类标签进行一次编码,上述代码就可以完美地工作.另外,请确保没有sparse_categorical_crossentropy作为损失函数,而仅使用categorical_crossentropy.

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.

如果您希望将分类值转换为Keras中的一键编码值,则可以使用以下代码:

If you wish to convert your categorical values to one-hot encoded values in Keras, you can just use this code:

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

您必须执行上述操作的原因已在Keras文档中指出:

The reason you have to do the above is noted in Keras documentation:

",当使用categorical_crossentropy损失时,您的目标应采用分类格式(例如,如果您有10个类别,则每个样本的目标应是全零的10维向量,但对应的索引处为1为了将整数目标转换为分类目标,可以使用Keras实用程序to_categorical"

"when using the categorical_crossentropy loss, your targets should be in categorical format (e.g. 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"

这篇关于Keras-精度和召回率大于1(多种分类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆