4

我有一个返回 numpy 数组的方法。我想要做的是在每次迭代中获取这个数组并将其连接到另一个数组数组中,以便在循环结束时我有一个矩阵

到目前为止,这是我的代码,但它在给定行崩溃了程序

 delta_Array = np.array([0.01,0.02,0.03, 0.04, 0.05, 0.06,0.07, 0.08, 0.09, 0.10])
 theta_Matrix = np.zeros(8)

 t = Ridge(Xtrain, ytrain, .3) # This method returns an array of 8 elements
 np.append(theta_Matrix,t, axis=0)
 print delta_Array
 print theta_Matrix

使用这种方法,我当前的输出是这样的

 [ 0.01  0.02  0.03  0.04  0.05  0.06  0.07  0.08  0.09  0.1 ] # delta_Array
 [ 0.  0.  0.  0.  0.  0.  0.  0.] # theta_Matrix

经过 2 次迭代后,输出 Id like 应该看起来像这样。此外,我事先不知道 lop 将经历的迭代次数。因此,在方法运行后可以生成任意数量的数组。但无论哪种方式,所有数组都应形成 theta_matrix:

  theta_Matrix:

 [[ 0.65  0.65565  0.19181  0.923  0.51561  0.846  0.6464  0.6464]
  [ 0.9879  0.31213  0.68464  0.611  0.6161  0.61651  0.29858  0.1811]]

谢谢

4

2 回答 2

3

我有一个项目,我需要做一些非常相似的事情。您可以在循环中实现动态调整大小,但 python 的列表类型实际上是作为动态数组实现的,因此您不妨利用已有的工具。你可以这样做:

delta_Array = np.array([0.01,0.02,0.03, 0.04, 0.05, 0.06,0.07, 0.08, 0.09, 0.10])
theta_Matrix = []

for i in range(N):
     t = Ridge(Xtrain, ytrain, .3)
     theta_Matrix.append(t)
theta_Matrix = np.array(theta_Matrix)

我应该提到,如果您已经知道您期望的大小theta_Matrix,您将通过执行以下操作获得最佳性能:

delta_Array = np.array([0.01,0.02,0.03, 0.04, 0.05, 0.06,0.07, 0.08, 0.09, 0.10])
theta_Matrix = np.zeros((N, 8))

for i in range(N):
     t = Ridge(Xtrain, ytrain, .3)
     theta_Matrix[i] = t
于 2012-11-17T18:09:03.410 回答
2

np.append 返回串联的数组,而您忽略了它的返回值。您还应该考虑np.vstack改用,因为它将行向量堆叠成矩阵(append可以这样做,但需要额外的参数)。

但是,运行np.appendnp.vstack循环仍然不是一个好主意,因为构建矩阵将花费二次时间。最好预先分配一个数组,然后使用切片逐行填充它。如果您不知道它需要多大,请考虑使用np.resize.

于 2012-11-17T17:55:26.727 回答