有效地将阈值函数应用于SciPy稀疏csr_matrix

时间:2017-07-02 17:10:41

标签: python numpy scipy sparse-matrix numpy-broadcasting

我有一个1列和x行的SciPy csr_matrix(在这种情况下是一个向量)。它是浮点值,我需要将其转换为离散类标签-1,0和1.这应该使用阈值函数来完成,该函数将浮点值映射到这3个类标签中的一个。

除了Iterating through a scipy.sparse vector (or matrix)中描述的迭代元素之外没有办法吗?我希望有一些优雅的方式以某种方式映射(thresholdfunc())所有元素。

请注意,虽然它的类型为csr_matrix,但它实际上并不稀疏,因为它只是涉及稀疏矩阵的另一个函数的返回。

1 个答案:

答案 0 :(得分:2)

如果您有数组,则可以使用np.where函数根据某些条件进行离散化。 e.g:

>>> 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]])