1. 合并(tf.concat和tf.stack两种方法)
# concat合并,不产生新维度,可以在任意的维度上进行,
# 唯一的约束是非合并的长度必须一致
import tensorflow as tf
#张量a保存4个班级35个学生的8科成绩
a = tf.random.normal([4,35,8])
#张量b保存6个班级35个学生的8科成绩
b = tf.random.normal([6,35,8])
# axis指定需要合并的维度
tf.concat([a,b],axis=0)
# concat合并输出
<tf.Tensor: shape=(10, 35, 8), dtype=float32, numpy=
array([[[-1.4764088 , 1.1085197 , -0.6670869 , ..., 0.48061377,
-1.0570003 , -0.8305168 ],
... ]]], dtype=float32)>
# tf.stack合并产生新的维度,约束为所有合并的张量shape完全一致。
import tensorflow as tf
#张量a保存1班35个学生的8科成绩
a = tf.random.normal([35,8])
#张量b保存2班级35个学生的8科成绩
b = tf.random.normal([35,8])
# axis指定新维度的插入位置
tf.stack([a,b],axis=0)
# tf.stack输出
<tf.Tensor: shape=(2, 35, 8), dtype=float32, numpy=
array([[[ 1.2596136 , 1.0518428 , -1.2914857 , 0.22543535,
0.32937077, -1.1548631 , -0.6478617 , 0.49399927],
...]]],
dtype=float32)>
2. 分割(tf.split和tf.unstack)
tf.split(x, axis, num_or_size_splits)可以完成张量的分割操作,其中
❑ x:待分割张量
❑ axis:分割的维度索引号
❑ num_or_size_splits:切割方案。当num_or_size_splits 为单个数值时,如10,表示切割
为10 份;当num_or_size_splits 为List 时,每个元素表示每份的长度,如[2,4,2,2]表示
切割为4 份,每份的长度分别为2,4,2,2
import tensorflow as tf
x = tf.random.normal([10,35,8])
result = tf.split(x,axis=0,num_or_size_splits=10)
len(result)
result[0]
'''
输出
10
<tf.Tensor: shape=(1, 35, 8), dtype=float32, numpy=
array([[[ 0.18462402, -0.6507553 , -1.5594233 , -2.7393978 ,
0.9367863 , -0.05196663, 1.8079358 , 1.409742 ],
...]]],
dtype=float32)>
'''
result2 = tf.split(x,axis=0,num_or_size_splits=[4,2,2,2])
len(result2)
result2[0]
'''
输出
4
<tf.Tensor: shape=(4, 35, 8), dtype=float32, numpy=
array([[[ 1.03377938e+00, 2.17056775e+00, -1.21275894e-01, ...,
-2.54096501e-02, 9.30325806e-01, -1.08327103e+00],
...]]],
dtype=float32)>
'''
tf.unstack(x,axis) 直接在axis上全部按长度为1的方式分割
import tensorflow as tf
x = tf.random.normal([10,35,8])
result = tf.unstack(x,axis=0)
len(result)
'''输出
10'''