简体   繁体   English

按元素添加 numpy 数组列表

[英]Add lists of numpy arrays element-wise

I've been working on an algorithm for backpropagation in neural networks.我一直在研究神经网络中的反向传播算法。 My program calculates the partial derivative of each weight with respect to the loss function, and stores it in an array.我的程序计算每个权重相对于损失函数的偏导数,并将其存储在一个数组中。 The weights at each layer are stored in a single 2d numpy array, and so the partial derivatives are stored as an array of numpy arrays, where each numpy array has a different size depending on the number of neurons in each layer.每层的权重存储在单个 2d numpy 数组中,因此偏导数存储为 numpy 数组的数组,其中每个 numpy 数组具有不同的大小,具体取决于每层中的神经元数量。

When I want to average the array of partial derivatives after a number of training data has been used, I want to add each array together and divide by the number of arrays.当我想在使用大量训练数据后对偏导数数组求平均值时,我想将每个数组加在一起并除以数组数。 Currently, I just iterate through each array and add each element together, but is there a quicker way?目前,我只是遍历每个数组并将每个元素添加在一起,但有没有更快的方法? I could use ndarray with dtype=object but apparently, this has been deprecated.我可以将 ndarray 与 dtype=object 一起使用,但显然,这已被弃用。

For example, if I have the arrays:例如,如果我有数组:

arr1 = [ndarray([[1,1],[1,1],[1,1]]), ndarray([[2,2],[2,2]])]
arr2 = [ndarray([[3,3],[3,3],[3,3]]), ndarray([[4,4],[4,4]])]

How can I add these together to get the array:我怎样才能把这些加在一起得到数组:

arr3 = [ndarray([[4,4],[4,4],[4,4]]), ndarray([[6,6],[6,6]])]

You can use zip / map / sum :您可以使用zip / map / sum

import numpy as np
arr1 = [np.array([[1,1],[1,1],[1,1]]), np.array([[2,2],[2,2]])]
arr2 = [np.array([[3,3],[3,3],[3,3]]), np.array([[4,4],[4,4]])]

arr3 = list(map(sum, zip(arr1, arr2)))

output:输出:

>>> arr3
[array([[4, 4],
        [4, 4],
        [4, 4]]),
 array([[6, 6],
        [6, 6]])]

In NumPy, you can add two arrays element-wise by adding two NumPy arrays.在 NumPy 中,您可以通过添加两个 NumPy 数组来按元素添加两个数组。 NB: if your array shape varies then reshape the array and fill with 0.注意:如果您的数组形状发生变化,则重新调整数组的形状并用 0 填充。

arr1 = np.array([np.array([[1,1],[1,1],[1,1]]), np.array([[2,2],[2,2]])])
arr2 = np.array([np.array([[3,3],[3,3],[3,3]]), np.array([[4,4],[4,4]])])
arr3 = arr2 + arr1

You don't need to add the numbers in the array element-wise, make use of numpy's parallel computations by usingnumpy.add您不需要按元素添加数组中的数字,通过使用numpy.add来利用 numpy 的并行计算

Here's some code to do just that:这里有一些代码可以做到这一点:

import numpy as np

arr1 = np.asarray([[[1,1],[1,1],[1,1]], [[2,2],[2,2]]])
arr2 = np.asarray([[[3,3],[3,3],[3,3]], [[4,4],[6,6]]])

ans = []

for first, second in zip(arr1, arr2):
    ans.append(np.add(first,second))

Outputs:输出:

>>> [array([[4, 4], [4, 4], [4, 4]]), array([[6, 6], [8, 8]])]

PS Could use a one-liner list-comprehension as well PS 也可以使用单行列表理解

ans = [np.add(first, second) for first, second in zip(arr1, arr2)]

您可以使用列表理解:

[x + y for x, y in zip(arr1, arr2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM