"and" 和 "or" 在 Theano 上

"and" and "or" on Theano

我运行下面的代码:

import theano.tensor as T

print(T.eq(2, 1).eval())
print(T.eq(1, 1).eval())
print((T.eq(2, 1) and T.eq(1, 1)).eval())
print((T.eq(2, 1) or T.eq(1, 1)).eval())

结果是:

False
True
True
False

为什么这不是 "False, True, False, True"?

因为theano是一个符号库,像T.eq(1,2)这样的东西不会直接被评估为布尔值。

>>> bool(T.eq(1,2))
True
>>> type(T.eq(1,2))
<class 'theano.tensor.var.TensorVariable'>

这个问题的奇怪结果是由于逻辑运算符在非布尔对象上工作。

>>> '123' and '456'
'456'
>>> '123' or '456'
'123'

引自 here,第 9.5 节:

x and y Returns x if x is False, y otherwise

x or y Returns y if x is False, x otherwise

正确的方法是使用位运算符:

>>> (T.eq(1,1) & T.eq(1,2)).eval()
array(False, dtype=bool)
>>> (T.eq(1,1) | T.eq(1,2)).eval()
array(True, dtype=bool)