我正在使用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 recalldef 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 precisionmodel.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy',recall,precision])
回答:
我已经解决了这个问题。一旦你对所有分类标签进行独热编码,上述代码就能完美运行。另外,确保你的损失函数不是sparse_categorical_crossentropy,而是使用categorical_crossentropy。
如果你希望在Keras中将分类值转换为独热编码值,你可以使用以下代码:
from keras.utils import to_categoricaly_train = to_categorical(y_train)
你需要执行上述操作的原因在Keras文档中有说明:
“当使用categorical_crossentropy损失函数时,你的目标应该采用分类格式(例如,如果你有10个类别,每个样本的目标应该是10维向量,除了对应样本类别的索引位置为1外,其余位置均为0)。为了将整数目标转换为分类目标,你可以使用Keras工具to_categorical。”