Keras - Precision和Recall大于1(多分类)
Keras - Precision and Recall is greater than 1 (Multi classification)
我正在使用 keras 中的 CNN 解决多分类问题。我的准确率和召回率分数总是超过 1,这根本没有任何意义。下面附上我的代码,我做错了什么?
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])
我想通了。一旦您 one-hot 对所有分类标签进行编码,上面的代码就可以完美运行。另外,确保你没有 sparse_categorical_crossentropy 作为你的损失函数,而只是使用 categorical_crossentropy。
如果您希望将分类值转换为 Keras 中的 one-hot 编码值,您可以使用以下代码:
from keras.utils import to_categorical
y_train = to_categorical(y_train)
您必须执行上述操作的原因已在 Keras 文档中注明:
"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 中的 CNN 解决多分类问题。我的准确率和召回率分数总是超过 1,这根本没有任何意义。下面附上我的代码,我做错了什么?
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])
我想通了。一旦您 one-hot 对所有分类标签进行编码,上面的代码就可以完美运行。另外,确保你没有 sparse_categorical_crossentropy 作为你的损失函数,而只是使用 categorical_crossentropy。
如果您希望将分类值转换为 Keras 中的 one-hot 编码值,您可以使用以下代码:
from keras.utils import to_categorical
y_train = to_categorical(y_train)
您必须执行上述操作的原因已在 Keras 文档中注明:
"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"