[英]Numpy create an array of matrices
I am trying to store matrices into an array, however when I append the matrix, it would get every element and output just an 1 dimensional array. 我正在尝试将矩阵存储到数组中,但是当我追加矩阵时,它将获取每个元素并仅输出一维数组。
Example Code: 示例代码:
matrix_array= np.array([])
for y in y_label:
matrix_array= np.append(matrix_array, np.identity(3))
Clearly np.append
is the wrong tool for the job: 显然,
np.append
是这项工作的错误工具:
In [144]: np.append(np.array([]), np.identity(3))
Out[144]: array([ 1., 0., 0., 0., 1., 0., 0., 0., 1.])
From its docs: 从其文档:
If
axis
is not specified,values
can be any shape and will be flattened before use.如果未指定
axis
,则values
可以是任何形状,并且在使用前将被展平。
With list append 附有清单
In [153]: alist=[]
In [154]: for y in [1,2]:
...: alist.append(np.identity(3))
...:
In [155]: alist
Out[155]:
[array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]]), array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])]
In [156]: np.array(alist)
Out[156]:
array([[[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]],
[[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]]])
In [157]: _.shape
Out[157]: (2, 3, 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.