我有一个 1 列 x 行的 SciPy csr_matrix(在本例中为向量)。其中有浮点值,我需要将其转换为离散类标签 -1、0 和 1。这应该使用阈值函数来完成,该函数将浮点值映射到这 3 个类标签之一。
除了Iterating through a scipy.sparse vector (or matrix)中描述的迭代元素之外,没有其他方法吗? ?我希望有一些优雅的方式来以某种方式在所有元素上映射(thresholdfunc())。
请注意,虽然它是 csr_matrix 类型,但它实际上并不是稀疏的,因为它只是涉及稀疏矩阵的另一个函数的返回。
最佳答案
如果您有一个数组,则可以使用 np.where
函数根据某些条件进行离散化。例如:
>>> import numpy as np
>>> x = np.arange(10)
>>> np.where(x < 5, 0, 1)
array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
语法为np.where(BOOLEAN_ARRAY, VALUE_IF_TRUE, VALUE_IF_FALSE)
。
您可以将两个 where
语句链接在一起以获得多个条件:
>>> np.where(x < 3, -1, np.where(x > 6, 0, 1))
array([-1, -1, -1, 1, 1, 1, 1, 0, 0, 0])
要将其应用于 CSR 或 CSC 稀疏矩阵中的数据,您可以使用 .data
属性,该属性使您可以访问包含稀疏矩阵中所有非零条目的内部数组。例如:
>>> from scipy import sparse
>>> mat = sparse.csr_matrix(x.reshape(10, 1))
>>> mat.data = np.where(mat.data < 3, -1, np.where(mat.data > 6, 0, 1))
>>> mat.toarray()
array([[ 0],
[-1],
[-1],
[ 1],
[ 1],
[ 1],
[ 1],
[ 0],
[ 0],
[ 0]])
关于python - 有效地将阈值函数应用于 SciPy 稀疏 csr_matrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44873272/