假设我有一个像这样的矩阵:
4 0 3 5
0 2 6 0
7 0 1 0
我希望它二值化为:
0 0 0 0
0 1 0 0
0 0 1 0
即设置阈值等于2,任何大于阈值的元素设置为0,任何小于或等于阈值(0除外)的元素设置为1。
我们可以在 python 的 csr_matrix 或任何其他稀疏矩阵上执行此操作吗?
我知道 scikit-learn 提供 Binarizer 将低于或等于阈值的值替换为 0,高于阈值的值替换为 1。
请您参考如下方法:
处理稀疏矩阵时,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())
产量
matrix([[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])
