如果未启用eager执行,则Tensor`对象不可迭代。要迭代此张量,请使用`tf.map_fn`

时间:2018-03-31 22:19:51

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

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

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`.

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

谢谢你。

1 个答案:

答案 0 :(得分:8)

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

而不是置换张量,我会创建索引的排列(这是你可以在图形创建时做的事情),然后从张量中收集置换索引。假设你的Keras后端是TensorFlow并且y_true / y_pred是2维的,你的损失函数可以实现如下:

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