[英]How to transform a list of 1-D ndarray to 2-D ndarray (mxnet ndarray)
In this example, I have a list of 1-d ndarray, with length 9, the list has 9 elements, and each one has shape=(2048,)
, so totally 9 * (2048,)
, I get these ndarray
from mxnet
so that each of the ndarray
is <NDArray 2048 @cpu(0)>
the array dtype=numpy.float32
在这个例子中,我有1-d ndarray的列表,以及长度为9,该列表具有9个元素,并且每一个具有
shape=(2048,)
所以完全9 * (2048,)
我得到这些ndarray
从mxnet
这样每个ndarray
都是<NDArray 2048 @cpu(0)>
数组dtype=numpy.float32
If I use np.asarray
to transform this list, it becomes the following result如果我使用
np.asarray
来转换这个列表,它会变成下面的结果
shape=<class 'tuple'>: (9, 2048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
Obviously, I want a 2-D array, with shape=(9, 2048)
, how to solve this problem?显然,我想要一个二维数组,
shape=(9, 2048)
,如何解决这个问题?
ps: I discover this problem by saving a npy
file and load it. ps:我通过保存一个
npy
文件并加载它来发现这个问题。 I directly saved the list before converting it to a ndarray
(so the np.save
would transform the list to the ndarrary
automatically) and after I loaded it, I found the shape has become something above, which is really abnormal我直接把list转成
ndarray
之前保存了(所以np.save
会自动把list转成ndarrary
),加载后发现shape变成了上面的东西,真是不正常
The answer below, np.vstack
and np.array
both works for the common list
to ndarray
problem but could not solve mine, so I doubt it is some special case of mxnet
下面的答案,
np.vstack
和np.array
都适用于ndarray
问题的公共list
,但无法解决我的问题,所以我怀疑这是mxnet
一些特殊情况
You can use np.vstack
.您可以使用
np.vstack
。 Here's an example:下面是一个例子:
import numpy as np
li = [np.zeros(2048) for _ in range(9)]
result = np.vstack(li)
print(result.shape)
This outputs (9, 2048)
as desired.这会根据需要输出
(9, 2048)
。
Since the guy who gives the correct answer as comment solve my problem but did not post an answer, I would post his answer here for the others who may also encounter this problem由于给出正确答案作为评论的人解决了我的问题但没有发布答案,我会在这里发布他的答案,供其他可能也遇到此问题的人使用
In fact, the np.array
and mxnet.ndarray
are not exactly the same, so it is dangerous to directly call numpy
methods on mxnet.ndarray
.实际上,
np.array
和mxnet.ndarray
并不完全相同,因此在mxnet.ndarray
上直接调用numpy
方法是危险的。 To use numpy
method in mxnet.ndarray
, we should first transform the array to np.array
, which is要在
mxnet.ndarray
使用numpy
方法,我们应该首先将数组转换为np.array
,即
mx_ndarray = mxnet.ndarray.zeros(5)
np_array = mx_ndarray.asnumpy()
Then numpy
methods could be used on np_array
然后可以在
np_array
上使用numpy
方法
Since the above answer is more general( np.vstack()
), I accept it and just post this answer as a reference, also, np.array()
does the same thing in the above example with np.vstack()
由于上面的答案更笼统(
np.vstack()
),我接受它并将此答案作为参考发布,此外, np.array()
在上面的示例中使用np.vstack()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.