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的用法