在四维预测和目标上提高分类互熵的性能

时间:2019-12-23 14:19:55

标签: python tensorflow machine-learning keras

我在tensorflow中实现了一个神经网络,该神经网络可以获取一批图像并预测形状为(batch_size,9,9,10)的张量

对于批次中的每个图像,目标(和预测)看起来像这样。 我们预测图像的宽度为9,高度9为深度10。每个像素的深度对应一个类别,因此我们有10个类别。

例如带有softmax的pixel(0,0)的预测看起来像这样[0,0.8,0,0,0,0,0.2,0,0,0] 像素(0,0)的目标看起来像这样[0,1,0,0,0,0,0,0,0]

我想在这两个张量之间使用经典的交叉熵。

目前我的损失是这样实现的:

def calculate_loss(prediction, target):
    '''
    prediction and target have shape (batch_size, 9, 9, 10)
    '''
    loss = 0
    for batch in range(0, BATCH_SIZE):
        for width in range(0,9):
            for heigth in range(0,9):
                loss += tf.losses.categorical_crossentropy(target[batch][width][height] , prediction[batch][width][height])
return loss

但是如果批次大小较大(1024),此计算将花费20秒。 这太慢了。 在Tensorflow / Keras中是否有已经实现的功能可以改善这种损失的性能? 还是您知道我是否可以更改代码以提高性能?

1 个答案:

答案 0 :(得分:0)

tf.nn.softmax_cross_entropy_with_logits(target, prediction)

是答案。 然后,我可以减少总和的输出值来获得相同的结果。 不要忘记删除模型中的sofmax层。