以不同的方式在python中二进制化稀疏矩阵

cin*_*vro 1 python numpy matrix sparse-matrix

假设我有一个矩阵,如:

4 0 3 5
0 2 6 0
7 0 1 0
Run Code Online (Sandbox Code Playgroud)

我希望它二进制化为:

0 0 0 0
0 1 0 0
0 0 1 0
Run Code Online (Sandbox Code Playgroud)

即将阈值设置为2,将大于阈值的任何元素设置为0,将小于或等于阈值的任何元素(除0)设置为1.

我们可以在python的csr_matrix或任何其他稀疏矩阵上执行此操作吗?

我知道scikit-learn提供Binarizer将低于或等于阈值的值替换为0,高于1.

unu*_*tbu 7

当处理稀疏矩阵时s,避免包含零的不等式,因为稀疏矩阵(如果你正确使用它)应该有很多零,并且形成一个零的所有位置的数组将是巨大的.所以避免s <= 2例如.使用从零开始选择的不等式.

import numpy as np
from scipy import sparse

s = sparse.csr_matrix(np.array([[4, 0, 3, 5],
         [0, 2, 6, 0],
         [7, 0, 1, 0]]))

print(s)
# <3x4 sparse matrix of type '<type 'numpy.int64'>'
#   with 7 stored elements in Compressed Sparse Row format>

s[s > 2] = 0
s[s != 0] = 1

print(s.todense())
Run Code Online (Sandbox Code Playgroud)

产量

matrix([[0, 0, 0, 0],
        [0, 1, 0, 0],
        [0, 0, 1, 0]])
Run Code Online (Sandbox Code Playgroud)