【问题标题】:For a np.array([1, 2, 3]) why is the shape (3,) instead of (3,1)? [duplicate]对于 np.array([1, 2, 3]) 为什么是形状 (3,) 而不是 (3,1)? [复制]
【发布时间】:2017-02-02 22:03:24
【问题描述】:

我注意到对于具有 3 个元素的 1 级数组,numpy 会为形状返回 (3,)。我知道这个元组代表了数组沿每个维度的大小,但是为什么不是(3,1)呢?

import numpy as np

a = np.array([1, 2, 3])  # Create a rank 1 array
print a.shape            # Prints "(3,)"

b = np.array([[1,2,3],[4,5,6]])   # Create a rank 2 array
print b.shape                     # Prints "(2, 3)"

【问题讨论】:

  • 一组括号,一个维度。

标签: python arrays numpy


【解决方案1】:

您同样可以问:“为什么形状不是(3,1,1,1,1,1,1)?毕竟它们是等价的。

NumPy 经常选择折叠单个维度,或者将它们视为可选的,例如在broadcasting 期间。这很强大,因为 3 向量与 3x1x1x1x1x1 矩阵具有完全相同的元素数量和相同的相对方向。

【讨论】:

  • 这是不正确的 - 广播会忽略长度为 1 的 前导 维度,而不是尾随维度。所以1x1x1x1x1x33是一样的
  • numpy 可以在广播期间添加前导 1,但它不会忽略它们,无论是前导还是尾随。您已使用squeeze 或索引来删除它们。
【解决方案2】:

简而言之,这是因为它是 one 维数组(因此是 one 元素形状元组)。也许以下内容将有助于解决问题:

>>> np.array([1, 2, 3]).shape
(3,)
>>> np.array([[1, 2, 3]]).shape
(1, 3)
>>> np.array([[1], [2], [3]]).shape
(3, 1)

我们甚至可以进入三个维度(甚至更高):

>>> np.array([[[1]], [[2]], [[3]]]).shape
(3, 1, 1)

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 2015-04-08
    • 2017-07-10
    • 2019-01-09
    • 2018-12-10
    • 2021-05-09
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    相关资源
    最近更新 更多