擅长:python、mysql、java
<p>虽然Aarons的回答是正确的,但我实现了一个解决方案,当时我想规范化<em>绝对</em>值的最大值,sklearn没有提供这个值。我的方法使用非零项并在csr_matrix.data数组中找到它们,以便快速替换其中的值。</p>
<pre><code>def normalize_sparse(csr_matrix):
nonzero_rows = csr_matrix.nonzero()[0]
for idx in np.unique(nonzero_rows):
data_idx = np.where(nonzero_rows==idx)[0]
abs_max = np.max(np.abs(csr_matrix.data[data_idx]))
if abs_max != 0:
csr_matrix.data[data_idx] = 1./abs_max * csr_matrix.data[data_idx]
</code></pre>
<p>与sunan的解决方案相反,这种方法不需要将矩阵转换成密集格式(这可能会引起内存问题),也不需要矩阵乘法。我在一个稀疏的形状矩阵(350000486000)上测试了这个方法,花了大约18秒。</p>