【问题标题】:Convert numpy object array to sparse matrix将numpy对象数组转换为稀疏矩阵
【发布时间】:2018-05-30 10:19:36
【问题描述】:

我想将带有 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吗?

【问题讨论】:

  • 稀疏矩阵可以包含非数字元素吗?
  • 什么是对象 dtype 中的 zero 元素? csr 数学不适用于对象。它是用一组有限的数字类型编译的。你希望用这样的矩阵做什么?连字符串都不起作用。
  • 好吧,我希望None 是zero 元素。但是,只使用数字类型确实有意义。

标签: python arrays numpy matrix scipy


【解决方案1】:

可以从您的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 属性。 (row 和 col 有索引)。

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 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。

【讨论】:

  • 啊,谢谢!我对这种行为感到很困惑,我猜它一定是这样的。感谢您的确认!
猜你喜欢
  • 2021-11-25
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 2023-04-10
  • 2017-07-02
  • 2020-04-07
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多