tensorflow比较两个tensor大小

# 出错情况:

import tensorflow as tf
import numpy as np

a = tf.placeholder(tf.float32, shape=([2]))

b = tf.placeholder(tf.float32, shape=([2]))

# 直接用if a[0]<b[0]会出现Using a `tf.Tensor` as a Python `bool` is not allowed情况

if tf.less(a[0], b[0]) is True:   # 或者写成is not None 也都不对的
    c = a
    print("a is small")
else:
    print('b is small')
    c = b

sess = tf.Session()

feed_dict = {a:np.array([1, 2]),
             b:np.array([3, 4])
             }

_c, _, _= sess.run([c, a, b], feed_dict=feed_dict)
print(_c)

feed_dict = {a:np.array([5, 2]),
             b:np.array([2, 4])
             }

扫描二维码关注公众号,回复: 2254529 查看本文章

bc, _, _ = sess.run([c, a, b], feed_dict=feed_dict)
print(bc)
sess.close()
 

# 上面输出是

[ 3.  4.]
[ 2.  4.]
 一直只输出b的值,并没有判断

# tf为1.3版本 

# 解决方法:if else语句好像没有起作用 所以判断语句都用tf.cond()来代替就可以了

import tensorflow as tf
import numpy as np

a = tf.placeholder(tf.float32, shape=([2]))
b = tf.placeholder(tf.float32, shape=([2]))
d = tf.constant(True)

get = tf.greater(b[0], a[0])

c = tf.cond(tf.greater(b[0], a[0]),  lambda: a,  lambda: b)  # 不能用if else

sess = tf.Session()

feed_dict = {a:np.array([1, 2]),
             b:np.array([3, 4])
             }

gg, _c, _a, _b= sess.run( [get, c, a[0], b[0]], feed_dict=feed_dict)
print(gg, _c, _a, _b)

feed_dict = {a:np.array([5, 2]),
             b:np.array([2, 4])
             }

_g, bc, aa, bb = sess.run([get, c, a[0], b[0]], feed_dict=feed_dict)
print(_g, bc, aa, bb)
sess.close()
 

# 输出会输出小的数了:

True [ 1.  2.] 1.0 3.0
False [ 2.  4.] 5.0 2.0
 

# tensorflow里如果把tensor和numpy if and or while这些混用的都是会有问题,所以一般还是不要用if while这些numpy下的语句了。包含or not这些逻辑运算等tensorflow都有自己的定义的(tf.logical_and,...)。还是用tensor统一的好

猜你喜欢

转载自blog.csdn.net/MD2017/article/details/81102904