本文介绍了scipy.sparse.hstack(([[1],[2]))-> "ValueError:块必须是二维的".为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scipy.sparse.hstack((1, [2]))scipy.sparse.hstack((1, [2]))可以正常工作,但scipy.sparse.hstack(([1], [2]))则不能.为什么会这样?

scipy.sparse.hstack((1, [2])) and scipy.sparse.hstack((1, [2])) work well, but not scipy.sparse.hstack(([1], [2])). Why is this the case?

以下是我系统上发生的情况的踪迹:

Here is a trace of what's happening on my system:

C:\Anaconda>python
Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52) [MSC v.
1500 64 bit (AMD64)] on win32
>>> import scipy.sparse
>>> scipy.sparse.hstack((1, [2]))
<1x2 sparse matrix of type '<type 'numpy.int32'>'
        with 2 stored elements in COOrdinate format>
>>> scipy.sparse.hstack((1, 2))
<1x2 sparse matrix of type '<type 'numpy.int32'>'
        with 2 stored elements in COOrdinate format>
>>> scipy.sparse.hstack(([1], [2]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda\lib\site-packages\scipy\sparse\construct.py", line 456, in h
stack
    return bmat([blocks], format=format, dtype=dtype)
  File "C:\Anaconda\lib\site-packages\scipy\sparse\construct.py", line 539, in b
mat
    raise ValueError('blocks must be 2-D')
ValueError: blocks must be 2-D
>>> scipy.version.full_version
'0.16.0'
>>>

推荐答案

编码细节为:

def hstack(blocks ...):
    return bmat([blocks], ...)

def bmat(blocks, ...):
    blocks = np.asarray(blocks, dtype='object')
    if blocks.ndim != 2:
        raise ValueError('blocks must be 2-D')
    (continue)

因此,请尝试其他方法(记住额外的[]):

So trying your alternatives (remembering the extra []):

In [392]: np.asarray([(1,2)],dtype=object)
Out[392]: array([[1, 2]], dtype=object)

In [393]: np.asarray([(1,[2])],dtype=object)
Out[393]: array([[1, [2]]], dtype=object)

In [394]: np.asarray([([1],[2])],dtype=object)
Out[394]: 
array([[[1],
        [2]]], dtype=object)

In [395]: _.shape
Out[395]: (1, 2, 1)

最后一个案例(您的问题案例)失败了,因为结果是3d.

This last case (your problem case) failed because the result was 3d.

具有2个稀疏矩阵(预期输入):

With 2 sparse matrices (expected input):

In [402]: np.asarray([[a,a]], dtype=object) 
Out[402]: 
array([[ <1x1 sparse matrix of type '<class 'numpy.int32'>'
    with 1 stored elements in COOrdinate format>,
        <1x1 sparse matrix of type '<class 'numpy.int32'>'
    with 1 stored elements in COOrdinate format>]], dtype=object)

In [403]: _.shape
Out[403]: (1, 2)

hstack通过将矩阵列表转换为嵌套的(2d)矩阵列表来利用bmat格式. bmat是将2d稀疏矩阵数组组合成一个较大的数组的一种方式.跳过首先制作这些稀疏矩阵的步骤可能会,也可能不会.代码和文档没有任何承诺.

hstack is taking advantage of the bmat format, by turning a list of matrices into a nested (2d) list of matrices. bmat is meant to be a way of combining a 2d array of sparse matrices into one larger one. Skipping the step of first making these sparse matrices may, or might not, work. The code and the documentation don't make any promises.

这篇关于scipy.sparse.hstack(([[1],[2]))-> "ValueError:块必须是二维的".为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 08:18