【问题标题】:Indexing tensors in custom loss function with Keras使用 Keras 在自定义损失函数中索引张量
【发布时间】:2020-05-30 07:35:43
【问题描述】:

我在Keras 中使用了自定义损失函数。 这是函数:

def custom_loss(groups_id_count):
  def listnet_loss(real_labels, predicted_labels):
    losses = tf.placeholder(shape=[None], dtype=tf.float32) # Tensor of rank 1
    for group in groups_id_count:
      start_range = 0
      end_range = (start_range + group[1])
      batch_real_labels = tf.slice(real_labels, [start_range, 1, None], [end_range, 1, None])
      batch_predicted_labels = tf.slice(predicted_labels, [start_range, 0, 0], [end_range, 0, 0])
      loss = -K.sum(get_top_one_probability(batch_real_labels)) * tf.math.log(get_top_one_probability(batch_predicted_labels))
      losses = tf.concat([losses, loss], axis=0)
      start_range = end_range
    return K.mean(losses)
  return listnet_loss

我会从start_rangeend_range 得到real_labelspredicted_labelsitems,但当前代码返回异常:

错误:

TypeError: Failed to convert object of type <class 'list'> to Tensor.
Contents: [0, 1, None]. Consider casting elements to a supported type.

我不知道该怎么办,因为这是我第一次接触TensorFlowKeras。 如何使用张量索引获取项目?提前致谢。

【问题讨论】:

  • 嗨@pairon,请提供最低可重现代码。

标签: python tensorflow keras tensor


【解决方案1】:

错误是由于tf.placeholder中指定的Noneshape,并且它正在发生在该行中,

  batch_real_labels = tf.slice(real_labels, [start_range, 1, None], [end_range, 1, None])

解决方案是将variable 定义为placeholdershape,并使用variable 而不是None

相同的代码如下所示:

h = tf.shape(losses)[0]
batch_real_labels = tf.slice(real_labels, [start_range, 1, h], [end_range, 1, h])

此解决方法将修复错误,TypeError: Failed to convert object of type &lt;class 'list'&gt; to Tensor. Contents: [0, 1, None]. Consider casting elements to a supported type.,但后续代码行可能会导致其他错误。

如果您遇到任何其他错误,请分享error,包括函数get_top_one_probability 的完整代码以及使用该函数要实现的目标custom_loss,我很乐意为您提供帮助.

刚接触TensorflowKeras,祝你学习愉快!

【讨论】:

    【解决方案2】:

    请使用后端函数K.reshape根据自己的知识对输入标签和输入预测进行重塑。

    对于标签,输入是未定义的(?,?),因此您需要通过重塑它来修复它。否则,您无法对其进行索引。

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 2021-02-08
      • 2020-01-08
      • 2021-01-03
      • 2019-07-28
      • 2020-12-19
      • 2017-12-18
      • 2020-03-27
      • 1970-01-01
      相关资源
      最近更新 更多