【问题标题】:What does this third argument of reshape mean?reshape 的第三个参数是什么意思?
【发布时间】:2020-04-29 13:29:42
【问题描述】:

我正在阅读 this question 关于 numpy、array 和 reshape 的内容。我了解 OP 在做什么以及他的代码行,除了 reshape 的最后一个参数:3

根据numpy.reshape的文档,函数的第三个参数是order,应该是一个字符串{'C', 'F', 'A'},可选。

那么 OP 参数 3 是什么意思?

旁注:在问题中,OP 将 3 作为 second 参数,因为它是函数 numpy.array.reshape,而在 numpy.reshape 的文档中,顺序是 第三 论点。但这是因为在numpy.reshape 中,数组本身就是第一个参数。

numpy.array.reshape 文档页面重定向到 numpy.reshape 页面。

【问题讨论】:

    标签: python arrays numpy reshape


    【解决方案1】:

    您查看的reshape 版本错误。相关的是ndarray.reshape

    允许将 shape 参数的元素作为单独的参数传入

    因此,

    a = np.array(...)
    a.reshape(3, 4, 5)
    

    就像在做

    np.reshape(a, (3, 4, 5))
    

    在最初的问题中,3 只是重塑操作的一部分,因为 OP 试图将 RGB 图像作为形状为 (height, width, 3) 的 3D 数组处理

    【讨论】:

    • 在问题的附注中,我确实解释说我注意到了,除了我将“ndarray.reshape”称为“nupy.array.reshape”
    • 3 只是为重塑操作指定形状的一部分
    • 但是形状已经在例子中用len(X)和len(Y)解释过了。参数3是什么意思?
    • 他们试图重塑彩色图像的数据,因此 3 对应于数组/图像的深度,即 RGB 通道。
    • 好的,这意味着一张图片处理三个数组,即每个RGB通道一个数组?
    【解决方案2】:

    考虑以下代码,它按预期运行:

    arr = np.arange(12) # arr has 12 element
    arr = np.reshape(arr, (3, 4)) 
    
    print(arr) # prints '[[ 0  1  2  3] [ 4  5  6  7] [ 8  9 10 11]]'
    

    现在,考虑一下这个有错误的代码:

    arr = np.arange(24) # arr has 24 element
    
    # next line will fail, because (3, 4) can only have 12 element... but 'arr' has 24 element
    arr = np.reshape(arr, (3, 4)) 
    
    print(arr)
    

    我们可以做些什么来解决它?

    一个解决方案是,在主列表中有 3 个父级 list,其中每个父级 list 的结构为 (4, 2)。所以这 3 位父母 list 一起可以持有 8 * 324 项目。这就是为什么下一段代码运行没有任何错误的原因。

    arr = np.arange(24) # arr has 24 element
    
    arr = np.reshape(arr, (3, 4, 2))  # 3 means it will have 3 parent list that has a structure of (4, 2)
    
    print(arr) # prints '[  [[ 0  1] [ 2  3] [ 4  5] [ 6  7]]    [[ 8  9] [10 11] [12 13] [14 15]]    [[16 17] [18 19] [20 21] [22 23]]  ]'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-22
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多