Tensorflow,多标签精度计算

Tensorflow, multi label accuracy calculation

我正在处理一个多标签问题,我正在尝试确定我的模型的准确性。

我的模特:

NUM_CLASSES = 361

x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS])
y_ = tf.placeholder(tf.float32, [None, NUM_CLASSES])

# create the network
pred = conv_net( x )

# loss
cost = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits( pred, y_) )

# train step
train_step   = tf.train.AdamOptimizer().minimize( cost )

我想用两种不同的方式计算准确度
- 正确预测的所有标签的百分比 - 正确预测所有标签的图像百分比

不幸的是,我只能计算预测正确的所有标签的百分比。

我认为这段代码会计算正确预测所有标签的图像的百分比

correct_prediction = tf.equal( tf.round( pred ), tf.round( y_ ) )

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

此代码预测正确的所有标签的百分比

pred_reshape = tf.reshape( pred, [ BATCH_SIZE * NUM_CLASSES, 1 ] )
y_reshape = tf.reshape( y_, [ BATCH_SIZE * NUM_CLASSES, 1 ] )

correct_prediction_all = tf.equal( tf.round( pred_reshape ), tf.round( y_reshape ) )

accuracy_all = tf.reduce_mean( tf.cast(correct_prediction_all, tf.float32 ) )

不知何故,属于一张图片的标签的一致性丢失了,我不确定为什么。

我认为您代码中的错误在:correct_prediction = tf.equal( tf.round( pred ), tf.round( y_ ) ).

pred 应该是 unscaled logits(即没有最终的 sigmoid)。

这里你要比较sigmoid(pred)y_的输出(都在区间[0, 1])所以你必须写:

correct_prediction = tf.equal(tf.round(tf.nn.sigmoid(pred)), tf.round(y_))

然后计算:

  • 所有标签的平均准确度:
accuracy1 = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  • 所有标签都需要正确的准确性:
all_labels_true = tf.reduce_min(tf.cast(correct_prediction), tf.float32), 1)
accuracy2 = tf.reduce_mean(all_labels_true)
# to get the mean accuracy over all labels, prediction_tensor are scaled logits (i.e. with final sigmoid layer)
correct_prediction = tf.equal( tf.round( prediction_tensor ), tf.round( ground_truth_tensor ) )
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# to get the mean accuracy where all labels need to be correct
all_labels_true = tf.reduce_min(tf.cast(correct_prediction, tf.float32), 1)
accuracy2 = tf.reduce_mean(all_labels_true)

参考:https://gist.github.com/sbrodehl/2120a95d57963a289cc23bcfb24bee1b