我想在imagenet2012数据集中计算top5,但我不知道如何在keras中做到这一点。 拟合函数只能算出前1精度。
答案 0 :(得分:20)
如果你刚刚在topK之后,你可以直接调用tensorflow(你不会说你正在使用哪个后端)。
from keras import backend as K
import tensorflow as tf
top_values, top_indices = K.get_session().run(tf.nn.top_k(_pred_test, k=5))
如果您需要精度指标,可以将其添加到模型'top_k_categorical_accuracy'。
model.compile('adam', 'categorical_crossentropy', ['accuracy', 'top_k_categorical_accuracy'])
history = model.fit(X_train, y_train, nb_epoch=3, validation_split=0.2)
Train on 31367 samples, validate on 7842 samples
Epoch 1/3
31367/31367 [==============================] - 6s - loss: 0.0818 - acc: 0.9765 - top_k_categorical_accuracy: 0.9996 -
...
此指标的默认k
为5,但如果您想将其更改为3,则可以按如下方式设置模型:
top3_acc = functools.partial(keras.metrics.top_k_categorical_accuracy, k=3)
top3_acc.__name__ = 'top3_acc'
model.compile('adam', 'categorical_crossentropy', ['accuracy', top3_acc])
答案 1 :(得分:1)
弗兰克·威尔逊(Frank Wilson)的答案可能是更正式的答案,但您也可以这样计算。
top1 = 0.0
top5 = 0.0
class_probs = model.predict(x)
for i, l in enumerate(labels):
class_prob = class_probs[i]
top_values = (-class_prob).argsort()[:5]
if top_values[0] == l:
top1 += 1.0
if np.isin(np.array([l]), top_values):
top5 += 1.0
print("top1 acc", top1/len(labels))
print("top1 acc", top5/len(labels))
答案 2 :(得分:0)
您可以使用 tf.keras.metrics.TopKCategoricalAccuracy(k)。默认情况下 k=5。
文档在这里:https://keras.io/api/metrics/accuracy_metrics/#topkcategoricalaccuracy-class。
这是在model.compile中使用它的代码示例。
import tensorflow as tf
model.compile(optimizer, loss,
metrics= [tf.keras.metrics.TopKCategoricalAccuracy(k=5)]
)