美文网首页
TensorFlow高阶操作之合并与分割

TensorFlow高阶操作之合并与分割

作者: 酵母小木 | 来源:发表于2020-02-03 16:17 被阅读0次

    Merge And Split


    1. 【tf.concat()】:拼接

    [classes, students, scores]

    //需要指定拼接维度,数据其他维度相同
    In [4]: a = tf.ones([4, 35, 8])
    
    In [5]: b = tf.ones([2, 35, 8])
    
    In [6]: c = tf.concat([a, b], axis=0)
    
    In [7]: c.shape
    Out[7]: TensorShape([6, 35, 8])
    
    In [8]: a = tf.ones([4, 32, 8])
    
    In [9]: b = tf.ones([4, 3, 8])
    
    In [10]: tf.concat([a, b], axis=1).shape
    Out[10]: TensorShape([4, 35, 8])
    

    2. 【tf.stack()】:堆叠

    school1:[classes, students, scores]
    school2:[classes, students, scores]
    [school, classes, students, scores]

    //需要指定新插入的维度,数据所有维度相同
    In [11]: a = tf.ones([4, 35, 8])
    
    In [12]: b = tf.ones([4, 35, 8])
    
    In [13]: a.shape
    Out[13]: TensorShape([4, 35, 8])
    
    In [14]: b.shape
    Out[14]: TensorShape([4, 35, 8])
    
    In [15]: tf.stack([a, b], axis=0).shape
    Out[15]: TensorShape([2, 4, 35, 8])
    
    In [16]: tf.stack([a, b], axis=3).shape
    Out[16]: TensorShape([4, 35, 8, 2])
    
    

    3. 【tf.unstack()】:拆叠

    //将某一维度数据拆分为单维度
    In [19]: a = tf.ones([4, 35, 8])
    
    In [20]: a1, a2, a3, a4 = tf.unstack(a, axis=0)
    
    In [22]: a1.shape
    Out[22]: TensorShape([35, 8])
    
    In [25]: res = tf.unstack(a, axis=2)
    
    In [28]: res[0].shape
    Out[28]: TensorShape([4, 35])
    

    4. 【tf.split()】:分割

    对比【unstack()】不仅可以指定分割的轴,还能指定分割的分配比例

    In [39]: a = tf.ones([2, 4, 35, 8])
    
    In [40]: res = tf.unstack(a, axis=3)  //对某个轴均分为单体
    In [41]: len(res)
    Out[41]: 8
    //如果不整除,则不可以分割
    In [42]: res=tf.split(a, axis=3, num_or_size_splits=2)    //分为数量相同的N个单体
    
    In [43]: len(res)      
    Out[43]: 2
    
    In [48]: res[0].shape
    Out[48]: TensorShape([2, 4, 35, 4])
    
    In [52]: a = tf.ones([2, 4, 35, 8])
    
    In [53]: res=tf.split(a, axis=3, num_or_size_splits=[2, 2, 4])
    
    In [54]: res[0].shape, res[1].shape, res[2].shape
    Out[54]:
    (TensorShape([2, 4, 35, 2]),
     TensorShape([2, 4, 35, 2]),
     TensorShape([2, 4, 35, 4]))
    

    参考资料

    相关文章

      网友评论

          本文标题:TensorFlow高阶操作之合并与分割

          本文链接:https://www.haomeiwen.com/subject/ivbhxhtx.html