问题描述
我正在尝试创建自己的损失函数:
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
是一个张量(在没有急切执行的情况下是不可迭代的)和 itertools.permutations 期望可迭代从中创建置换.此外,计算最小损失的部分也不起作用,因为张量t
的值在图形创建时未知.
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
这篇关于未启用急切执行时,张量对象不可迭代.要遍历此张量,请使用tf.map_fn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!