繁体   English   中英

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

[英]Convert numpy object array to sparse matrix

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

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

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

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

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

事实上,即使打电话

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

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

我不认为这是支持的,虽然这方面的文件有点稀疏, 但这部分来源应该表明:

# 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

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

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>

String x.astype('U1')效果要好一些, x.astype('U1') ,但在转换为csr仍然存在问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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