给定一个二维张量(矩阵),我想将其划分为几个大小相等的小张量。你可以将其视为最大池化的预处理。例如,
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
我研究了slice
和gather
一段时间了。但我仍然不知道该怎么做。你能告诉我如何得到它吗?提前致谢!
最佳答案
您可以使用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]]])
关于python - 在tensorflow中将一个2d张量动态划分为多个张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44889448/