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]]]