180411 tf.slice() 用法举例

tf.slice一句话概括就是:从指定的数据起始位置(begin)切片(size)尺寸的数据。tensorflow官方定义如下:

This operation extracts a slice of size size from a tensor input starting at the location specified by begin. The slice size is represented as a tensor shape, where size[i] is the number of elements of the ‘i’th dimension of input that you want to slice. The starting location (begin) for the slice is represented as an offset in each dimension of input. In other words, begin[i] is the offset into the ‘i’th dimension of input that you want to slice from.

tf.slice(
    input_,
    begin,
    size,
    name=None
)
  • 应用举例1-制定size个数
# https://www.tensorflow.org/api_docs/python/tf/slice
# 原始数据t.shape = (3,2,4)即3个shape为(2,4)样本
t = tf.constant([[[1, 1, 1], [2, 2, 2]],
                 [[3, 3, 3], [4, 4, 4]],
                 [[5, 5, 5], [6, 6, 6]]])

# [1,0,0]代表从第一个样本的第0行第0列开始begin
a = tf.slice(t, [1, 0, 0], [1, 1, 3]) # [1,1,3]选取1个样本,shape为[1,3]的样本
b = tf.slice(t, [1, 0, 0], [1, 2, 3]) # [1,2,3]选取1个样本,shape为[2,3]的样本 
c = tf.slice(t, [1, 0, 0], [2, 1, 3]) # [2,1,3]选取2个样本,shape为[1,3]的样本

结果如下:

The input data is:
[[[1 1 1]
  [2 2 2]]

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

 [[5 5 5]
  [6 6 6]]] 

Shape size is :
 (1, 1, 3)
Slice data is: 
 [[[3 3 3]]]


Shape size is :
 (1, 2, 3)
Slice data is: 
 [[[3 3 3]
  [4 4 4]]]


Shape size is :
 (2, 1, 3)
Slice data is: 
 [[[3 3 3]]

 [[5 5 5]]]

with tf.Session() as sess:
    print('The input data is:')
    print(sess.run(t),'\n')
    sess.run(t)
    for i in [a,b,c]:
        print('Shape size is :\n',sess.run(i).shape)
        print('Slice data is: \n',sess.run(i))
        print('\n')
  • 应用举例2-不制定size个数(用-1代替)
import tensorflow as tf  
import numpy as np  

z=tf.constant([[[1,2,3],[4,5,6]], [[7,8,9],[10,11,12]],  [[13,14,15],[16,17,18]]])

with tf.Session() as sess:
    print('The data z is:\n')
    print(sess.run(z),'\n')

    begin_z=[0,1,1]  
    size_z=[-1,1,2]   
    out=tf.slice(z,begin_z,size_z)  
    print('The out result is:\n')
    print (sess.run(out))  # size[i]=-1 表示第i维从begin[i]剩余的元素都要被抽取,结果:[[[ 5  6]] [[11 12]] [[17 18]]] 

结果如下:
“`
The data z is:

[[[ 1 2 3]
[ 4 5 6]]

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

[[13 14 15]
[16 17 18]]]

The out result is:

[[[ 5 6]]

[[11 12]]

[[17 18]]]

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GuokLiu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值