Skip to main content
 首页 » 编程设计

python之尝试创建 numpy 矩阵时出现内存错误

2024年10月01日7xiaohuochai

text = codecs.open("lith.txt", encoding= 'utf-8') 
text = text.read().lower().replace('"','').replace('?','').replace(',','').replace('!','').replace('.','') 
text = text.split() 
words = sorted(list(set(text))) 
Unigram = np.zeros([len(words)]) 
ind = range(len(words)) 
Lexicon = dict(zip(words,ind)) 
Bigram = np.zeros([len(words),len(words)]) 

我一直在程序这部分的最后一行遇到重大问题。文本文件的长度可能约为 7,000,000 字。目前,字数/长度约为200,000。当我将文本文件剪切到单词长度变为 40,000 左右时,程序可以运行。无论如何要解决这个内存限制?谢谢你的帮助。如果我一直删掉部分文本直到内存错误消失,我在程序后面部分得到的结果似乎真的会受到影响。

for n in range(len(text)-1): 
    Unigram[Lexicon[text[n]]] = Unigram[Lexicon[text[n]]] + 1 
    Bigram[Lexicon[text[n]]][Lexicon[text[n+1]]] = Bigram[Lexicon[text[n]]][Lexicon[text[n+1]]] + 1 
Unigram_sorted = np.argsort(Unigram) 
Unigram_sorted = Unigram_sorted[::-1] 
Unigram_sorted = Unigram_sorted[0:4999] 

请您参考如下方法:

我假设引发异常的行:

Bigram = np.zeros([len(words),len(words)]) 

如果 len(words) 为 200,000,则矩阵的大小为 200,000^2 个整数。假设 int64,这需要 320gb 的内存。

假设大多数条目将保持为零,稀疏矩阵可能会有所帮助。例如,scipy's sparse matrices .在计算联合对的情况下,此代码段可能会有所帮助:

from scipy.sparse.dok import dok_matrix 
 
Bigrams = dok_matrix((len(words), len(words))) 
# Bigrams[i, j] += 1 

关于代码本身,第一部分可能在scikit-learn text vectorizers 有一个相对相似的实现。 .