zoukankan      html  css  js  c++  java
  • tf.concat, tf.stack和tf.unstack的用法

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

    tf.concat相当于numpy中的np.concatenate函数,用于将两个张量在某一个维度(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)
    ab1 = tf.concat([a,b], axis=0) # shape(4,3)
    ab2 = tf.concat([a,b], axis=1) # shape(2,6)
    • 1
    • 2
    • 3
    • 4

    tf.stack其作用类似于tf.concat,都是拼接两个张量,而不同之处在于,tf.concat拼接的是两个shape完全相同的张量,并且产生的张量的阶数不会发生变化,而tf.stack则会在新的张量阶上拼接,产生的张量的阶数将会增加,例如:

    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)
    • 1
    • 2
    • 3

    改变参数axis为2,有:

    import tensorflow as tf
    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=2) # shape (2,3,2)

    所以axis是决定其层叠(stack)张量的维度方向的。

    tf.unstacktf.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)

    其a1的输出为

    [<tf.Tensor 'unstack_1:0' shape=(2, 3) dtype=int32>,
     <tf.Tensor 'unstack_1:1' shape=(2, 3) dtype=int32>]
  • 相关阅读:
    阿里terway源码分析
    golang timeoutHandler解析及kubernetes中的变种
    第四章 控制和循环
    关于 自媒体的声明
    java用正则表达式获取url的域名
    javaweb三大核心基础技术
    NumPy之计算两个矩阵的成对平方欧氏距离
    C/C++之计算两个整型的平均值
    C/C++代码优化之整型除以2的指数并四舍五入
    SSE系列内置函数中的shuffle函数
  • 原文地址:https://www.cnblogs.com/DjangoBlog/p/9233153.html
Copyright © 2011-2022 走看看