2016-12-18 68 views
1

我試圖將CNN輸出饋入TensorFlow中的RNN。在張量流中填充可變長度序列

CNN處理10幅圖像並輸出形狀張量(1,230,2048)。其中230是所有圖像的序列總數,2048是每個序列的長度。

我跟蹤矢量中每個圖像的序列數量。例如:

[1, 9, 25, 29, 31, 10, 23, 29, 37, 36]

我可以得到最大的序列號,在這種情況下這將是37.

的問題是如何將墊(1,230,2048)張量在不同的位置這樣所有圖像都用相同數量的序列表示(本例中爲37)?

最終的張量應該是形狀(1,370,2048)。

謝謝

回答

0

看看tf.pad。你可以通過它列出一對 - 每個維度一對。

+2

的一件事情是,我需要填充區的張量內。整體上不是張量。 – Edgard

2

我寫了一個短代碼解決了它。這裏有一個小例子,其中6個圖像具有不同的序列號(爲了清楚起見,我在張量中插入了間距)。

vec = tf.constant([[1, 1, 1, 1, 1, 1, 1, 1], 
     [1, 1, 1, 1, 1, 1, 1, 1], 
     [1, 1, 1, 1, 1, 1, 1, 1], 
     [1, 1, 1, 1, 1, 1, 1, 1], 

     [2, 2, 2, 2, 2, 2, 2, 2], 
     [2, 2, 2, 2, 2, 2, 2, 2], 

     [3, 3, 3, 3, 3, 3, 3, 3], 

     [4, 4, 4, 4, 4, 4, 4, 4], 
     [4, 4, 4, 4, 4, 4, 4, 4], 
     [4, 4, 4, 4, 4, 4, 4, 4], 

     [5, 5, 5, 5, 5, 5, 5, 5], 
     [5, 5, 5, 5, 5, 5, 5, 5], 

     [6, 6, 6, 6, 6, 6, 6, 6]], dtype=tf.float32) 

seqLens = [4, 2, 1, 3, 2, 1] 
maxLen = max(seqLens) 

NFeatures = 8 
BatchSize = 6 

n = 0 
offset = sum(seqLens[0:(n)]) 
indices = tf.reshape(tf.range(offset, seqLens[n]+offset), [seqLens[n], 1]) 
res = tf.gather_nd(vec, [indices]) 
res_as_vector = tf.reshape(res, [-1]) 
zero_padding = tf.zeros([NFeatures * maxLen] - tf.shape(res_as_vector), dtype=res.dtype) 
a_padded = tf.concat(0, [res_as_vector, zero_padding]) 
result = tf.reshape(a_padded, [maxLen, NFeatures]) 
Inputs2 = result 

for n in range(1, BatchSize): 
    offset = sum(seqLens[0:(n)]) 
    indices = tf.reshape(tf.range(offset, seqLens[n]+offset), [seqLens[n], 1]) 
    res = tf.gather_nd(vec, [indices]) 
    res_as_vector = tf.reshape(res, [-1]) 
    zero_padding = tf.zeros([NFeatures * maxLen] - tf.shape(res_as_vector), dtype=res.dtype) 
    a_padded = tf.concat(0, [res_as_vector, zero_padding]) 
    result = tf.reshape(a_padded, [maxLen, NFeatures]) 
    Inputs2 = tf.concat(0, [Inputs2, result]) 

sess = tf.Session() 
sess.run(tf.global_variables_initializer()) 

print(sess.run(Inputs2)) 

輸出應該是這樣的:

[[ 1. 1. 1. 1. 1. 1. 1. 1.] 
[ 1. 1. 1. 1. 1. 1. 1. 1.] 
[ 1. 1. 1. 1. 1. 1. 1. 1.] 
[ 1. 1. 1. 1. 1. 1. 1. 1.] 
[ 2. 2. 2. 2. 2. 2. 2. 2.] 
[ 2. 2. 2. 2. 2. 2. 2. 2.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 3. 3. 3. 3. 3. 3. 3. 3.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 4. 4. 4. 4. 4. 4. 4. 4.] 
[ 4. 4. 4. 4. 4. 4. 4. 4.] 
[ 4. 4. 4. 4. 4. 4. 4. 4.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 5. 5. 5. 5. 5. 5. 5. 5.] 
[ 5. 5. 5. 5. 5. 5. 5. 5.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 6. 6. 6. 6. 6. 6. 6. 6.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0. 0. 0.]] 

'