gpt4 book ai didi

python - 将数组(等级为 1 的形状)馈送到 TensorFlow tf.case

转载 作者:太空宇宙 更新时间:2023-11-04 04:09:18 25 4
gpt4 key购买 nike

按照 tf.case 文档中的这个例子:

def f1(): return tf.constant(17)
def f2(): return tf.constant(23)
def f3(): return tf.constant(-1)
r = tf.case({tf.less(x, y): f1, tf.greater(x, z): f2},
default=f3, exclusive=True)

我想做同样的事情,但允许使用 feed_dict 作为输入,如下图所示:

x = tf.placeholder(tf.float32, shape=[None])
y = tf.placeholder(tf.float32, shape=[None])
z = tf.placeholder(tf.float32, shape=[None])
def f1(): return tf.constant(17)
def f2(): return tf.constant(23)
def f3(): return tf.constant(-1)
r = tf.case({tf.less(x, y): f1, tf.greater(x, z): f2},
default=f3, exclusive=True)
print(sess.run(r, feed_dict={x: [0, 1, 2, 3], y: [1, 1, 1, 1], z: [2, 2, 2, 2]}))
# result should be [17, -1, -1, 23]

所以,基本上我想提供三个长度相等的 int 数组,并接收一个包含 17、23 或 -1 的 int 值数组。不幸的是,上面的代码给出了错误:

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

我知道,tf.case 需要 bool 标量张量输入值,但有什么方法可以实现我想要的吗?我也尝试了 tf.cond 但没有成功。

最佳答案

使用tf.where为此,例如像这样( broadcasting support for tf.where seems to be on its way ,但据我所知还没有,所以你必须确保所有参数都具有相同的大小和一个向量,或者 tf.filltf.tile 。 ..).

import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
x = tf.placeholder(tf.float32, shape=[None])
y = tf.placeholder(tf.float32, shape=[None])
z = tf.placeholder(tf.float32, shape=[None])
ones = tf.ones_like(x)
r = tf.where(x < y, 17 * ones, tf.where(x > z, 23 * ones, -ones))
print(sess.run(r, feed_dict={x: [0, 1, 2, 3], y: [1, 1, 1, 1], z: [2, 2, 2, 2]}))
# [17. -1. -1. 23.]

关于python - 将数组(等级为 1 的形状)馈送到 TensorFlow tf.case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56635027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com