简体   繁体   English

如何将一维 ndarray 列表转换为二维 ndarray (mxnet ndarray)

[英]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,)我得到这些ndarraymxnet这样每个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.vstacknp.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.arraymxnet.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM