gpt4 book ai didi

Python Numpy - 矩阵内存错误和限制

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:11 30 4
gpt4 key购买 nike

在网上搜索这个主题后,我发现不是我一个人遇到这个问题,但我不明白是否有办法解决这个问题。

我有 5036 个文本文件和一个包含 15985 个单词的单词表。对于在文本文件中找到的单词列表中的每个单词,我想在矩阵中放一个 1。但我收到错误:MemoryError

我也尝试过创建矩阵并进行打印(以防我的 python 代码中出现错误)。我遇到了同样的错误。有什么建议吗?

matrix = np.zeros(shape=(5036,15985))

编辑:那是我的代码,可能有一些错误..它应该以这种方式工作:

  1. 从文件中创建词典(文本文件中的每个词都是命名为“1_word1 2_word2”等,所以拆分文本的每一行文件我将在 split_[0] 矩阵中的位置,在 split_[1]这个词本身)
  2. 对于每个文本文件,它保存文件的编号以便放置矩阵上的正确文档(每个文本文件都被命名为“1_1A_out.txt 2_1A_out.txt 等”)
  3. 最后打印矩阵。

    import os
    import re
    import fileinput
    import numpy as np

    matrix = np.zeros(shape=(6000,16000))

    def dictionary_creation (filepath):
    fileopen = open(filepath, "r")
    dictionary = fileopen.read().split('\n')
    fileopen.close()
    return dictionary


    def find_doc_matrix_position (filename):
    regex = re.compile('(\d)_(.*)')
    find_regex = regex.search(file)
    if find_regex:
    pos_doc = int(find_regex.group(1))-1
    return pos_doc

    def put_nbdoc_nbword_in_matrix (filename, dictionary, nb_file):
    for line in fileinput.input([filename]):
    line = line.replace("\n", "")
    for w in range(0,len(dictionary)-1):
    split_ = dictionary[w].split('_',1)
    if line == split_[1]:
    # print ("nb_file is: "+str(nb_file))
    # print ("nb_word is : "+str(split_[0]))
    # print ("line is: "+line+" word is: "+split_[1])
    # print '####'
    matrix[nb_file,split_[0]] = 1

    dictionary = dictionary_creation('C:\\Users\\KP\\Desktop\\FSC_lemmes_sort.txt')

    for file in os.listdir('C:\Users\KP\Desktop\FSC_Treetag\out'):
    fin = open(file, 'r')
    filename = file
    nb_file = find_doc_matrix_position(file)
    put_nbdoc_nbword_in_matrix(filename, dictionary, nb_file)

    print "this is the final matrix\n"
    print matrix

最佳答案

根据具体错误信息:

File "C:/Users/KP/Desktop/FSC_Treetag/out/f3_test_from_files_to_matrix_fonctions.py", line 6, in matrix = np.zeros(shape=(5037,15999)) MemoryError

您没有足够的内存来分配数组。根据您的系统,您的 matrix 中的每个值将使用大约 8 个字节,因此这个数组应该只出现大约 600 MB 的内存......这真的不多。可能还有其他东西(进程、打开的文件等)正在耗尽您的所有系统内存。

同时,由于您只是在查找文件中是否存在每个单词,因此对于矩阵中的每个文件单词条目,您只需要一个位。在那种情况下,你应该简单地 use a bitarray (即每个条目一个位)。

关于Python Numpy - 矩阵内存错误和限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33614000/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com