繁体   English   中英

Tensorflow 2:如何在自定义损失中使用张量 y_true 的形状?

[英]Tensorflow 2: How can I use the shape of tensor y_true in custom loss?

我将列表a传递给我的自定义 function ,我想在将其转换为常量张量后对其进行tf.tile 我平铺的时间取决于y_true的形状。 我不知道如何将y_true的形状作为整数。 这是代码:

def getloss(a):
    a = tf.constant(a, tf.float32)
    def loss(y_true, y_pred):
        a = tf.reshape(a, [1,1,-1])
        ytrue_shape = y_true.get_shape().as_list() #????
        multiples = tf.constant([ytrue_shape[0], ytrue_shape[1], 1], tf.int32)
        a = tf.tile(a, multiples)
        #...
    return loss

我尝试过y_true.get_shape().as_list()但它报告错误,因为在编译 model 时第一个维度(批量大小)为None 有什么办法可以在这里使用y_true的形状吗?

在构建 model 期间尝试访问张量的形状时,当并非所有形状都已知时,最好使用tf.shape 它将在运行 model 时进行评估,如文档中所述:

tf.shape 和 Tensor.shape 在 Eager 模式下应该相同。 在 tf.function 或 compat.v1 上下文中,直到执行时才可能知道所有维度。 因此,在为图形模式定义自定义层和模型时,更喜欢动态 tf.shape(x) 而不是 static x.shape。

ytrue_shape = tf.shape(y_true)

这将产生一个张量,所以使用 TF ops 来获得你想要的:

multiples = tf.concat((tf.shape(y_true_shape)[:2],[1]),axis=0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM