python - 在tensorflow中将一个2d张量动态划分为多个张量

标签 python tensorflow deep-learning

给定一个二维张量(矩阵),我想将其划分为几个大小相等的小张量。你可以将其视为最大池化的预处理。例如,

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一段时间了。但我仍然不知道该怎么做。你能告诉我如何得到它吗?提前致谢!

最佳答案

您可以使用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/

相关文章:

python - 在 Sympy 中求解简单的凸优化

python - 使用 2 位 Dtype 指定 NumPy 数组

python - 使用多个模块进行 Python 日志记录的常见/标准做法是什么?

python - Tensorflow:特定GPU设备下的dynamic_rnn无法工作,没有GPU设备支持的内核可用

tensorflow - 如何在 tensorflow 中使用非常大(>2M)的词嵌入?

deep-learning - Keras 中的任意深度网络结构

deep-learning - CNN 有 2000 个类(class)?

python - 如何使用awk替换所有组合中的不同文本 block ?

python - 精确模型在 keras-tf 上收敛,但在 keras 上不收敛

python - Tensorflow:使用 tf.mat_fn() 或 tf.nn.dynamic_rnn() 在 LSTM 之前应用层有什么区别?