2014-10-08 50 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來完成,但這是另一回事。