Theano广播不同于numpy的

mba*_*rov 9 numpy matrix theano

考虑下面的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
Run Code Online (Sandbox Code Playgroud)

正如所料,向量bval被添加到矩阵的每一行,xval输出为:

[[11 22 33]
 [14 25 36]]
Run Code Online (Sandbox Code Playgroud)

试图在theano的git版本中复制相同的行为:

x = T.dmatrix('x')
b = theano.shared(bval)
z = x + b
f = theano.function([x], z)

print f(xval)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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']
Run Code Online (Sandbox Code Playgroud)

我理解具有属性的Tensor对象,但我找不到方法1)为对象正确设置或2)正确推断它.我怎样才能在theano中重新实现numpy的行为?xbroadcastableshared

nou*_*uiz 10

Theano需要在编译之前在图表中声明所有可广播的维度.NumPy使用运行时形状信息.

默认情况下,所有共享变量dimsions都不可广播,因为它们的形状可能会发生变化.

要使用示例中所需的可广播维度创建共享变量,请执行以下操作:

b = theano.shared(bval, broadcastable=(True,False))
Run Code Online (Sandbox Code Playgroud)

我将此信息添加到文档中.