numpy中具有不同行长的矩阵 [英] Matrices with different row lengths in numpy

查看:168
本文介绍了numpy中具有不同行长的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以定义具有不同长度行的numpy矩阵(例如 m ),但是 m 保持二维(iemndim = 2 )?

Is there a way of defining a matrix (say m) in numpy with rows of different lengths, but such that m stays 2-dimensional (i.e. m.ndim = 2)?

例如,如果您定义 m = numpy.array([[1,2,3],[4,5]]),则 m.ndim = 1.我知道为什么会发生这种情况,但是我对是否有任何办法欺骗numpy将 m 视为2D感兴趣.一种想法是使用虚拟值进行填充,以使行的大小相等,但是我有很多这样的矩阵,并且会占用太多空间.我之所以真正需要 m 是2D的原因是我正在与Theano合作,并且将获得 m 值的张量需要一个2D值.

For example, if you define m = numpy.array([[1,2,3], [4,5]]), then m.ndim = 1. I understand why this happens, but I'm interested if there is any way to trick numpy into viewing m as 2D. One idea would be padding with a dummy value so that rows become equally sized, but I have lots of such matrices and it would take up too much space. The reason why I really need m to be 2D is that I am working with Theano, and the tensor which will be given the value of m expects a 2D value.

推荐答案

否,这是不可能的. NumPy数组在每对尺寸中都必须为矩形.这是由于它们映射到内存缓冲区的方式,如指针,项大小,跨步三倍.

No, this is not possible. NumPy arrays need to be rectangular in every pair of dimensions. This is due to the way they map onto memory buffers, as a pointer, itemsize, stride triple.

至于占用空间:np.array([[1,2,3], [4,5]])实际上比2×3数组占用更多的空间,因为它是两个指向Python列表的指针的数组(即使元素被转换为数组,内存布局也会仍然效率不高).

As for this taking up space: np.array([[1,2,3], [4,5]]) actually takes up more space than a 2×3 array, because it's an array of two pointers to Python lists (and even if the elements were converted to arrays, the memory layout would still be inefficient).

这篇关于numpy中具有不同行长的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆