【问题标题】:Replace a slice of one tensor with another bigger Tensor in Python在 Python 中用另一个更大的张量替换一个张量的一部分
【发布时间】:2021-07-13 05:50:38
【问题描述】:

在 Tensorflow 2.4.1 中的自定义损失函数中。和 Python 3.7 y_pred 张量的形状为 (batch, 21,21,3) 其中 3 是模型中的类数

y_true 是一个整数,表示模型应该分类的正确类别。 为了进行计算,创建了一个形状为 y_pred 的 zeros 张量,名称为 y_true_array

应该有比以下解决方法更简单的方法:

  y_true_array= tf.zeros_like(y_pred, dtype=tf.float32, name="loss_tru_array")
  one_class_shape = y_pred.shape[:-1] + [1]

  ones =tf.ones(one_class_shape, dtype=tf.float32, name="loss_ones")
  zeros = tf.zeros(one_class_shape, dtype=tf.float32, name="loss_ones")
  if (y_true == 0):
    y_true_array = tf.concat([ones, zeros, zeros], axis=-1)
  elif (y_true == 1):
    y_true_array = tf.concat([zeros, ones, zeros], axis=-1)
  elif (y_true == 2):
    y_true_array = tf.concat([zeros, zeros, ones], axis=-1)

例如 对于大小为 (3, 2, 3) 的 y_pred 数组。第二维中的 2 是特征尺寸。如果 y_true = 1,y_true_array 应该是

[ [[0, 1, 0],[0,1,0]] ,
[[0, 1, 0],[0, 1, 0]] ,
[[0, 1, 0],[0,1,0]] ]

【问题讨论】:

    标签: python tensorflow loss-function


    【解决方案1】:

    在我看来,您只是对y_true 中的类标签进行一次性编码?

    y_true_array = tf.one_hot(y_pred, depth=3)
    

    基本上,如果你有 y_pred 数组

    [0, 1, 2]
    

    y_true_array 将是,

    [
     [1, 0, 0],
     [0, 1, 0],
     [0, 0, 1],
    ]
    

    【讨论】:

    • 不,不是。例如对于大小为 (3, 2, 3) 的 y_pred 数组。第二维中的 2 是特征尺寸。如果 y_true = 1,y_true_array 应该是: t = np.array([ [[0, 1, 0],[0,1,0]] , [[0, 1, 0],[0, 1, 0] ] , [[0, 1, 0],[0,1,0]] ])
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多