【问题标题】:How to reshape a tensor and obtain the first dimension in Tensorflow?如何重塑张量并获得Tensorflow中的第一个维度?
【发布时间】:2025-11-27 23:45:02
【问题描述】:

我有一个张量。假设它的维度是 [2, 999]。如何将其reshape为[999, 2]并得到第一维,即Tensorflow中的999?

【问题讨论】:

    标签: python tensorflow tensor


    【解决方案1】:

    您好,您可以这样做:

    顺便说一句,张量对象没有整形函数,你必须使用 tf.reshape 函数来调用它

    import tensorflow as tf 
    tensor = tf.range(999 * 2) # create a tensor
    reshaped_tensor = tf.reshape(tensor, (2, 999))
    
    # this doesn't work
    tensor = tensor.reshape(999, 2)
    

    你可以用转置命令切换轴,因为你有相同的尺寸

    switched_axis = tf.transpose(tensor) # assuming tensor has a shape of 999, 2
    

    打印第一个维度

    print(tensor.shape[0])
    

    【讨论】:

      【解决方案2】:

      重塑:

      new_tensor = tensor.reshape((999,2))
      

      查找第一个维度:

      first_dimension = tensor.shape[0]
      

      【讨论】: