2014-10-08 79 views
2

我有一个用Theano构建的计算图。它是这样的:转换theano张量类型

import theano 
from theano import tensor as T 
import numpy as np 

W1 = theano.shared(np.random.rand(45,32).astype('float32'), 'W1') 
b1 = theano.shared(np.random.rand(32).astype('float32'), 'b1') 
W2 = theano.shared(np.random.rand(32,3).astype('float32'), 'W2') 
b2 = theano.shared(np.random.rand(3).astype('float32'), 'b2') 

input = T.matrix('input') 
hidden = T.tanh(T.dot(input, W1)+b1) 
output = T.nnet.softmax(T.dot(hidden, W2)+b2) 

现在,从矢量到矢量的映射。但是,输入被设置为矩阵类型,所以我可以同时通过映射传递多个向量。我正在做一些机器学习,这使得学习阶段更有效率。

的问题是,在学习阶段之后,我想查看映射为矢量为矢量,所以我可以计算:

jac = theano.gradient.jacobian(output, wrt=input) 

jacobian抱怨输入不TensorType(float32, vector)。有没有一种方法可以在不重建整个计算图的情况下改变输入张量类型?

+0

如果没有具体的例子,无法回答这个问题 - 原则上可以像重塑numpy数组一样轻松地重塑张量。切片也一样。如果我理解正确,您将需要这些操作之一。 'input.reshape(( - 1,))'产生一个长向量。 'input [:,0]'选择第一列。 HTH – eickenberg 2014-10-08 20:30:10

+0

在雅可比调用中使用重构或平坦张量的问题是,这种重构的张量不是“输出”的计算图的一部分。流程是输入=> stuff =>输出。可以在输入和“东西”之间插入整形吗? – 2014-10-08 20:40:55

+0

我不知道。但是,如果我们有一个工作示例,我们可以找出:) – eickenberg 2014-10-08 20:47:07

回答

1

从技术上讲,这是一个可能的解决方案:

import theano 
from theano import tensor as T 
import numpy as np 

W1 = theano.shared(np.random.rand(45,32).astype('float32'), 'W1') 
b1 = theano.shared(np.random.rand(32).astype('float32'), 'b1') 
W2 = theano.shared(np.random.rand(32,3).astype('float32'), 'W2') 
b2 = theano.shared(np.random.rand(3).astype('float32'), 'b2') 

input = T.vector('input') # it will be reshaped! 
hidden = T.tanh(T.dot(input.reshape((-1, 45)), W1)+b1) 
output = T.nnet.softmax(T.dot(hidden, W2)+b2) 

#Here comes the trick 
jac = theano.gradient.jacobian(output.reshape((-1,)), wrt=input).reshape((-1, 45, 3)) 

这样jac.eval({input: np.random.rand(10*45)}).shape将导致(100, 45, 3)

问题是它计算批次索引中的导数。因此理论上第一个1x45数字可以影响所有10x3输出(在一批长度为10)。

为此,有几种解决方案。 您可以在前两个轴上取对角线,但不幸的是Theano does not implement itnumpy does

我认为可以用scan来完成,但这是另一回事。