Python:使用 For 循环将稀疏矩阵转换为数组
Python: Convert Sparse Matrix to Array using a For loop
使用 pandas=1.1.5。我使用 Bag to Word 创建了一个非常大的稀疏矩阵。我想将稀疏矩阵转换为数组。但是我得到
MemoryError:无法为形状为 (17799, 275656) 且数据类型为 int64
的数组分配 36.6 GiB
我没有在高级系统设置中增加内存的管理员权限。所以我想使用 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
你可以试试:
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>]
使用 pandas=1.1.5。我使用 Bag to Word 创建了一个非常大的稀疏矩阵。我想将稀疏矩阵转换为数组。但是我得到
MemoryError:无法为形状为 (17799, 275656) 且数据类型为 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
你可以试试:
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>]