【问题标题】:Using tf.cond with a condition comparing two tensors将 tf.cond 与比较两个张量的条件一起使用
【发布时间】:2021-08-13 19:49:02
【问题描述】:

我正在尝试编写以下函数:

我已经使用 numpy 在 python 中实现了它,但需要将其重新编码为 tensorflow:

input_array = np.array([0.2, 2.1, 4.5, 6.7, 8.1, 10.0])

def f_funct(input_array):
    arr = np.ones(len(input_array))
    delta_vec = np.multiply(arr,6.0/29.0)
    res = np.where(input_array>np.power(delta_vec,3), np.cbrt(input_array), 
             input_array/(3*np.power(delta_vec,2)) + 4.0/29.0)
    return res

print(f_funct(input_array))

我试过了:

# convert input from np.array to tensor
def np_array_to_tensor(input_array):
    input_array = tf.convert_to_tensor(input_array, dtype=tf.float64)
    return input_array

input_tensor = np_array_to_tensor(tf.constant(input_array)) 
arr = tf.ones([tf.size(input_tensor)], tf.float64)
delta_vec = tf.math.multiply(arr,tf.math.divide(6.0,29.0))

res1 = tf.math.divide(4.0,29.0) 
res2 = tf.divide(input_tensor,(3*tf.pow(delta_vec,2)))
    
res = tf.cond(input_tensor>tf.pow(delta_vec,3), 
             lambda: tf.pow(input_tensor,1.0/3.0), 
             lambda: tf.add(res2,res1))


with tf.Session() as sess:  
    print(input_tensor.eval())
    print(arr.eval())
    print(delta_vec.eval())
    print(res1)
    print(res2.eval())
    print(res.eval())

但这会引发错误,因为条件只能使用标量。

ValueError: Shape must be rank 0 but is rank 1 for 'cond_13/Switch' (op: 'Switch') with input shapes: [6], [6].

由于我的输入数组相当大,我宁愿坚持使用数组/张量。是否可以使用基于条件的张量来做到这一点?

如果有任何建议,我将不胜感激。谢谢。

【问题讨论】:

  • @Lescurel 谢谢。我已经修好了。

标签: arrays numpy tensorflow conditional-statements


【解决方案1】:

您想要的不是tf.cond,而是tf.where(condition, x, y),它返回来自xy 的元素,具体取决于condition,与 完全相同。 (TF 1.x 中tf.where 的广播规则与 numpy 有点不同,所以你可能更喜欢tf.where_v2,如果它在你的 tensorflow 1.x 版本中可用)。

res = tf.where(input_tensor>tf.pow(delta_vec,3),
               tf.pow(input_tensor,1.0/3.0),
               tf.add(res2,res1))

使用您的 input_tensor 在会话中运行:

>>> sess.run(res)
array([0.58480355, 1.28057916, 1.65096362, 1.88520363, 2.00829885,
       2.15443469])

【讨论】:

  • 非常感谢。您的解决方案正是我所需要的。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多