tensorflow如何添加if语句?

2024-10-02 22:38:21 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我要做的事情的简化版本:

result = sess.run(cost, feed_dict={X: np.matrix(np.array(values[0][1]))})

if result > Z:
    print('A')
else:
    print('B')

但当我尝试运行这个程序时,我得到:

^{pr2}$

怎么解决这个问题?在

编辑:

def getCertitude1(result):
    return (Z/result)*100

def getCertitude2(result):
    return (result/Z)*100

result = sess.run(cost, feed_dict={X: np.matrix(np.array(reps[0][1]))})

if result is not None:
    a = tf.cond(tf.less(result, Z), lambda: getCertitude1(result), lambda: getCertitude2(result))     
    print("a: " + str(a))                   

结果是a: : Tensor("cond/Merge:0", shape=(?, 128), dtype=float32)


Tags: runreturnifdeffeednpresultarray
1条回答
网友
1楼 · 发布于 2024-10-02 22:38:21

Tensorflow对象不能与常规python对象和函数一起使用。张量流就是这样设计的。if/else块、forwhile和其他python内容应该替换为适当的tensorflow操作,比如tf.while_looptf.cond等等。这些操作使用的是主要的tensorflow对象张量,不能与python对象一起使用。在

从tensor获取python对象的唯一方法是调用这个对象上的tf.Session对象。因此,当您调用sess.run()时,您将得到python对象(更准确地说,是numpyone)。显然,Z是一个tf.Tensor,它不应该与python对象result混合使用。在

您可以使用另一个sess.run()Z求值,然后切换到常规的python操作,或者正确使用tf.cond并基于cost和{}的值创建子图,这两个值都是张量。在

相关问题 更多 >