深度学习(12)TensorFlow高阶操作一: 合并与分割
深度學習(12)TensorFlow高階操作一: 合并與分割
- 1. concat
- 2. stack: create new dim
- 3. Dim mismatch
- 4. unstuck
- 5. split
Merge and split
- tf.concat(拼接)
- tf.split(分割)
- tf.stack(堆疊)
- tf.unstack(分割,為split中的一種)
1. concat
- Statistics about scores
- [class1?4,students,scores][class1-4,students,scores][class1?4,students,scores]
- [class5?6,students,scores][class5-6,students,scores][class5?6,students,scores]
(1) c = tf.concat([a, b], axis=0)1: 將a和b合并為c,合并第1個維度(axis=0),c.shape=[6, 35, 8];
(2) tf. concat([a, b], axis=1): 合并a和b的第2個維度(axis=1),其shape=[4, 35, 8];
- Along distinct dim/axis
- Dim = d
- axis = 0;
shape=[12, 4];
- axis=0:
shape=[4, 7];
注: 合并操作不會增加維度,合并之前是2維的Tensor,那么合并之后還是2維的Tensor。如果想要創造新的維度,我們就需要stack操作了;
2. stack: create new dim
- Statistics about scores
- School1: [classes,students,scores][classes,students,scores][classes,students,scores]
- School2: [classes,students,scores][classes,students,scores][classes,students,scores]
→\to→ - [schools,classes,students,scores][schools,classes,students,scores][schools,classes,students,scores]
(1) tf.concat([a, b], axis=-1): 合并a和b的倒數第1個維度(axis=-1),其shape=[4, 35, 16];
(2) tf.stack([a, b], axis=0): 在第1個維度(axis=0)處創造一個新的維度,創建后其shape=[2, 4, 35, 8];
(3) tf.stack([a, b], axis=3): 在第4個維度(axis=3)處創造一個新的維度,創建后其shape=[4, 35, 8, 2];
3. Dim mismatch
- concat要求除了合并的那個維度外,其它維度的數值必須相等;
- stack要求所有維度的數值必須相等;
4. unstuck
(1) c = tf.stack([a, b]): 將a和b通過stack()函數合并為c,合并完c.shape=[2, 4, 35, 8];
(2) aa, bb = unstack(c, axis=0): 將c從第1個維度(axis=0)處拆解為aa和bb,拆解完aa.shape=[4, 35, 8]; bb.shape=[4, 35 ,8];
(3) res = tf.unstack(c, axis=3): 將c從第4個維度(axis=3)處拆解,第4個維度消失,拆解后共有8個res,每個res.shape=[2, 4, 35],所以res[0].shape=[2, 4, 35]; res[7].shape=[2, 4, 35];
- 如果我們不希望將c拆解為這么多個res,比如只拆解為2個res,那么我們就需要使用一個臨摹性更強的API——split。
5. split
- VS unstack
(1) res = tf.split(c, axis=3, num_or_size_splits=2): 將c從第4個維度(axis=3)處均分為2個res,每個res.shape=[2, 4, 35, 4];
(2) res = tf.split(c, axis=3, num_or_size_splits=[2, 2, 4]): 將c從第4個維度(axis=3)處均分為3個res,將8按照[2, 2, 4]分為3份,其中res[0].shape=[2, 4, 35, 2]; res[1].shape=[2, 4, 35, 2]; res[2].shape=[2, 4, 35, 4]。
參考文獻:
[1] 龍良曲:《深度學習與TensorFlow2入門實戰》
總結
以上是生活随笔為你收集整理的深度学习(12)TensorFlow高阶操作一: 合并与分割的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 别慌!李楠:AI不会让程序员、媒体作者和
- 下一篇: 深度学习(14)TensorFlow高阶