tf.stack详解

官方文档:
https://tensorflow.google.cn/api_docs/python/tf/stack
把一些秩为R的Tensor堆叠成R+1。
给定一个元素shape为(A,B,C)的Tensor的列表,列表长度为N,则
axis==0,shape=(N, A, B, C)
axis==1,shape=(A, N, B, C)

tf.stack(
    values,
    axis=0,
    name='stack'
)

例子:

import tensorflow as tf

x = tf.constant([1, 4])  # shape=(2,),N=3
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.stack([x, y, z])  # [[1, 4], [2, 5], [3, 6]] (Pack along first dim.)  shape=[3,2]
tf.stack([x, y, z], axis=1)  # [[1, 2, 3], [4, 5, 6]]  shape=[2,3]

完整代码

import tensorflow as tf

x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
a=tf.stack([x, y, z])  # [[1, 4], [2, 5], [3, 6]] (Pack along first dim.)
b=tf.stack([x, y, z], axis=1)  # [[1, 2, 3], [4, 5, 6]]

with tf.Session() as sess:
    print(sess.run(a))
    print(a.shape)
    print(sess.run(b))
    print(b.shape)
[[1 4]
 [2 5]
 [3 6]]
(3, 2)
[[1 2 3]
 [4 5 6]]
(2, 3)

猜你喜欢

转载自blog.csdn.net/lllxxq141592654/article/details/85346094