theano T.switch(): 如果张量为空奇怪的行为

theano T.switch(): if tensor is empty strange behaviour

我想检查向量 A is empty: return [0] else: return A

import theano
import theano.tensor as T

A = T.ivector()

out = T.switch( T.eq(A.size, 0), [0], A )

f = theano.function([A], out)

print f([1])
print f([])

这会打印:

[ 1 ]
[]

条件语句本身有效,如果 A 为空,它仅 returns 1。

这是因为theano.tensor.switch operates differently to theano.ifelse.ifelse.

theano.tensor.switch 按元素操作。这三个参数需要具有相同的形状,或者可以广播为相同的形状。 T.eq(A.size, 0) 将始终是标量和真值,[0] 是具有单个元素的向量,因此两者都将广播为 A 的形状。 A == [] 的情况无疑是奇怪的,我不知道它是否是设计使然; Theano 似乎是 "broadcasting" 空向量的标量和单项向量。

解决办法是换成theano.ifelse.ifelse:

A = tt.ivector()
out = theano.ifelse.ifelse(
    tt.eq(A.size, 0), tt.unbroadcast(tt.zeros((1,), dtype=A.dtype), 0), A)
f = theano.function([A], out)
print f([])
print f([1])
print f([1, 2])

根据需要,打印

[0]
[1]
[1 2]

请注意,两个可能的 ifelse 输出值(比较为真时的值和比较为假时的值)必须具有相同的类型,因此构造零向量的复杂方法具有单项。