12

解决TF-IDF特征提取时因toarray()出现的MemoryError问题

 3 years ago
source link: https://jarviswwong.com/solve-tfidf-toarray-memory-error.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在使用tf-idf做特征提取时,为了使用特征向量矩阵做进一步的查询,我很习惯的使用 toarray() 将fit_transform后的结果转换为向量矩阵:

tfidf = TfidfVectorizer().fit_transform(frontpage_index) 
...
matrix = tfidf.toarray()

然后因为数据量大的关系,直接给我报了一个 MemoryError ,内存被撑爆了  ZnYrMfN.gif!mobile

查看 fit_transform官方文档 发现,其返回的是一个sprase matrix(稀疏矩阵),可以节省大量内存空间并提升处理速度。

首先我看了下该稀疏矩阵的数据结构:

(0, 18)       0.424688479366
(0, 6)        0.424688479366
(0, 4)        0.424688479366
(0, 14)       0.239262081323
(0, 17)       0.202366335916
(0, 5)        0.424688479366
(0, 1)        0.424688479366
(1, 17)       0.184426607226
(1, 8)        0.387039944282
(1, 15)       0.387039944282
(1, 0)        0.387039944282
(1, 2)        0.387039944282
(1, 13)       0.387039944282
(1, 7)        0.387039944282
(1, 11)       0.259205161463
(2, 14)       0.313686744222
(2, 17)       0.530628478217

其中 (A, B)   C 代表: (文档索引, 特征词向量索引)  文档A中单词B的tfidf分数

所以我们毋需再将其转化成向量数组, 直接在稀疏矩阵上进行查询操作就行了

比如:

# 稀疏矩阵上操作
score = sprase_matrix[i,j]

# 等同于向量矩阵
score = matrix[i][j]

这样就免去了生成/拷贝向量矩阵的过程,可以在较大数据量的情况下避免出现MemoryError,当然你是大内存壕那当我没说。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK