MemoryError:无法为形状为287318,3704243和数据类型float64的数组分配7.74 TiB

问题描述

我正在研究形状为{2871,3704243)的矩阵tfidf_matrix,我正尝试将其重用于以后的计算。这是我的完整代码

tfidf_vectorizer = TfidfVectorizer()                                    
# text shape is (287318,)
tfidf_matrix  = tfidf_vectorizer.fit_transform(text)
X = tfidf_matrix.todense()  # error here

pca_num_components = 2
reduced_data = PCA(n_components=pca_num_components).fit_transform(X)

我正试图通过PCA减少tfidf_matrix来进行绘图,但是在行X = tfidf_matrix.todense()上出现内存错误问题

MemoryError: Unable to allocate 7.74 TiB for an array with shape (287318,3704243) and data type float64

请问有什么办法解决这个问题?

解决方法

一种可能的解决方案(尽管并不完美)是随机选择特定数量的行,并按以下步骤对其执行PCA。

max_items = np.random.choice(range(tfidf_matrix.shape[0]),size=3000,replace=False)
X=tfidf_matrix[max_items,:].todense()   
pca = PCA(n_components=2).fit_transform(X)

如果需要,我们可以更改size参数

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...