【问题标题】:Tensor Comparison and Manipulation张量比较和操作
【发布时间】:2021-06-14 19:40:35
【问题描述】:

我正在尝试在 Keras 中编写自定义损失函数。我有y_predy_true。两者都是张量,值可以是01。因此,例如,y_true 是:

[0,1,0,1]

y_pred 是:

[1,1,0,0].

我正在尝试比较这两个张量以输出以下内容:

[-0.7, 2.5, 0.025, -0.1]

逻辑是这样的:

y_true y_pred result
0 1 -0.7
1 1 2.5
0 0 0.025
1 0 -0.1

我不确定使用各种 tensorflow 操作来实现这一目标的最佳方式。我的损失函数将采用 logits,所以我正在尝试这样做:

def roi_loss_fn(y_true, y_pred):
  print("Y_TRUE-----")
  print(y_true)
  print("Y_PRED-----")
  print(y_pred)

  softmax = tf.nn.softmax(y_pred)
  print("SOFTMAX-----")
  print(softmax)

  #iterate or manipulate tensors to compare boolean values according to the table

编辑:

这是我当前的损失函数,但它抛出错误:ValueError: No gradients provided for any variable

def roi_loss_fn(y_true, y_pred):

  y_pred = tf.argmax(y_pred, axis=1)
  tf.reshape(y_pred, tf.shape(y_true))

  t_equal = tf.equal(y_true, y_pred)
  t_loss = tf.Variable(tf.zeros_like(y_true, dtype=tf.float32))

  idx = 0
  for x1 in t_equal:
    if x1 == True:
      # Value is either "successful investment" (e.g., 2.5) or "successfully passed" (e.g., 0.025)
      if y_true[idx] == 0:
        t_loss[idx].assign(2.5)
      else:
        t_loss[idx].assign(0.025)
    else:
      # Value is either "bad investment" (e.g., -0.7) or "missed investment" (e.g., -1.4)
      if y_true[idx] == 0:
        t_loss[idx].assign(-0.7)
      else:
        t_loss[idx].assign(-1.4)
    idx += 1
  
  return t_loss

【问题讨论】:

  • 我最终选择了以下方法,但不确定这是否是最好的方法:``` for idx, x1 in enumerate(t_equal): if x1 == True: # Value is either "successful投资”(例如,2.5)或“成功通过”(例如,0.025) if t1[idx] == 0: t_new[idx].assign(2.5) else: t_new[idx].assign(0.025) else: # Value如果 t1[idx] == 0: t_new[idx].assign(-0.7) else: t_new[idx].assign (-1.4) ```
  • 损失函数的负值不是一个好主意。如果一个大的负值加上一个大的正值损失总和为零,那可能会停止训练。
  • 谢谢@TouYou。我可以编辑这些参数,所以它不是负面的。话虽如此,我只是想让损失函数首先工作。目前它正在抛出错误,所以我无法在我的模型上运行 fit 函数。

标签: python tensorflow machine-learning keras tf.keras


【解决方案1】:

一种解决方案是使用np.where() 进行比较和分配。

让我们以你所说的y_truey_pred为例:

y_true = tf.constant([0,1,0,1])
y_pred = tf.constant([1,1,0,0])

然后,为了比较它们并分配所需的值,损失函数可能是这样的:

def roi_loss_fn(y_true, y_pred):  
   c = tf.zeros(y_pred.shape)
   c = np.where(y_true<y_pred, -0.7, c)
   c = np.where(y_true>y_pred, -0.1, c)
   c = np.where(y_true+y_pred==2, 2.5, c)
   c = np.where(y_true+y_pred==0, 0.025, c)
   return c

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 2018-01-21
    • 2016-02-26
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多