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

Dar*_*lyn 11 python artificial-intelligence neural-network conv-neural-network keras

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

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
Run Code Online (Sandbox Code Playgroud)

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

   "`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`.
Run Code Online (Sandbox Code Playgroud)

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

谢谢你.

rvi*_*nas 10

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

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

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
Run Code Online (Sandbox Code Playgroud)