How to fix “NaN or infinity” issue for sparse matrix in python?

99封情书 提交于 2019-12-05 22:55:20

I found that doing the following, assuming sm is a sparse matrix (mine was CSR matrix, please say something about other types if you know!) worked quite nicely:

Manually replacing nans with appropriate numbers in data vector:

In [4]: np.isnan(matrix.data).any()
Out[4]: True

In [5]: sm.data.shape
Out[5]: (553555,)

In [6]: sm.data = np.nan_to_num(sm.data)

In [7]: np.isnan(matrix.data).any()
Out[7]: False

In [8]: sm.data.shape
Out[8]: (553555,)

So we no longer have nan values, but matrix explicitly encodes those zeros as valued indices.

Removing explicitly encoded zero values from sparse matrix:

In [9]: sm.eliminate_zeros()

In [10]: sm.data.shape
Out[10]: (551391,)

And our matrix actually got smaller now, yay!

I usually use this function:

x = np.nan_to_num(x)

Replace nan with zero and inf with finite numbers.

This usually happens when you have missing values in your data or as a result of your processing.

First, find the cells in the sparse matrix X with Nan or Inf value:

def find_nan_in_csr(self, X):

    X = coo_matrix(X)
    for i, j, v in zip(X.row, X.col, X.data):
        if (np.isnan(v) or np.isinf(v)):
            print(i, j, v)
    return None

This function will provide you the row and column indexes in the sparse matrix where the values are problematic.
Then, to "fix" the values - it depends what caused these values (missing values, etc.).

EDIT: Note that sklearn is usually using dtype=np.float32 for maximum efficiency, so it converts sparse matrix to np.float32 (by X = X.astype(dtype = np.float32)) when it can. In this conversion from float64 to np.float32, a very high number (e.g.,2.9e+200) are converted to inf.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!