我寫了一個短代碼解決了它。這裏有一個小例子,其中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.]]
'
的一件事情是,我需要填充區的張量內。整體上不是張量。 – Edgard