python - SciPy/NumPy : Normalize a csr_matrix

标签 python numpy scipy

我正在尝试标准化 csr_matrix:

<5400x6845 sparse matrix of type '<type 'numpy.float64'> with 91833 stored elements in Compressed Sparse Row format>

我试过的是这样的:

import numpy as np
from scipy import sparse

# ve is my csr_matrix
ve_sum = ve.sum(axis=1)
ve_sums = sparse.csr_matrix(np.tile(ve_sum, (1, ve.shape[1]))) # <-- here I get MemoryError
n_ve = ve/ve_sums 

这显然不是进行这种简单归一化的正确方法。

正确的做法是什么?

最佳答案

# Normalize the rows of ve.
row_sums = np.array(ve.sum(axis=1))[:,0]
row_indices, col_indices = ve.nonzero()
ve.data /= row_sums[row_indices]

快速谷歌搜索也揭示了这一点。

关于python - SciPy/NumPy : Normalize a csr_matrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13705435/

相关文章:

python - 在 Python 中打印集合时删除集合标识符

检查特定 Linux 命令是否仍在运行的 Python 脚本

python - matplotlib 轮廓可以匹配像素边缘吗?

python理解数组乘法行为

python - NumPy:创建类似于 "repeat"的 bool 数组,但在多个维度中

python - 如何有效地将 scipy 稀疏数组和 numpy 数组分割成较小的 N 个不等 block ?

python - sklearn : how to correlate test data to original data?

Python/Statsmodels - 向量自回归 endog

Numpy 提取网格数据的子集