初始化高维稀疏矩阵

本教程将介绍初始化高维稀疏矩阵的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

初始化高维稀疏矩阵 教程 第1张

问题描述

我希望使用sklearn初始化300,000 x 300,0000稀疏矩阵,但它需要内存,就像它不是稀疏矩阵一样:

>>> from scipy import sparse
>>> sparse.rand(300000,300000,.1)

它显示错误:

MemoryError: Unable to allocate 671. GiB for an array with shape (300000, 300000) and data type float64

这与我使用numpy进行初始化时的错误相同:

np.random.normal(size=[300000, 300000])

即使我的密度非常低,它也会重现错误:

>>> from scipy import sparse
>>> from scipy import sparse
>>> sparse.rand(300000,300000,.000000000001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../python3.8/site-packages/scipy/sparse/construct.py", line 842, in rand
 return random(m, n, density, format, dtype, random_state)
  File ".../lib/python3.8/site-packages/scipy/sparse/construct.py", line 788, in random
 ind = random_state.choice(mn, size=k, replace=False)
  File "mtrand.pyx", line 980, in numpy.random.mtrand.RandomState.choice
  File "mtrand.pyx", line 4528, in numpy.random.mtrand.RandomState.permutation
MemoryError: Unable to allocate 671. GiB for an array with shape (90000000000,) and data type int64

有什么更省内存的方法来创建这样的稀疏矩阵?

推荐答案

只生成您需要的内容。

from scipy import sparse
import numpy as np

n, m = 300000, 300000
density = 0.00000001
size = int(n * m * density)

rows = np.random.randint(0, n, size=size)
cols = np.random.randint(0, m, size=size)
data = np.random.rand(size)

arr = sparse.csr_matrix((data, (rows, cols)), shape=(n, m))

这使您可以构建怪物稀疏数组,前提是它们足够稀疏,可以放入内存中。

>>> arr
<300000x300000 sparse matrix of type '<class 'numpy.float64'>'
 with 900 stored elements in Compressed Sparse Row format>

这可能就是parse.rand构造函数无论怎么都应该工作的方式。如果任何行、列对发生冲突,它会将数据值相加在一起,这可能适用于我能想到的所有应用程序。

好了关于初始化高维稀疏矩阵的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。