【问题标题】:What does -1 mean in numpy reshape?-1 在 numpy reshape 中是什么意思?
【发布时间】:2013-09-12 12:28:56
【问题描述】:

一个 numpy 矩阵可以使用参数 -1 的 reshape 函数重新整形为一个向量。但我不知道 -1 在这里是什么意思。

例如:

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

b 的结果是:matrix([[1, 2, 3, 4, 5, 6, 7, 8]])

有人知道 -1 在这里是什么意思吗? 而且似乎python给-1赋予了几种含义,比如:array[-1]表示最后一个元素。能解释一下吗?

【问题讨论】:

    标签: python numpy reshape numpy-ndarray


    【解决方案1】:

    提供新形状要满足的标准是'新形状应该与原始形状兼容'

    numpy 允许我们将新的形状参数之一指定为 -1(例如:(2,-1) 或 (-1,3) 但不是 (-1, -1))。它只是意味着它是一个未知维度,我们希望 numpy 弄清楚它。 numpy 将通过查看'数组的长度和剩余维度' 并确保它满足上述条件来计算这一点

    现在看例子。

    z = np.array([[1, 2, 3, 4],
             [5, 6, 7, 8],
             [9, 10, 11, 12]])
    z.shape
    (3, 4)
    

    现在尝试用 (-1) 重塑。结果新形状为 (12,) 并且与原始形状 (3,4) 兼容

    z.reshape(-1)
    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
    

    现在尝试用 (-1, 1) 重塑。我们提供了 column 为 1 但 rows 为 unknown 。所以我们得到的结果新形状为 (12, 1)。再次与原始形状 (3,4) 兼容

    z.reshape(-1,1)
    array([[ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5],
       [ 6],
       [ 7],
       [ 8],
       [ 9],
       [10],
       [11],
       [12]])
    

    以上与numpyadvice/error message 一致,将reshape(-1,1) 用于单个功能;即单列

    如果您的数据具有单一特征

    ,请使用 array.reshape(-1, 1) 重塑您的数据

    新形状为 (-1, 2)。行未知,第 2 列。我们得到的结果新形状为 (6, 2)

    z.reshape(-1, 2)
    array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10],
       [11, 12]])
    

    现在尝试将列保持为未知。新形状为 (1,-1)。即,行为 1,列未知。我们得到结果新形状为 (1, 12)

    z.reshape(1,-1)
    array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]])
    

    以上与numpyadvice/error message一致,单样使用reshape(1,-1);即单行

    如果数据包含单个样本

    ,则使用 array.reshape(1, -1) 重塑您的数据

    新形状 (2, -1)。第 2 行,列未知。我们得到结果新形状为 (2,6)

    z.reshape(2, -1)
    array([[ 1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12]])
    

    新形状为 (3, -1)。第 3 行,列未知。我们得到结果新形状为 (3,4)

    z.reshape(3, -1)
    array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
    

    最后,如果我们尝试将两个维度都提供为未知,即新形状为 (-1,-1)。会报错

    z.reshape(-1, -1)
    ValueError: can only specify one unknown dimension
    

    【讨论】:

    • 这个答案包含很多例子,但没有列出 -1 用简单的英语做什么。重塑数组时,新形状必须包含与旧形状相同数量的元素,这意味着两个形状尺寸的乘积必须相等。当使用-1时,-1对应的维度将是原始数组的维度除以给reshape的维度的乘积,以保持相同的元素数量。
    • 在我看来接受的答案和这个答案都有帮助,而接受的答案更简单,我更喜欢更简单的答案
    • 形状 (12, 1) 与形状 (3,4) 如何“兼容”?
    • @Vijender 我猜这意味着相同数量的元素但不同的轴 - 即 12x1 == 3x4?
    • 一个 (12,1) 数组是一个包含 12 个元素的容器。 (3,4) 和 (2,6) 数组等也有 12 个元素。它们与 重塑元素 兼容,这是 OP 问题中的功能。请注意,对于一大堆函数,(12x1)数组与(3x4)数组不兼容,例如 np.matmul()
    【解决方案2】:

    用于重塑数组。

    假设我们有一个维度为 2 x 10 x 10 的 3 维数组:

    r = numpy.random.rand(2, 10, 10) 
    

    现在我们要重塑为 5 X 5 x 8:

    numpy.reshape(r, shape=(5, 5, 8)) 
    

    会做的。

    请注意,一旦您修复了第一个 dim = 5 和第二个 dim = 5,您就不需要确定第三个维度。为了缓解你的懒惰,Numpy 提供了使用 -1 的选项:

    numpy.reshape(r, shape=(5, 5, -1)) 
    

    会给你一个shape = (5, 5, 8)的数组。

    同样,

    numpy.reshape(r, shape=(50, -1)) 
    

    会给你一个 shape = (50, 4) 的数组

    您可以在http://anie.me/numpy-reshape-transpose-theano-dimshuffle/阅读更多内容

    【讨论】:

      【解决方案3】:

      根据the documentation

      newshape : 整数或整数元组

      新形状应与原始形状兼容。如果 整数,则结果将是该长度的一维数组。一种形状 维度可以是-1。在这种情况下,该值是从 数组长度和剩余维度。

      【讨论】:

      • 在这种情况下,该值被推断为 [1, 8]。 8是矩阵a的总数。对吗?
      • @user2262504,我不确定。我认为推断的值是[8],因为文档是这样说的(1-D array)。试试numpy.reshape(a, [8])。对于矩阵,它与numpy.reshape(a, [1,8]) 产生相同的结果。
      • -1 让 numpy 为您确定结果矩阵中未知的列数或行数。注意:未知数应该是列或行,而不是两者。
      【解决方案4】:
      numpy.reshape(a,newshape,order{})
      

      查看以下链接了解更多信息。 https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

      对于您提到的以下示例,输出将结果向量解释为单行。(-1)表示行数为 1。 如果

      a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
      b = numpy.reshape(a, -1)
      

      输出:

      matrix([[1, 2, 3, 4, 5, 6, 7, 8]])
      

      这可以用另一个例子更准确地解释:

      b = np.arange(10).reshape((-1,1))
      

      输出:(是一维柱状数组)

      array([[0],
             [1],
             [2],
             [3],
             [4],
             [5],
             [6],
             [7],
             [8],
             [9]])
      

      b = np.arange(10).reshape((1,-1))
      

      输出:(是一维行数组)

      array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
      

      【讨论】:

        【解决方案5】:

        转换的最终结果是最终数组中的元素个数与初始数组或数据框的元素个数相同。

        -1 对应于行或列的未知计数。 我们可以将其视为x(unknown)。 x 是通过将原始数组中的元素个数除以有序对的另一个值与 -1 得到的。

        例子:

        reshape(-1,1) 的 12 个元素对应于 x=12/1=12 行 1 列的数组。


        reshape(1,-1) 的 12 个元素对应于 1 行 x=12/1=12 列的数组。

        【讨论】:

          【解决方案6】:

          这只是意味着您不确定可以提供多少行或列数,并且您要求 numpy 建议要重新调整的列数或行数。

          numpy 提供了 -1 的最后一个例子 https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

          检查下面的代码及其输出以更好地理解 (-1):

          代码:-

          import numpy
          a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
          print("Without reshaping  -> ")
          print(a)
          b = numpy.reshape(a, -1)
          print("HERE We don't know about what number we should give to row/col")
          print("Reshaping as (a,-1)")
          print(b)
          c = numpy.reshape(a, (-1,2))
          print("HERE We just know about number of columns")
          print("Reshaping as (a,(-1,2))")
          print(c)
          d = numpy.reshape(a, (2,-1))
          print("HERE We just know about number of rows")
          print("Reshaping as (a,(2,-1))")
          print(d)
          

          输出:-

          Without reshaping  -> 
          [[1 2 3 4]
           [5 6 7 8]]
          HERE We don`t know about what number we should give to row/col
          Reshaping as (a,-1)
          [[1 2 3 4 5 6 7 8]]
          HERE We just know about number of columns
          Reshaping as (a,(-1,2))
          [[1 2]
           [3 4]
           [5 6]
           [7 8]]
          HERE We just know about number of rows
          Reshaping as (a,(2,-1))
          [[1 2 3 4]
           [5 6 7 8]]
          

          【讨论】:

            【解决方案7】:

            -1 代表“未知维度”,可以从另一个维度推断。 在这种情况下,如果您像这样设置矩阵:

            a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
            

            像这样修改你的矩阵:

            b = numpy.reshape(a, -1)
            

            它将调用矩阵a的一些默认操作,这将返回一个一维numpy数组/矩阵。

            但是,我认为使用这样的代码不是一个好主意。为什么不试试呢:

            b = a.reshape(1, -1)
            

            它会给你同样的结果,而且读者更容易理解:将b设置为a的另一种形状。对于a,我们不知道它应该有多少列(将其设置为 -1!),但我们想要一个一维数组(将第一个参数设置为 1!)。

            【讨论】:

              【解决方案8】:

              长话短说:您设置了一些维度,让 NumPy 设置剩余的维度。

              (userDim1, userDim2, ..., -1) -->>
              
              (userDim1, userDim1, ..., TOTAL_DIMENSION - (userDim1 + userDim2 + ...))
              

              【讨论】:

              • 这是我一直在寻找的英文答案,简单明了。即你给出你的设计偏好,让 numpy 算出剩下的数学:)
              【解决方案9】:
              import numpy as np
              x = np.array([[2,3,4], [5,6,7]]) 
              
              # Convert any shape to 1D shape
              x = np.reshape(x, (-1)) # Making it 1 row -> (6,)
              
              # When you don't care about rows and just want to fix number of columns
              x = np.reshape(x, (-1, 1)) # Making it 1 column -> (6, 1)
              x = np.reshape(x, (-1, 2)) # Making it 2 column -> (3, 2)
              x = np.reshape(x, (-1, 3)) # Making it 3 column -> (2, 3)
              
              # When you don't care about columns and just want to fix number of rows
              x = np.reshape(x, (1, -1)) # Making it 1 row -> (1, 6)
              x = np.reshape(x, (2, -1)) # Making it 2 row -> (2, 3)
              x = np.reshape(x, (3, -1)) # Making it 3 row -> (3, 2)
              

              【讨论】:

                【解决方案10】:

                在阅读this article 之前,我无法理解np.reshape() 的作用。

                从机械上讲,reshape() 做了什么很清楚。但是我们如何解读 reshape 前后的数据呢?

                对我来说缺少的部分是:

                当我们训练机器学习模型时,数组的嵌套级别具有精确定义的含义。

                这意味着重塑操作必须敏锐地意识到以下两点,操作才有任何意义:

                • 它操作的数据(reshape 输入的样子)
                • 算法/模型期望重整后的数据如何(重整后输出的样子)

                例如:

                外部数组包含观察/行。内部数组包含列/特征。当我们有一组仅对一个特征的多个观察值或对多个特征的单个观察值时,这会导致两种特殊情况。

                更高级的例子: 见this stackoverflow question

                【讨论】:

                  【解决方案11】:

                  当你在

                  中使用 -1(或任何其他负整数,我做了这个测试 kkk)
                  b = numpy.reshape(a, -1)
                  

                  您只是说 numpy.reshape 自动计算向量的大小(行 x 列)并将其重新定位到具有该维度的一维向量中。这个命令很有趣,因为它会自动为您执行。如果您想通过输入一个正整数值将向量重塑为一维,则reshape 命令只有在您正确输入值“行 x 列”时才有效。因此,您知道,能够输入负整数会使过程更容易。

                  【讨论】:

                    猜你喜欢
                    • 2017-06-06
                    • 1970-01-01
                    • 1970-01-01
                    • 2010-12-28
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-04-28
                    相关资源
                    最近更新 更多