1 个数组中的多个 2D numpy 数组
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 数组中保存一个 2D 数组:
arr3D[0,:,:] = arr
均值数组的计算是这样的:
mean_arr = arr3D.mean(axis=0)
假设您可以就地修改 weights
数组,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. ]]]
我正在研究基本神经网络的反向传播,对于每个示例我都必须计算新的权重。我将权重保存在一个名为 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 数组中保存一个 2D 数组:
arr3D[0,:,:] = arr
均值数组的计算是这样的:
mean_arr = arr3D.mean(axis=0)
假设您可以就地修改 weights
数组,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. ]]]