我想将一个numpy数组转换dtype=object
为一个稀疏数组,例如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吗?
可以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
属性。(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>
字符串dtype效果更好,x.astype('U1')
但是转换为仍然有问题csr
。
开发了用于大型线性代数问题的稀疏矩阵。进行矩阵乘法和线性方程求解的能力最为重要。它们在非数字任务中的应用是最近的,并且不完整。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句