Tensorflow(八) —— Tensor的合并与切割
1. 主要操作方式
- 1、tf.concat # 常用
- 2、tf.split # 常用
- 3、tf.stack # 常用
- 4、tf.unstack
2. concat操作
指定axis则沿该轴进行拼接
# ********************* concat
"""
指定axis则沿该轴进行拼接
"""
a = tf.random.normal([2,28,28,3])
b = tf.random.normal([3,28,28,3])
c = tf.concat([a,b],axis = 0)
print("c:",c.shape)
d = tf.random.uniform([4,14,28,3])
e = tf.random.uniform([4,14,28,3])
f = tf.concat([d,e],axis = 1)
print("f:",f.shape)
3. stack操作
- create new dim
- 在指定轴上创建新的一个维度来盛装数据
# ********************** stack
"""
create new dim
在指定轴上创建新的一个维度来盛装数据
"""
a = tf.ones([4,28,28,3])
b = tf.zeros_like(a)
c1 = tf.concat([a,b],axis = 0)
print("c1:",c1.shape)
c2 = tf.stack([a,b],axis = 0)
print("c2:",c2.shape)
c3 = tf.stack([a,b],axis = 3)
print("c3:",c3.shape)
c4 = tf.concat([a,b],axis = -1)
print("c4:",c4.shape)
4. concat 与 stack 的区别
- 1、concat约束:除了需要拼接那个轴可以不一致,其它所有轴都需要相同。
- 2、stack约束:所有轴都必须维持一致
5. unstack & stack 为可逆操作
# ********************** unstack & stack 可逆
a = tf.ones([4,28,28,3])
b = tf.zeros_like(a)
c = tf.stack([a,b],axis = 0)
print("c:",c.shape)
d = tf.unstack(c,axis = 0)
print("d:",d[0].shape,d[1].shape)
e = tf.unstack(c,axis = 3)
print("e:",len(e))
"""
得到28个形状相同的Tensor
"""
e[27].shape
6. split操作
- unstack沿axis轴等分为axis轴shape的数量
- split可以指定等分的数量
# ************************ split
"""
unstack沿axis轴等分为axis轴shape的数量
split可以指定等分的数量
"""
a = tf.zeros([4,28,28,3])
b = tf.unstack(a,axis = 1)
print("b:",len(b))
c = tf.split(a,axis = 1,num_or_size_splits = 7)
print("c:",len(c))
print("c:",c[6].shape)
d = tf.split(a,axis = 1,num_or_size_splits = [10,10,8])
print("d:",len(d))
print("d:",d[1].shape)
本文为参考龙龙老师的“深度学习与TensorFlow 2入门实战“课程书写的学习笔记
by CyrusMay 2022 04 16