我试图沿着2-dim张量的第0轴提取长度为4的所有切片.到目前为止,我可以将纯Python与tensorflow混合使用.
r = test.shape[0] # test should be a tensor
n = 4
a_list = list(range(r))
the_list = np.array([a_list[slice(i, i+n)] for i in range(r - n+1)])
test_stacked = tf.stack(tf.gather(test, the_list))
Run Code Online (Sandbox Code Playgroud)
在不使用纯Python的情况下,这样做的有效方法是什么?请注意,"test"数组实际上应该是一个张量,因此在执行图的第一部分之前,它的形状是未知的.
一个完整的香草例子:
array = np.array([[0, 1],[1, 2],[2, 3],[3, 4],[4, 5],[5, 6]])
array.shape # (6,2)
r = array.shape[0]
n = 4
a_list = list(range(r))
the_list = np.array([a_list[slice(i, i+n)] for i in range(r - n+1)])
result = array[the_list] # all possible slices of length 4 of the array along 0th axis
result.shape # (3, 4, 2)
Run Code Online (Sandbox Code Playgroud)
结果:
[[[0 1]
[1 2]
[2 3]
[3 4]]
[[1 2]
[2 3]
[3 4]
[4 5]]
[[2 3]
[3 4]
[4 5]
[5 6]]]
Run Code Online (Sandbox Code Playgroud)
您可能想尝试更通用的tf.extract_image_patches
。
import tensorflow as tf
a = tf.constant([[0, 1],[1, 2],[2, 3],[3, 4],[4, 5],[5, 6]])
# tf.extract_image_patches requires a [batch, in_rows, in_cols, depth] tensor
a = a[None, :, :, None]
b = tf.extract_image_patches(a,
ksizes=[1, 4, 2, 1],
strides=[1, 1, 1, 1],
rates=[1, 1, 1, 1],
padding='VALID')
b = tf.reshape(tf.squeeze(b), [-1, 4, 2])
sess = tf.InteractiveSession()
print(b.eval())
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
185 次 |
最近记录: |