首页 > 解决方案 > 访问张量中索引处的元素

问题描述

我正在尝试在 Keras 中构建自定义损失函数。我的模型是一个图像着色 CNN,其想法是根据每个预测像素在我的数据集上先前测量的像素颜色分布中的稀有性来惩罚它。损失函数从分布中获取每个颜色值与像素总数的预先计算的比率。所以我必须获取每个真实像素的系数,必须在当前像素值索引处的比率数组中访问该系数。

我在 NumPy 中构建了“哑”损失版本,它按预期工作。当我尝试使用 tf.map_fn 将其转换为 Tensorflow 时,看不到实现该功能的方法。我尝试运行会话或评估张量失败。

下面是我的损失函数。

def color_rebalancing_loss(ratios):

    def loss(y_true, y_pred):
        err = np.absolute(np.subtract(y_true, y_pred))
        pixel_weight = tf.map_fn(lambda x: coefficient(x), y_true)
        return err * pixel_weight

    def coefficient(x):
        x = tf.to_int32(x)
        x = x.eval(session = tf.Session())
        return 1/ratios[x]

    return loss

它在这条线上失败了,

    x = x.eval(session = tf.Session())

出现此错误:

    ValueError: Operation 'loss/activation_1_loss/map/while/TensorArrayReadV3' has been marked as not fetchable.

我在互联网上的搜索没有发现任何潜在的修复,人们建议不要遍历数组,使用内置的 tensorflow 函数,但访问

   ratios[x] 

在这种情况下是必须的。任何建议将不胜感激。

标签: numpytensorflowtensorloss-function

解决方案


推荐阅读