tensorflow2之维度变换与合并分割

  • 维度变换
    • tf.reshape :改变张量形状
    a = tf.random.uniform(shape=[1,3,3,2],minval=0,maxval=255,dtype=tf.int32)
    # 将原tensor reshape为3行6列的tensor
    tf.reshape(a,[3,6])
    
    • tf.squeeze:减少维度,去掉一维
    a = tf.random.uniform(shape=[1, 2, 1, 3, 1, 1],minval=-10, maxval=10)
    tf.squeeze(a)  # 去掉了所有的1维,返回为shape = [2, 3]
    
    • tf.expand_dims:指定位置增加一维
    # shape=[2, 3]
    t = tf.constant([[1, 2, 3],[4, 5, 6]])
    # shape = [1, 2, 3]
    tf.expand_dims(t, 0)
    # shape = [2, 1, 3]
    tf.expand_dims(t, 1) 
    
    • tf.transpose:tensor本身的维度互换
    # 维度为:[2, 3]
    x = tf.constant([[1, 2, 3], [4, 5, 6]])
    # 维度为[3, 2]
    tf.transpose(x).shape
    
    # 维度: [4, 2, 3]
    x = tf.constant([[[ 1,  2,  3],
                   [ 4,  5,  6]],
                  [[ 7,  8,  9],
                   [10, 11, 12]],
                  [[ 1,  3,  7],
                   [1, 5, 3]],
                 [[2, 7, 4],
                   [2, 9, 10]]])   
    # 维度为[3, 2, 4]
    tf.transpose(x).shape
    
  • 合并分割
    • tf.concat:张量合并,类似pd.concat
    • tf.stack:类似pd.concatnp.stack,但是不同于pd.stack
    • tf.split:tf.concat的逆运算,类似tf.unstack
    # shap = [5, 30]
    x = tf.Variable(tf.random.uniform([5, 30], -1, 1))
    # split to 3份
    tf.split(x, num_or_size_splits=3, axis=1)
    

你可能感兴趣的:(机器学习,tensorflow)