【问题标题】:How to multiply a 3D numpy array in Python to get a 2D numpy array?如何在 Python 中乘以 3D numpy 数组以获得 2D numpy 数组?
【发布时间】:2021-02-19 21:50:24
【问题描述】:

假设我有以下数组 A,其中右侧是它的“.shape”:

A.shape = (10000, 10, 10)

我想得到C.shape = (10000,10) 这样: 对于 A 中的每个 10x10 矩阵(10000 个矩阵),它被简化为每行之和的一维向量 (10,1),因此,最终结果为 C.shape = (10000,10)

基本上,如果我们有形状 (10,10) 并乘以 numpy.ones 向量 (10,1) 就可以完成这项工作。

但是在处理 3D 数组 (10000,10,10) 时如何用 Python 编写呢?

最终目标是形状 (10000,10,10) 乘以 something = (10000,10),其中 (10000,10) 的第二维现在是前一个的行​​和(10,10) 矩阵。

【问题讨论】:

    标签: python arrays numpy multidimensional-array vectorization


    【解决方案1】:

    最简单的解决方案是:

    import numpy as np
    C = np.sum (A, axis=2)
    

    替代解决方案 1(减少):

    如果你想使用reduce()函数,使用这个:

    import numpy as np
    C = np.add.reduce (A, 2)
    

    这里,2 表示通过add 操作进行减少的轴。

    更多详情请参考this

    这可能仅适用于 numpy 的 1.17 及更高版本

    替代解决方案 2:(与向量相乘)

    使用numpy.dot()

    B = np.ones((10,), dtype=A.dtype)
    C = np.dot (A,B)
    

    【讨论】:

      【解决方案2】:

      是的,您可以沿轴 1 使用 .sum()(10000,10,10) 形状数组中获取它:

      import numpy as np
      a=np.ones(1000000).reshape(10000,10,10)
      print(a.shape) # 10000,10,10
      b=a.sum(axis=1)
      print(b.shape) # 10000,10
      c=b.sum(axis=1)
      print(c.shape) # 10000,1
      

      【讨论】:

      • 我不认为这是我想要的,至少当我手动浏览这样的示例时它不会加起来
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 2021-10-28
      • 1970-01-01
      • 2020-02-23
      • 2018-12-22
      • 2021-01-28
      • 2013-01-08
      相关资源
      最近更新 更多