考虑下面的numpy广播示例:
import numpy as np
import theano
from theano import tensor as T
xval = np.array([[1, 2, 3], [4, 5, 6]])
bval = np.array([[10, 20, 30]])
print xval + bval
正如所料,向量bval
被添加到矩阵xval
的每一行,输出为:
[[11 22 33]
[14 25 36]]
尝试在theano的git版本中复制相同的行为:
x = T.dmatrix('x')
b = theano.shared(bval)
z = x + b
f = theano.function([x], z)
print f(xval)
我收到以下错误:
ValueError: Input dimension mis-match. (input[0].shape[0] = 2, input[1].shape[0] = 1)
Apply node that caused the error: Elemwise{add,no_inplace}(x, <TensorType(int64, matrix)>)
Inputs types: [TensorType(float64, matrix), TensorType(int64, matrix)]
Inputs shapes: [(2, 3), (1, 3)]
Inputs strides: [(24, 8), (24, 8)]
Inputs scalar values: ['not scalar', 'not scalar']
我理解Tensor
x
对象具有broadcastable
属性,但我无法找到1)为shared
对象正确设置此对象的方法2)正确推断它。我怎样才能在theano中重新实现numpy的行为?
答案 0 :(得分:10)
Theano需要在编译之前在图表中声明所有可广播的维度。 NumPy使用运行时形状信息。
默认情况下,所有共享变量幻灯片都不可播放,因为它们的形状可能会发生变化。
使用示例中所需的可广播维度创建共享变量:
b = theano.shared(bval, broadcastable=(True,False))
我会将此信息添加到文档中。