【问题标题】:Using loops, tf.Variable, tf.tensorarray inside a tf.function function in tensorflow在 tensorflow 中的 tf.function 函数中使用循环、tf.Variable、tf.tensorarray
【发布时间】:2021-08-31 01:48:45
【问题描述】:

我一直试图让它工作一段时间,但我不知道如何。我尝试了十几种组合。

我要做的是获取输入数组,比较每个元素以查看其是正数还是负数。根据积极性或消极性应用独特的转换。取平均值并返回结果。这是我拥有的,但它不起作用。

编辑:我最近的尝试

@tf.function
def transform(x, y):
    et = tf.math.subtract(x, y)
    et_variable = tf.Variable(et)

    max_loop = tf.shape(x)[0]

    loss = tf.TensorArray(tf.float32, size=et.shape[0], clear_after_read=False)
    loss = loss.unstack(et_variable)

    i = tf.constant(0)
    while tf.math.less(i, max_loop):
        if loss.gather([i])[0] > 0:
            val = 3 * loss.gather([i])[0]
        else:
            val = 2 * loss.gather([i])[0]
        loss = loss.scatter([i], value=[val])
        i = tf.Variable(i)
        i = i + 1
        i = tf.constant(i)
    return(K.mean(loss.stack()))

我收到一个错误:

ValueError: condition of if statement expected to be `tf.bool` scalar, got Tensor("loss_funk/while/Greater:0", shape=(11,), dtype=bool); to check for None, use `is not None`

我尝试过使用 tf.Variable 和 tf.tensorarray,但都不能使用 tf.function。

【问题讨论】:

    标签: python tensorflow tensor


    【解决方案1】:

    以下是满足您期望的示例。 Tensor没有gather_nd,是tensorflow的API。我的 tensorflow 版本是 2.3

    import numpy as np
    import tensorflow as tf
    from tensorflow.keras import backend as K
    
    y_true = np.random.normal(size=(30, 50)).astype('float32')
    x = np.random.normal(size=(30, )).astype('float32')
    y = np.random.normal(size=(30, )).astype('float32')
    
    
    @tf.function
    def transform(x, y):
        et = tf.math.subtract(x, y)
        max_loop = tf.shape(y_true)[0]
        res = tf.TensorArray(tf.float32, size=et.shape[0], clear_after_read=False)
        i = tf.constant(0)
        while tf.math.less(i, max_loop):
            if tf.gather_nd(et, [i]) > 0:
                val = 0.03 * tf.gather_nd(et, [i])
            else:
                val = 0.05 * tf.gather_nd(et, [i])
            res = res.write(i, val)
            i = i + 1
        return K.mean(res.stack())
    
    
    transform(x, y)
    

    【讨论】:

    • 谢谢,但没用。我收到一条错误消息: if tf.gather_nd(et, [i]) > 0: ValueError: condition of if statement expected to be tf.bool scalar, got Tensor("transform/while/Greater:0", shape =(11,), dtype=bool);
    • 你的 tensorflow 版本是什么?这项工作在 tf 2.3
    • 好的,它适用于无头 linux 服务器,但不适用于我的 windows 机器?
    • 似乎与平台无关。我猜你的 x 是二维张量?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2022-06-13
    • 1970-01-01
    相关资源
    最近更新 更多