当未启用急切执行时,Tensor对象是不可迭代的.要遍历此张量,请使用`tf.map_fn`. [英] Tensor` objects are not iterable when eager execution is not enabled. To iterate over this tensor use `tf.map_fn`

查看:385
本文介绍了当未启用急切执行时,Tensor对象是不可迭代的.要遍历此张量,请使用`tf.map_fn`.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create my own loss function:

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

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

It should create permutations of predicted vector, and return the smallest loss.

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

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

error. I fail to find any source for this error. Why is this happening?

谢谢你.

推荐答案

之所以发生错误,是因为y_pred是张量(在没有急切执行的情况下是不可迭代的)和

The error is happening because y_pred is a tensor (non iterable without eager execution), and itertools.permutations expects an iterable to create the permutations from. In addition, the part where you compute the minimum loss would not work either, because the values of tensor t are unknown at graph creation time.

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

Instead of permuting the tensor, I would create permutations of the indices (this is something you can do at graph creation time), and then gather the permuted indices from the tensor. Assuming that your Keras backend is TensorFlow and that y_true/y_pred are 2-dimensional, your loss function could be implemented as follows:

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

这篇关于当未启用急切执行时,Tensor对象是不可迭代的.要遍历此张量,请使用`tf.map_fn`.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆