【问题标题】:Tensor objects are not iterable when eager execution is not enabled. To iterate over this tensor use tf.map_fn当未启用急切执行时,张量对象不可迭代。要迭代此张量,请使用 tf.map_fn
【发布时间】:2018-09-10 14:10:06
【问题描述】:

我正在尝试创建自己的损失函数:

def custom_mse(y_true, y_pred):
    tmp = 10000000000
    a = list(itertools.permutations(y_pred))
    for i in range(0, len(a)): 
     t = K.mean(K.square(a[i] - y_true), axis=-1)
     if t < tmp :
        tmp = t
     return tmp

它应该创建预测向量的排列,并返回最小的损失。

   "Tensor objects are not iterable when eager execution is not "
TypeError: Tensor objects are not iterable when eager execution is not enabled. To iterate over this tensor use tf.map_fn.

错误。我找不到此错误的任何来源。为什么会这样?

【问题讨论】:

    标签: python neural-network keras artificial-intelligence conv-neural-network


    【解决方案1】:

    发生错误是因为y_pred 是一个张量(没有急切执行的不可迭代),而itertools.permutations 期望一个可迭代的来创建排列。此外,计算最小损失的部分也不起作用,因为张量 t 的值在图创建时是未知的。

    我将创建索引的排列(这是您可以在创建图形时执行的操作),而不是排列张量,然后从张量中收集排列的索引。假设您的 Keras 后端是 TensorFlow,并且 y_true/y_pred 是二维的,您的损失函数可以实现如下:

    def custom_mse(y_true, y_pred):
        batch_size, n_elems = y_pred.get_shape()
        idxs = list(itertools.permutations(range(n_elems)))
        permutations = tf.gather(y_pred, idxs, axis=-1)  # Shape=(batch_size, n_permutations, n_elems)
        mse = K.square(permutations - y_true[:, None, :])  # Shape=(batch_size, n_permutations, n_elems)
        mean_mse = K.mean(mse, axis=-1)  # Shape=(batch_size, n_permutations)
        min_mse = K.min(mean_mse, axis=-1)  # Shape=(batch_size,)
        return min_mse
    

    【讨论】:

    • 我的 y_true/y_pred 实际上是一维向量
    • 这对我来说似乎很奇怪。那么,您是否正在沿批量大小维度进行排列?
    • 好像我不是,请您详细说明一下?我对此很陌生。谢谢。
    • 打印y_pred.get_shape() 会得到什么?如果你得到 2 个数字(最常见),我的答案应该是你所期望的。第一个数字(批量大小)表示您输入网络的示例数量,第二个是输出维度(即每个示例的输出数量)。
    • 奇怪,我得到 (?,40),我使用的是 batch_size = 5
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2018-08-02
    相关资源
    最近更新 更多