Initialize high dimensional sparse matrix(初始化高维稀疏矩阵)
本文介绍了初始化高维稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望使用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构造函数无论如何都应该工作的方式。如果任何行、列对发生冲突,它会将数据值相加在一起,这可能适用于我能想到的所有应用程序。
这篇关于初始化高维稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:初始化高维稀疏矩阵


基础教程推荐
猜你喜欢
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01