问题现场:
import tensorflow as tf
parsed_example = {
"label":[[1, 1, 1, 0],
[0, 1, 1, 0],
[1, 1, 1, 0]],
"ot": [[1, 1, 1, -1],
[0, 1, 1, 0],
[1, 1, 1, 0]],
}
label = tf.slice(tf.cast(parsed_example["label"], tf.int32), [0, 0], [-1, 1])
sess = tf.Session()
label = sess.run(label)
print label
ot = tf.slice(tf.cast(parsed_example["label"], tf.int32), [0, 0], [-1, 1])
ot = sess.run(ot)
print ot
test = tf.cond(ot == 1, 0, 1)
test = sess.run(test)
print test
解决:
typyerror表示:true_fn
或false_fn
是不可调用的。(说明上面的代码中的第二个参数和第三个参数类型错误,并且不是tensor,返回结果必须是tensor。)
test = tf.cond(ot == ot1, lambda: tf.add(ot, ot), lambda : tf.add(ot1, ot1))
将fn改为参数后,报错:
raise TypeError("pred must not be a Python bool")
TypeError: pred must not be a Python bool
解决:
个类型错误,或者不兼容的问题,Python中的True不是tf.bool类型,所以导致不兼容,只要定义的时候加上type就行了,举个例子:
tf.cast(True, tf.bool)
tf.cond()用法
在TensorFlow中,tf.cond()类似于c语言中的if...else...,用来控制数据流向,但是仅仅类似而已,其中差别还是挺大的。关于tf.cond()函数的具体操作,参考了tf的说明文档。
重点:
- 输入参数中pred的类型必须是tensorflow的bool类型(tf.bool,可通过tf.cast(True, tf.bool)来转换)
- fnq'和‘fn2’返回的是非零的且类型相同的输出。得是函数的形式,如果你输出是常量,可以使用匿名函数的形式作为函数
例子:
经过debug,上述例子可以运行的代码:
import tensorflow as tf
parsed_example = {
"label":[[1, 1, 1, 0],
[0, 1, 1, 0],
[1, 1, 1, 0]],
"ot": [[1, 1, 1, -1],
[0, 1, 1, 0],
[1, 1, 1, 0]],
}
label = tf.slice(tf.cast(parsed_example["label"], tf.int32), [0, 0], [-1, 1])
sess = tf.Session()
label = sess.run(label)
# print label
ot = tf.slice(tf.cast(parsed_example["label"], tf.int32), [0, 0], [-1, 1])
ot1 = tf.slice(tf.cast(parsed_example["label"], tf.int32), [0, 1], [-1, 1])
# ot = sess.run(ot)
# print ot
a = tf.add(ot, ot)
b = tf.add(ot1, ot1)
print sess.run(a)
print sess.run(b)
print ot == ot1
print ot == 1
test = tf.cond(tf.cast(ot == ot1, tf.bool), lambda: tf.add(ot, ot), lambda : tf.add(ot1, ot1))
test = sess.run(test)
print test
倒数第三句代码中,对输出常量,可以改写为匿名函数的形式:
test = tf.cond(tf.cast(ot == ot1, tf.bool), lambda: 1, lambda : 2)
参考:
1.https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/cond
2.帮助理解:https://blog.csdn.net/m0_37041325/article/details/76908660