【问题标题】:np.transpose behavior different for different array constructionsnp.transpose 行为因不同的数组结构而异
【发布时间】:2022-01-17 12:25:47
【问题描述】:

我在np.transpose 中遇到了这种奇怪的行为,其中在numpy 数组和从列表构造的数组上使用时它的工作方式不同。作为一个 MWE,下面的代码被呈现出来。

import numpy as np

a = np.random.randint(0, 5, (1, 2, 3))
print(a.shape)
# prints (1, 2, 3)
b = np.transpose(a, (0, 2, 1))
print(b.shape)
# prints (1, 3, 2), which is expected

# Constructing array from list of arrays
c = np.array([np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3))])
print(c.shape)
# prints (4, 2, 3)
d = np.transpose(c, (2, 0, 1))
print(d.shape)
# prints (3, 4, 2), whereas I expect it to be (2, 3, 4)

我不理解这种行为。为什么从列表构造的数组的维度混淆了?任何帮助表示赞赏。

【问题讨论】:

  • 我在您的示例中看不到任何意外行为。 transpose 按给定顺序排列轴。为什么你认为这取决于数组的构造?
  • @MichaelSzczesny,我的印象是,映射工作相反。在第二个示例中,结果数组中的最后一个维度应该是 4,对应于(2, 0, 1) 的第一个维度应该是 2,第二个维度应该是 3。但正如下面的答案所指出的,映射最初是固定的,然后是我现在理解的排列。

标签: python arrays python-3.x numpy transpose


【解决方案1】:

np.transpose() 按照您指定的顺序选择您指定的维度。

在您的第一种情况下,您的数组形状是(1,2,3),即dimension->value 格式,它是0 -> 11 -> 22 -> 3。在np.transpose() 中,您请求的是0,2,1 的订单,即1,3,2

在第二种情况下,您的数组形状是(4,2,3),即dimension->value 格式,它是0 -> 41 -> 22 -> 3。在np.transpose() 中,您请求订单2,0,1,即3,4,2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多