【问题标题】:"Tensor objects are only iterable when eager execution is enabled" error when trying to create custom loss function in Keras尝试在 Keras 中创建自定义损失函数时出现“张量对象仅在启用急切执行时可迭代”错误
【发布时间】:2019-08-11 19:03:50
【问题描述】:

我正在尝试使用神经网络进行 SVD。我的输入是一个矩阵(假设只有 4x4 矩阵),输出是一个表示分解形式的向量(假设输入是 4x4,这将是一个 36 个元素的向量,其中 U 有 16 个元素,S 有 4 个元素,还有 16 个元素对于 V.T)。

我正在尝试定义一个自定义损失函数,而不是在分解形式上使用 MSE 之类的东西。因此,我不想比较 36 个长度向量的损失,而是计算重建矩阵之间的损失。所以如果A = U * S * V.T(实际)和A' = U' * S' * V.T'(预测),我想计算A和A'之间的损失。

我对 tensorflow 和 keras 还很陌生,所以我可能会做一些幼稚的事情,但这是我目前所拥有的。虽然逻辑对我来说似乎没问题,但我收到了 TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn. 我不知道为什么会这样以及如何解决它?另外,我是否需要像我目前所做的那样将reconstruct_matrix 的输出展平,还是应该保持原样?

# This function takes the decomposed matrix (vector of U, S, V.T)
# and reconstructs the original matrix

def reconstruct_matrix(decomposed_vector):
  example = decomposed_vector
  s = np.zeros((4,4))
  for en, i in enumerate(example[16:20]):
    s[en, en] = i
  u = example[:16].reshape(4,4)
  vt = example[20:].reshape(4,4)
  orig = np.matmul(u, s)
  orig = np.matmul(orig, vt)
  return orig.flatten() # Given that matrices are 4x4, this will be a length 16 vector

# Custom loss that essentially computes MSE on reconstructed matrices 

def custom_loss(y_true, y_pred):
    Y = reconstruct_matrix(y_true)
    Y_prime = reconstruct_matrix(y_pred)
    return K.mean(K.square(Y - Y_prime)) 

model.compile(optimizer='adam',
              loss=custom_loss)

注意:我的keras版本是2.2.4,我的tensorflow版本是1.14.0。

【问题讨论】:

  • 张量流版本?在发布问题时始终指定它,因为即使是次要版本,此框架也在改变范式。
  • 好点!我的keras版本是2.2.4,我的tensorflow版本是1.14.0。

标签: python tensorflow keras loss-function svd


【解决方案1】:

在tf1.x 中,Eager Execution 默认是禁用的(2 以后的版本是开启的)。

您必须通过在脚本顶部调用来启用它:

import tensorflow as tf

tf.enable_eager_execution()

此模式允许您使用类似 Python 的抽象来进行流控制(例如,您在代码中使用的 if 语句和 for 循环)。如果它被禁用,您需要使用 Tensorflow 函数(tf.cond 和 tf.while_loop 分别用于 if 和 for)。

更多信息in the docs。

顺便说一句。我不确定是否要展平,但请记住您的 y_true 和 y_pred 需要相同的形状,并且样本必须彼此对应,如果满足了你应该没问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2018-09-10
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多