[英]Multiple 2D numpy arrays in 1 array
我正在为一个基本的神经网络进行反向传播,对于每个示例,我必须计算新的权重。 我将权重保存在一个名为weights
的 2D numpy 数组中,如下所示:
[[0.09719335 0.03077288 0.84256845 0.78993436]
[0.87452232 0.9833483 0.803617 0.46675746]
[0.77805488 0.11567956 0.63747511 0.14045771]]
对于新的权重,我需要一对神经元之间每个权重的平均值。 我的想法是为我的训练集中的所有数据项计算它,然后计算平均值。 为此,我想用 np.zeros 制作一个零数组,上面数组的大小乘以我的集合中的数据项数量。 我试过这样
newWeights = np.zeros((2,(weights.shape)))
但这没有用。 有没有办法像这样初始化一个数组,或者有另一种方法可以让我更容易地做到这一点(我想过 np.append 但无法弄清楚)
weights.shape
是一个元组,因此不能按原样包含它,因为尺寸必须是整数。 您可以使用 * 解包元组:
newWeights = np.zeros((2, *weights.shape))
这基本上解开了weights.shape
所以它相当于 (2, x, y) 的尺寸。
你可以这样做
import numpy as np
arr = np.array( [[0.09719335, 0.03077288, 0.84256845, 0.78993436],
[0.87452232, 0.9833483, 0.803617, 0.46675746],
[0.77805488, 0.11567956, 0.63747511, 0.14045771]])
arr3D = np.zeros((2,*arr.shape))
然后在 3D 数组中保存一个二维数组,如下所示:
arr3D[0,:,:] = arr
平均数组的计算是这样的:
mean_arr = arr3D.mean(axis=0)
假设您可以就地修改weights
-array, np.ndarray.resize
会将您的数组大小调整为(2, 3, 4)
并用0
填充新值:
import numpy as np
weights = np.asarray([[0.09719335, 0.03077288, 0.84256845, 0.78993436], [0.87452232, 0.9833483, 0.803617, 0.46675746],
[0.77805488, 0.11567956, 0.63747511, 0.14045771]])
print(weights.shape) # (3, 4)
weights.resize((2, *weights.shape), refcheck=False)
print(weights.shape) # (2, 3, 4)
[[[0.09719335 0.03077288 0.84256845 0.78993436]
[0.87452232 0.9833483 0.803617 0.46675746]
[0.77805488 0.11567956 0.63747511 0.14045771]]
[[0. 0. 0. 0. ]
[0. 0. 0. 0. ]
[0. 0. 0. 0. ]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.