天天看點

np.stack/tf.stack-np.concatenate/tf.concat-tf.unstackstack函數concatenate/concat函數unstack函數

stack函數

NumPy和TensorFlow都有

stack

函數,該函數主要是用來提升次元。

import numpy as np
import tensorflow as tf
np.stack(arrays, axis=0)
tf.stack(arrays, axis=0)
           

假設要轉變的張量數組

arrays

的長度為

N

,其中的每個張量數組的形狀為

(A, B, C)

。如果軸

axis=0

,則轉變後的張量形狀為

(N, A, B, C)

;如果軸

axis=1

,則轉變後的張量形狀為

( A, N, B, C)

;如果軸

axis=2

,則轉變後的張量形狀為

( A, B, N, C)

;其他情況依次類推。

import numpy as np
import tensorflow as tf
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8, 9], [10, 11, 12]])
a
Out[6]: 
array([[1, 2, 3],
       [4, 5, 6]])
b
Out[7]: 
array([[ 7,  8,  9],
       [10, 11, 12]])
a.shape
Out[8]: (2, 3)
b.shape
Out[9]: (2, 3)
np.stack([a, b], axis=0)
Out[10]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],
       [[ 7,  8,  9],
        [10, 11, 12]]])
np.stack([a, b], axis=1)
Out[11]: 
array([[[ 1,  2,  3],
        [ 7,  8,  9]],
       [[ 4,  5,  6],
        [10, 11, 12]]])
np.stack([a, b], axis=2)
Out[12]: 
array([[[ 1,  7],
        [ 2,  8],
        [ 3,  9]],
       [[ 4, 10],
        [ 5, 11],
        [ 6, 12]]])

sess = tf.Session()
sess.run(tf.global_variables_initializer())
st_0 = tf.stack([a, b], axis=0)
st_0 = sess.run(st_0)
print(st_0)
[[[ 1  2  3]
  [ 4  5  6]]
 [[ 7  8  9]
  [10 11 12]]]
print(st_0.shape)
(2, 2, 3)
st_1 = tf.stack([a, b], axis=1)
st_1 = sess.run(st_1)
st_1
Out[21]: 
array([[[ 1,  2,  3],
        [ 7,  8,  9]],
       [[ 4,  5,  6],
        [10, 11, 12]]])
st_1.shape
Out[22]: (2, 2, 3)
st_2 = tf.stack([a, b], axis=2)
st_2 = sess.run(st_2)
st_2
Out[24]: 
array([[[ 1,  7],
        [ 2,  8],
        [ 3,  9]],
       [[ 4, 10],
        [ 5, 11],
        [ 6, 12]]])
st_2.shape
Out[25]: (2, 3, 2)

           

concatenate/concat函數

tf.concat

相當于numpy中的

np.concatenate

函數,用于将兩個張量在某一個次元(axis)合并起來

concatenate/concat

函數不會增加次元。隻在

axis

指定的次元上進行拼接。

np.concatenate([a, b], axis=0)
Out[26]: 
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
np.concatenate([a, b], axis=1)
Out[27]: 
array([[ 1,  2,  3,  7,  8,  9],
       [ 4,  5,  6, 10, 11, 12]])

ct_0 = tf.concat([a, b], axis=0)
ct_0 = sess.run(ct_0)
ct_0
Out[31]: 
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
ct_0.shape
Out[32]: (4, 3)
ct_1 = tf.concat([a, b], axis=1)
ct_1 = sess.run(ct_1)
ct_1
Out[37]: 
array([[ 1,  2,  3,  7,  8,  9],
       [ 4,  5,  6, 10, 11, 12]])
ct_1.shape
Out[38]: (2, 6)
           

unstack函數

tf.unstack與tf.stack的操作相反,是将一個高階數的張量在某個axis上分解為低階數的張量。

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=0) # shape (2,2,3)

a1 = tf.unstack(ab, axis=0)
[<tf.Tensor 'unstack_1:0' shape=(2, 3) dtype=int32>,
 <tf.Tensor 'unstack_1:1' shape=(2, 3) dtype=int32>]
           

參考資料

np.stack() 與 tf.stack() 的簡單了解

tf.stack() 詳解 —》了解為主

tf.concat與tf.stack(僅個人了解)

tf.concat, tf.stack和tf.unstack的用法

繼續閱讀