Python 当未启用急切执行时,Tensor` 对象不可迭代。迭代这个张量使用`tf.map_fn`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49592980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tensor` objects are not iterable when eager execution is not enabled. To iterate over this tensor use `tf.map_fn`
提问by Darlyn
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?
错误。我找不到此错误的任何来源。为什么会这样?
Thanks for hel.
谢谢你的帮助。
回答by rvinas
The error is happening because y_pred
is a tensor (non iterable without eager execution), and itertools.permutationsexpects 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.
发生错误是因为它y_pred
是一个张量(在没有急切执行的情况下不可迭代),并且itertools.permutations期望一个可迭代来创建排列。此外,您计算最小损失的部分也不起作用,因为t
在图创建时张量的值是未知的。
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:
我将创建索引的排列而不是排列张量(这是您可以在创建图形时执行的操作),然后从张量中收集排列的索引。假设您的 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