tf.strided_slice解释

Update

tf.stride_slice(data, begin, end)
tf.slice(data, begin, end)
和tf.slice的区别是slice的end索引是闭区间,stride_slice的end索引是开区间,所以一个截掉最后一列(remove the last element or column of each line)的小技巧是用stride_slice(data, [0, 0], [rows, -1]),但是如果是用slice(data, [0, 0], [rows, -1])则仍是原矩阵。


官方介绍一眼看不明白,搜索之后看到这篇文章tf.strided_slice 实例,但是缺乏对于stride的介绍,自己动手再写个notebook

import tensorflow as tf
data = [[[1, 1, 1], [2, 2, 2]],
            [[3, 3, 3], [4, 4, 4]],
            [[5, 5, 5], [6, 6, 6]]]
x = tf.strided_slice(data,[0,0,0],[1,1,1])
with tf.Session() as sess:
    print(sess.run(x))

[[[1]]]

x = tf.strided_slice(data,[0,0,0],[2,2,2])
with tf.Session() as sess:
    print(sess.run(x))

[[[1 1]
[2 2]]

[[3 3]
[4 4]]]

从这里可以判断对于tf.strided_slice(data, begin, end, stride)
begin和end指定了位于[begin, end)的一小块切片。注意end中的索引是开区间。

x = tf.strided_slice(data,[0,0,0],[2,2,2],[1,1,1])
with tf.Session() as sess:
    print(sess.run(x))

[[[1 1]
[2 2]]

[[3 3]
[4 4]]]

当指定stride为[1,1,1]输出和没有指定无区别,可以判断默认的步伐就是每个维度为1

x = tf.strided_slice(data,[0,0,0],[2,2,2],[1,2,1])
with tf.Session() as sess:
    print(sess.run(x))

[[[1 1]]

[[3 3]]]

指定第二个维度步伐为2,看到第二个维度先选取了位置为0的数据[1,1,1],[3,3,3],然后没有继续选取[2,2,2],[4,4,4]

x = tf.strided_slice(data,[0,0,0],[2,2,3],[-1,1,2])
with tf.Session() as sess:
    print(sess.run(x))

[]

当begin为正值,stride任意位置为负值,输出都是空的

x = tf.strided_slice(input, [1, -1, 0], [2, -3, 3], [1, -1, 1])
with tf.Session() as sess:
    print(sess.run(x))

[[[4 4 4]
[3 3 3]]]

当begin和end对应维度为负值,stride可以为负值,表示反向的步伐。首先选取第一个维度索引为1的数据[3,3,3],[4,4,4]。再在第二个维度选取索引为-1的数据[4,4,4],再根据步伐-1选取索引为-2的数据[3,3,3]。再在第三个维度选取索引为0的数据[4],[3],再选取索引为1的数据[4],[3],再选取索引为2的数据[4],[3],最后得到上面的结果。



作者:jayzhou215
链接:https://www.jianshu.com/p/a1a9e44708f6
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值