首页 文章

Theano多个张量作为输出

提问于
浏览
3

我正在使用Theano创建一个神经网络,但当我尝试 return two lists of tensors at the same time in a list 时,我收到错误:

#This is the line that causes the error
#type(nabla_w) == <type 'list'>
#type(nabla_w[0]) == <class 'theano.tensor.var.TensorVariable'>
backpropagate = function(func_inputs, [nabla_w, nabla_b])

TypeError: Outputs must be theano Variable or Out instances. Received [dot.0, dot.0, dot.0, dot.0] of type <type 'list'>

我应该使用什么样的Theano结构将两个张量一起返回到数组中,以便我可以像这样检索它们:

nabla_w, nabla_b = backpropagate(*args)

我尝试使用我在_2868665中找到的一些东西,但没有一个工作 . (例如我尝试了堆栈或堆栈列表)

这是我使用theano.tensor.stack或stacklists的错误:

ValueError: all the input array dimensions except for the concatenation axis must match exactly
Apply node that caused the error: Join(TensorConstant{0}, Rebroadcast{0}.0, Rebroadcast{0}.0, Rebroadcast{0}.0, Rebroadcast{0}.0)
Inputs shapes: [(), (1, 10, 50), (1, 50, 100), (1, 100, 200), (1, 200, 784)]
Inputs strides: [(), (4000, 400, 8), (40000, 800, 8), (160000, 1600, 8), (1254400, 6272, 8)]
Inputs types: [TensorType(int8, scalar), TensorType(float64, 3D), TensorType(float64, 3D), TensorType(float64, 3D), TensorType(float64, 3D)]
Use the Theano flag 'exception_verbosity=high' for a debugprint of this apply node.

代码的一些额外上下文:

weights = [T.dmatrix('w'+str(x)) for x in range(0, len(self.weights))]
biases = [T.dmatrix('b'+str(x)) for x in range(0, len(self.biases))]
nabla_b = []
nabla_w = []
# feedforward
x = T.dmatrix('x')
y = T.dmatrix('y')
activations = []
inputs = []
activations.append(x)
for i in xrange(0, self.num_layers-1):
    inputt = T.dot(weights[i], activations[i])+biases[i]
    activation = 1 / (1 + T.exp(-inputt))
    activations.append(activation)
    inputs.append(inputt)

delta = activations[-1]-y
nabla_b.append(delta)
nabla_w.append(T.dot(delta, T.transpose(inputs[-2])))

for l in xrange(2, self.num_layers):
    z = inputs[-l]
    spv = (1 / (1 + T.exp(-z))*(1 - (1 / (1 + T.exp(-z)))))
    delta = T.dot(T.transpose(weights[-l+1]), delta) * spv
    nabla_b.append(delta)
    nabla_w.append(T.dot(delta, T.transpose(activations[-l-1])))
T.set_subtensor(nabla_w[-l], T.dot(delta, T.transpose(inputs[-l-1])))
func_inputs = list(weights)
func_inputs.extend(biases)
func_inputs.append(x)
func_inputs.append(y)


backpropagate = function(func_inputs, [nabla_w, nabla_b])

1 回答

  • 6

    Theano不支持此功能 . 当你调用 theano.function(inputs, outputs) 时,输出只能是两件事:

    1)Theano变量2)Theano变量列表

    (2)不允许您在顶级列表中有一个列表,因此您应该在输出中展平列表 . 这将返回超过2个输出 .

    解决问题的一个可行的解决方案是将内部列表复制到1个变量中 .

    tensor_nabla_w = theano.tensor.stack(*nabla_w).
    

    这要求nabla_w中的所有元素都是相同的形状 . 这将在计算图中添加一个额外的副本(因此可能会慢一点) .

    更新1:修复对stack()的调用

    更新2:

    到目前为止,我们还有一个额外的约束,即所有元素都有不同的形状,因此不能使用堆栈 . 如果它们都具有相同数量的维度和dtype,则可以使用typed_list,否则您需要自己修改Theano或者压缩输出列表 .

相关问题