【问题标题】:Python: Convert Sparse Matrix to Array using a For loopPython:使用 For 循环将稀疏矩阵转换为数组
【发布时间】:2021-12-07 22:33:54
【问题描述】:

使用熊猫=1.1.5。我使用 Bag to Word 创建了一个非常大的稀疏矩阵。我想将稀疏矩阵转换为数组。但我得到
MemoryError: Unable to allocate 36.6 GiB for an array with shape (17799, 275656) and data type int64

我没有管理员权限来增加高级系统设置中的内存。所以我想使用 FOR 循环将稀疏矩阵转换为数组。或者,还有更好的方法?请协助。谢谢

vector1 = CountVectorizer(ngram_range=(1,2))  
vector1.fit_transform(text).toarray()

备用矩阵
(0, 81346) 1
(0, 89381) 1
(0, 120631) 1
(0, 69446) 1
(0, 8579) 1
(0, 8531) 1
.
.
.
(17798, 72613) 1
(17798, 116023) 1
(17798, 25859) 1
(17798, 206370) 1
(17798, 153517) 1
(17798, 26090) 1

【问题讨论】:

  • 取值范围是多少?您可以将类型转换为使用更少的内存
  • @Tom Ron:如何找到稀疏矩阵的取值范围?
  • vector1.fit_transform(text).shape
  • 一般来说,使用稀疏矩阵的目的是存储大于您能够存储/转换的内存量的数据。考虑一下您尝试使用密集矩阵实现的目标并提出一个问题可能会更好 - 可能有更好的方法可以在不转换为密集矩阵的情况下完成您想要做的事情。
  • @Peter 在我看来,您尝试做的事情并不需要放弃稀疏矩阵结构。如果你真的必须走这条路,我建议你联系你的大学(假设你在一个学校工作)HPC 服务;他们可能已经获得了具有大量内存的可用资源,这比笔记本电脑更适合运行此类代码。

标签: python arrays sparse-matrix


【解决方案1】:

你可以试试:

NUM_SPLIT = 2

arr = vector1.fit_transform(text).astype(np.int8)

# Split sparse matrix into NUM_SPLIT small ones
r = range(0, 1+arr.shape[0], arr.shape[0]//NUM_SPLIT)

lst = [arr[i:j] for i, j in zip(r, r[1:])]

输出:

>>> arr
<4x22 sparse matrix of type '<class 'numpy.int8'>'
    with 39 stored elements in Compressed Sparse Row format>

>>> lst
[<2x22 sparse matrix of type '<class 'numpy.int8'>'
    with 19 stored elements in Compressed Sparse Row format>,
 <2x22 sparse matrix of type '<class 'numpy.int8'>'
    with 20 stored elements in Compressed Sparse Row format>]

【讨论】:

  • 不起作用。我仍然遇到内存错误
  • 报错信息上大小还是36.6 GiB?
  • 我可以将稀疏矩阵的一部分转换为数组吗?如何对稀疏矩阵进行切片?谢谢!
  • MemoryError: 无法为形状为 (17799, 275656) 且数据类型为 int8 的数组分配 4.57 GiB
  • @彼得。您有时间测试建议的解决方案吗?
猜你喜欢
  • 2023-04-10
  • 2018-05-10
  • 2021-11-25
  • 2017-07-02
  • 1970-01-01
  • 2019-09-20
  • 2013-05-28
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多