【问题标题】:Process y_pred and y_true chunk wise in custom loss function in Tensorflow在 Tensorflow 的自定义损失函数中处理 y_pred 和 y_true 块
【发布时间】:2020-09-27 15:52:31
【问题描述】:

在我的 Tensorflow 模型中,y_pred 包含从 0 到 1 的概率,而 y_true 包含 0 和 1 的标签。

在我的自定义损失函数中,我想使用 4(或 n)对 y_true 和 y_pred 连续对的信息。

在 numpy 中我可以做这样的事情

y_true=np.array([1,1,1,1,0,0,0,])
y_pred=np.array([0.5,0.5,0.5,0.5,0.2,0.2,0.2,0.2])

def custom_loss(y_true, y_pred):
    n=len(t)
    res= 0
    for i in range(0,n,4):
        res += np.sum(y_true[i:i+4])-np.sum(y_pred[i:i+4])
    return res

有没有办法在 Tensorflow 中使用张量来实现这一点?

我使用的是 TensorFlow 2.2.0 版和 python 3.8

【问题讨论】:

  • len(y_true) % 4 == 0?还是有时更少?
  • 尽管如此,你没有理由四乘四地拿走它们

标签: python tensorflow


【解决方案1】:

当心len(y_true) % 4 != 0

@tf.function
def custom_loss_tf(y_true, y_pred):
  length = tf.shape(y_true)[0]
  end_i = length % 4
  start_y_true, end_y_true = y_true[:length-end_i], y_true[length-end_i:]
  start_y_pred, end_y_pred = y_pred[:length-end_i], y_pred[length-end_i:]
  sum_start_y_true = tf.reduce_sum(tf.reshape(start_y_true, (-1,4)), axis=0)
  sum_start_y_pred = tf.reduce_sum(tf.reshape(start_y_pred, (-1,4)), axis=0)
  res = tf.reduce_sum(tf.cast(sum_start_y_true, tf.float32)) - tf.reduce_sum(tf.cast(sum_start_y_pred, tf.float32))
  res_ending = tf.reduce_sum(tf.cast(end_y_true, tf.float32) - tf.cast(end_y_pred, tf.float32))
  return res_ending + res

不过,您的函数没有多大意义,您正在计算总和的总和。你不能总结一切吗?

【讨论】:

  • 是的,这个函数没有意义,我只是想知道如何处理成块的数组。
猜你喜欢
  • 2018-04-02
  • 2016-12-05
  • 2020-09-21
  • 2020-03-07
  • 2018-12-30
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 2018-06-10
相关资源
最近更新 更多