将numpy对象数组转换为稀疏矩阵

问题描述 投票:0回答:2

我想将dtype=object的numpy数组转换为稀疏数组,例如csr_matrix。但是,这失败了。

x = np.array(['a', 'b', 'c'], dtype=object)

csr_matrix(x) # This fails
csc_matrix(x) # This fails

对稀疏矩阵的两次调用都会产生以下错误:

TypeError:类型不支持转换:(dtype('O'),)

事实上,甚至打电话

csr_matrix(['a', 'b', 'c'])

产生相同的错误。稀疏矩阵不支持object dtypes吗?

python arrays numpy matrix scipy
2个回答
2
投票

可以从coo创建x格式矩阵:

In [22]: x = np.array([['a', 'b', 'c']], dtype=object)
In [23]: M=sparse.coo_matrix(x)
In [24]: M
Out[24]: 
<1x3 sparse matrix of type '<class 'numpy.object_'>'
    with 3 stored elements in COOrdinate format>
In [25]: M.data
Out[25]: array(['a', 'b', 'c'], dtype=object)

coo刚刚将输入数组展平并将其分配给data属性。 (rowcol有指数)。

In [31]: M=sparse.coo_matrix(x)
In [32]: print(M)
  (0, 0)    a
  (0, 1)    b
  (0, 2)    c

但是将其显示为数组会产生错误。

In [26]: M.toarray()
ValueError: unsupported data types in input

试图将其转换为其他格式会产生你的typeerror

dok的作品:

In [28]: M=sparse.dok_matrix(x)
/usr/local/lib/python3.5/dist-packages/scipy/sparse/sputils.py:114: UserWarning: object dtype is not supported by sparse matrices
  warnings.warn("object dtype is not supported by sparse matrices")
In [29]: M
Out[29]: 
<1x3 sparse matrix of type '<class 'numpy.object_'>'
    with 3 stored elements in Dictionary Of Keys format>

字符串dtype工作得更好,x.astype('U1'),但仍然有转换到csr的问题。

针对大线性代数问题开发了稀疏矩阵。进行矩阵乘法和线性方程解的能力是最重要的。它们对非数字任务的应用是最近的,并且是不完整的。


2
投票

我不认为这是支持的,虽然文件在这方面有点稀疏,this part of the sources应该表明:

# List of the supported data typenums and the corresponding C++ types
#
T_TYPES = [
    ('NPY_BOOL', 'npy_bool_wrapper'),
    ('NPY_BYTE', 'npy_byte'),
    ('NPY_UBYTE', 'npy_ubyte'),
    ('NPY_SHORT', 'npy_short'),
    ('NPY_USHORT', 'npy_ushort'),
    ('NPY_INT', 'npy_int'),
    ('NPY_UINT', 'npy_uint'),
    ('NPY_LONG', 'npy_long'),
    ('NPY_ULONG', 'npy_ulong'),
    ('NPY_LONGLONG', 'npy_longlong'),
    ('NPY_ULONGLONG', 'npy_ulonglong'),
    ('NPY_FLOAT', 'npy_float'),
    ('NPY_DOUBLE', 'npy_double'),
    ('NPY_LONGDOUBLE', 'npy_longdouble'),
    ('NPY_CFLOAT', 'npy_cfloat_wrapper'),
    ('NPY_CDOUBLE', 'npy_cdouble_wrapper'),
    ('NPY_CLONGDOUBLE', 'npy_clongdouble_wrapper'),
]

要求基于对象的类型听起来很多。甚至还缺少一些像float16这样的基本类型。

© www.soinside.com 2019 - 2024. All rights reserved.