python - np.mean() 导致内存不足错误

标签 python sql-server numpy out-of-memory scikit-learn

我在 SQL Server 2008 中有一个表,其中有 2800 万行。我只对一列感兴趣,并且想对该列执行一些文本分析。

作为第一步,我将查询限制为返回大约 120 万行(只有 1 列包含文本数据)。

我使用以下代码来向量化并计算每列的平均值,其中每列代表整个词汇表中的一个单词。

vectorizer = TfidfVectorizer(min_df=2, stop_words='english',tokenizer=tokenize)
X_train = vectorizer.fit_transform(trainer)
meanArray = np.mean(X_train.toarray(),axis=0)

遇到 X_train.toarray() 时,我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/Support_Dot_Com/PROD1_Analysis.py", line 69, in <module>
    meanArray = np.mean(X_train.toarray(),axis=0)
  File "C:\Anaconda\lib\site-packages\scipy\sparse\compressed.py", line 790, in toarray
    return self.tocoo(copy=False).toarray(order=order, out=out)
  File "C:\Anaconda\lib\site-packages\scipy\sparse\coo.py", line 239, in toarray
    B = self._process_toarray_args(order, out)
  File "C:\Anaconda\lib\site-packages\scipy\sparse\base.py", line 699, in _process_toarray_args
    return np.zeros(self.shape, dtype=self.dtype, order=order)
MemoryError

我知道 .toarray() 将稀疏矩阵转换为 numpy ndarray,这会占用内存。有没有办法在不使用 .toarray() 的情况下做同样的事情?

最佳答案

正如 Alexandre Iolov 在评论中所建议的,只需在稀疏矩阵上调用 mean 方法即可:

X_train.mean(axis=0)

关于python - np.mean() 导致内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22061791/

相关文章:

python - 将 nan 替换为 NOT KNOWN

sql-server - SQL 维护计划在未配置邮件时发送邮件

sql-server - 设置现有 sql ce 数据库的密码(按代码)

python - sklearn.model_selection.train_test_split 示例中的 "random-state"是什么?

python - 为什么有些字符串方法是在方法括号内用变量调用的,有些是在方法括号外调用的?

Python - 查询倒排索引

python - lxml - 如何获取元素的最小xpath?

sql - SQL Server Management Studio 中的存储过程依赖项

numpy - 自定义 seaborn 联合图中的轴标签

python - 使用 Python 和 Numpy 高效计算阶乘