[英]Make an array of matrices in Python (numpy)
I'm trying to create an undefined length array of matrices for a neural.network, but, when i append the second matrix to the array, the format is messed up.我正在尝试为 neural.network 创建一个未定义长度的矩阵数组,但是,当我 append 数组的第二个矩阵时,格式被搞乱了。
def createRandomWeights(X):
initialW = generateWeights(X.shape[1], S[0]) # first weight matrix
w = np.array([initialW]) # array of weight matrices
for i in range(0, L - 1):
layerW = np.random.uniform(-1, 1, (S[i], S[i + 1]))
w = np.append(w, [layerW])
return w
The function generateWeights only creates an NxM size np.matrix of random numbers between -1 and 1. S is an array of numbers L is the lenght of S function generateWeights 只创建一个 NxM 大小的 np.matrix 随机数在 -1 和 1 之间。S 是一个数字数组 L 是 S 的长度
Example:例子:
S = [2,3]
L = len(s)
X = [[1,1,1],[1,-1,1],[-1,1,1],[-1,-1,1]]
Expected output example (random numbers wrote as 'rn'):预期 output 示例(随机数写为 'rn'):
matrix1 = [[rn, rn],[rn, rn],[rn, rn]] # 3x2 matrix
matrix2 = [[rn, rn, rn],[rn, rn, rn]] # 2x3 matrix
output = [matrix1, matrix2] # 2 matrix elements array
Real output:真实 output:
output = [rn, rn, rn, rn, rn...] #12 times
The problem is that you are using np.append
instead of using the append
method for list in Python.问题是您正在使用
np.append
而不是对 Python 中的列表使用append
方法。
def createRandomWeights(X):
initialW = generateWeights(X.shape[1], S[0]) # first weight matrix
w = np.array([initialW]) # array of weight matrices
for i in range(0, L - 1):
layerW = np.random.uniform(-1, 1, (S[i], S[i + 1]))
w.append(layerW)
return w
The code above should do the job.上面的代码应该可以完成这项工作。 If you check the docs on
np.append
you will see that it will turn the arguments into a 1 dimensional array if no other params are specified.如果你查看
np.append
上的文档,你会发现如果没有指定其他参数,它将把 arguments 变成一维数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.