【问题标题】:How to find square of individial elements of different sized numpy arrays in the list如何在列表中找到不同大小的numpy数组的单个元素的平方
【发布时间】:2020-11-08 22:16:43
【问题描述】:

考虑我有以下 np 数组列表:

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

我想找到此列表中所有 numpy 数组的每个单独值的平方和。执行以下操作:

>>> np.sum(np.square(l)) 

给出以下错误:

ValueError: operands could not be broadcast together with shapes (2,3) (2,2)

我如何以更 Pythonic 或 numpythonic 的方式做到这一点?我是否必须手动遍历每个 numpy 数组以找到它们的 squres,然后手动求和,如下所示?

>>> np.sum(list(map(lambda i: np.sum(np.square(i)),l)))
944

PS:

以下列表

>>> l                                     
[array([[1, 2, 3],
       [4, 5, 6]]), array([[ 7,  8],
       [ 9, 10]])]

我可以做到:

>>> np.sum(np.square(np.hstack(l)))  
385

但是hstack() 的输入列表的维度似乎有一些限制,因为它在第一个列表上给出了类似的错误。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    我是否必须手动遍历每个 numpy 数组以找到它们的 squres,然后手动求和,如下所示?

    基本上,是的。您有一个形状/长度不兼容的 numpy 数组列表。这意味着你走出了 numpy 数组模型。但你的实现可能会更顺畅一些:

    sum(np.sum(np.square(a)) for a in l)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 2021-06-18
      • 2021-08-19
      • 2018-09-01
      • 1970-01-01
      • 2018-07-15
      相关资源
      最近更新 更多