Python 2.7 转换无张量类型

Python 2.7 转换无张量类型,python-2.7,machine-learning,theano,Python 2.7,Machine Learning,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.rando

我有一个用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)
。有没有一种方法可以在不重建整个计算图的情况下更改输入张量类型?

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

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)

为此,有几种解决方案。 你可以把对角线穿过前两个轴,但不幸的是


我认为这可以通过
扫描来完成,但这是另一件事。

没有具体的例子就无法回答这个问题——原则上,你可以像重塑numpy数组一样轻松地重塑张量。切片也是如此。如果我理解正确,您将需要这些操作中的任何一个<代码>输入。重塑(-1,)
生成一个长向量<代码>输入[:,0]选择第一列。h在雅可比函数调用中使用整形或展平张量的问题在于,该整形张量不是
输出的计算图的一部分。流程是input=>stuff=>output。是否可以在输入和“填充”之间插入重塑?我不知道。但如果我们有一个工作示例,我们可以发现:)我添加了一个示例计算图。此图通常是根据用户参数在对象内部构建的。所以这个图并不总是像这样。尽管如此,
input
始终是一个矩阵,但所建模的固有函数是向量对向量的。我想问的是,在构建这个图之后,
input
TensorType
是否可以更改。在No
0.6.0
中,我没有得到这个错误。然而,由于输出的形状,我确实得到了一个,但是
jac=theano.gradient.jacobian(output.flatte(),wrt=input)
修复了这一点,如果您想一次评估这一幅图像,应该可以。如果这对您不起作用,您可以执行
input=t.fvector()
,然后使用
hidden=t.tanh(t.dot(input.reformate(-1,W1.shape[0])),W1)+b1将其重塑为“隐藏”矩阵。(我很好奇-这是用来操作输入样本的吗?:))。你能纠正一下
b1
b2
表达式中的打字错误吗?