在张量流

时间:2017-07-03 15:36:29

标签: python tensorflow deep-learning

给定2d张量(矩阵),我想将它分成几个大小相等的小张量。您可以将其视为最大池的预处理。例如,

1 2 3 4 5 6 7 8
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9 10 
4 5 6 7 8 9 10 11

如果动态desired_size为2 * 4,则输出应为:

1 2 3 4
2 3 4 5

5 6 7 8
6 7 8 9

3 4 5 6
4 5 6 7

7 8 9 10 
8 9 10 11

我已经研究了slicegather一段时间了。但我仍然不知道该怎么做。你能告诉我怎么做吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

你可以使用tf.extract_image_patches,尽管结果有些冗长:

import numpy as np
import tensorflow as tf

x = tf.constant(np.arange(8) + np.arange(1,5)[:,np.newaxis])
e = tf.extract_image_patches(x[tf.newaxis,:,:,tf.newaxis],
    [1, 2, 4, 1], [1, 2, 4, 1], [1, 1, 1, 1], padding='VALID')
e = tf.reshape(e, [-1, 2, 4])
sess = tf.InteractiveSession()
e.eval()

# returns
# array([[[ 1,  2,  3,  4],
#         [ 2,  3,  4,  5]],
#        [[ 5,  6,  7,  8],
#         [ 6,  7,  8,  9]],
#        [[ 3,  4,  5,  6],
#         [ 4,  5,  6,  7]],
#        [[ 7,  8,  9, 10],
#         [ 8,  9, 10, 11]]])

答案 1 :(得分:1)

我与tf.split()绑定:

num_splits = 2
desired_size = (2, 4)
A = tf.constant(a)

C = tf.concat(tf.split(A, desired_size[0], 0),1)
D = tf.reshape(tf.concat(tf.split(C, num_splits*desired_size[0], 1), 0), (-1, desired_size[0], desired_size[1]))

#The result
[[[ 1  2  3  4]
[ 2  3  4  5]]

[[ 5  6  7  8]
[ 6  7  8  9]]

[[ 3  4  5  6]
[ 4  5  6  7]]

[[ 7  8  9 10]
[ 8  9 10 11]]]

# For num_splits = 4, desired_size = (2, 2) you get 
[[[ 1  2]
[ 2  3]]

[[ 3  4]
[ 4  5]]

[[ 5  6]
[ 6  7]]

[[ 7  8]
[ 8  9]]

[[ 3  4]
[ 4  5]]

[[ 5  6]
[ 6  7]]

[[ 7  8]
[ 8  9]]

[[ 9 10]
[10 11]]]