Skip to main content
 首页 » 编程设计

np.loadtxt 和 iter_loadtxt 中的 Python MemoryError 或 ValueError

2025年05月04日7jiqing9006

我的出发点是 NumPy 的函数 loadtxt 有问题:

X = np.loadtxt(filename, delimiter=",") 

在 np.loadtxt(..) 中给出了一个 MemoryError。我用谷歌搜索并找到了this question on StackOverflow .这给出了以下解决方案:

def iter_loadtxt(filename, delimiter=',', skiprows=0, dtype=float): 
    def iter_func(): 
        with open(filename, 'r') as infile: 
            for _ in range(skiprows): 
                next(infile) 
            for line in infile: 
                line = line.rstrip().split(delimiter) 
                for item in line: 
                    yield dtype(item) 
        iter_loadtxt.rowlength = len(line) 
 
    data = np.fromiter(iter_func(), dtype=dtype) 
    data = data.reshape((-1, iter_loadtxt.rowlength)) 
    return data 
 
data = iter_loadtxt('your_file.ext') 

所以我试过了,但是遇到了以下错误信息:

> data = data.reshape((-1, iter_loadtext.rowlength)) 
> ValueError: total size of new array must be unchanged 

然后我尝试使用下面的代码片段将行数和最大列数添加到代码中,我部分得到了 from another question我自己也写了一部分:

num_rows = 0 
max_cols = 0 
with open(filename, 'r') as infile: 
    for line in infile: 
        num_rows += 1 
        tmp = line.split(",") 
        if len(tmp) > max_cols: 
            max_cols = len(tmp) 
 
def iter_func(): 
    #didn't change 
 
data = np.fromiter(iter_func(), dtype=dtype, count=num_rows) 
data = data.reshape((num_rows, max_cols)) 

但这仍然给出了相同的错误信息,虽然我认为它应该已经解决了。另一方面,我不确定我是否以正确的方式调用 data.reshape(..)。

我评论了调用 date.reshape(..) 的规则以查看发生了什么。这给出了这个错误信息:

> ValueError: need more than 1 value to unpack 

这发生在用 X 完成某些事情的第一点,这个问题就是关于这个变量的。

我知道这段代码可以处理我得到的输入文件,因为我看到它与它们一起使用。但是我找不到为什么我不能解决这个问题。我的推理之所以如此,是因为我使用的是 32 位 Python 版本(在 64 位 Windows 机器上),内存出现问题,而在其他计算机上不会发生。但我不确定。有关信息:我有 8GB 的​​ RAM 用于 1.2GB 的文件,但根据任务管理器,我的 RAM 未满。

我想解决的是,我正在使用需要读取和解析给定文件的开源代码,就像 np.loadtxt(filename, delimiter=",") 一样,但是随后在我的内存中。我知道代码最初适用于 MacOsx 和 Linux,更准确地说:“MacOsx 10.9.2 和 Linux(版本 2.6.18-194.26.1.el5 (brewbuilder@norob.fnal.gov)(gcc 版本 4.1.2 20080704(Red Hat 4.1.2-48))1 SMP 2010 年 11 月 9 日星期二 12:46:16 EST)。”

我不太在乎时间。我的文件包含 +-200.000 行,其中每行有 100 或 1000 个(取决于输入文件:一个总是 100,一个总是 1000)个项目,其中一个项目是一个 float ,有 3 位小数,取反或不取反,它们由 、 和一个空格分隔。 F.e.:[..] 0.194、-0.007、0.004、0.243、[..],以及您看到 4 的那些项目中的 100 或 100 个,用于 +-200.000 行。

我正在使用 Python 2.7,因为开源代码需要它。

你们有解决这个问题的方法吗?提前致谢。

请您参考如下方法:

在 Windows 上,32 位进程最多只能获得 2GB(或 GiB?)内存,而 numpy.loadtxt 因占用大量内存而臭名昭著,因此这解释了为什么第一种方法没有不工作。

您似乎面临的第二个问题是您正在测试的特定文件缺少数据,即并非所有行都具有相同数量的值。这很容易检查,例如:

import numpy as np 
 
numbers_per_line = [] 
with open(filename) as infile: 
    for line in infile: 
        numbers_per_line.append(line.count(delimiter) + 1) 
 
# Check where there might be problems 
numbers_per_line = np.array(numbers_per_line) 
expected_number = 100 
print np.where(numbers_per_line != expected_number)