读取大的csv文件中带有洗牌行的大块文件,以便用ML进行分类。

问题描述 投票:0回答:1

我最近得到的这个数据集对我的内存来说太大了,我必须用以下方法分块读取它

pd.read_csv('filename.csv', chunksize=1024)

而数据集中的所有标签都是连续的,即所有的0都在一起,还有1,2.每个标签有12000个,所以每个块都有所有的0或1或2。

我遇到的问题是,即使我使用的是 randomizetest_train_split在我的训练数据中,我仍然得到了所有相同的标签,结果,我的模型学习为任何输入输出一个值。我需要知道如何解决这个错误。

EDIT:以下是所要求的代码

data_in_chunks = pd.read_csv(data_file, chunksize=4096)
data = next(iter(data_in_chunks)
X = data.drop(['labels'], axis=1)
Y = data.labels
X_train, X_val, Y_train, Y_val = train_test_split(X, Y, stratify=Y, random_state=0) # train test random state has no effect
for i in iter(data_in_chunks):
    train(i) # this is just simplified i used optim in the actual code

所以,换句话说,4096是最高的。chunksize 我的16G内存可以处理,由于所有标签的顺序性质,我所有的。Y_trainY_test 只有0,或1或2(所有可能的输出)。

请帮忙先谢谢你

python pandas numpy dataframe data-science
1个回答
2
投票

你可以通过随机洗牌磁盘上的.csv来解决标签顺序的问题,这些工具包括 https:/github.comalexandresterashuf。 - 取决于你的操作系统

编辑

只使用pandas和标准库的解决方案可以使用 skiprows 参数。

import pandas as pd
import random, math

def read_shuffled_chunks(filepath: str, chunk_size: int,
                        file_lenght: int, has_header=True):

    header = 0 if has_header else None
    first_data_idx = 1 if has_header else 0
    # create index list
    index_list = list(range(first_data_idx,file_lenght))

    # shuffle the list in place
    random.shuffle(index_list)

    # iterate through the chunks and read them
    n_chunks = ceil(file_lenght/chunk_size)
    for i in range(n_chunks):

        rows_to_keep = index_list[(i*chunk_size):((i+1)*chunk_size - 1)]
        if has_header:
            rows_to_keep += [0] # include the index row
        # get the inverse selection
        rows_to_skip = list(set(index_list) - set(rows_to_keep)) 
        yield pd.read_csv(filepath,skiprows=rows_to_skip, header=header)

请注意,虽然每个数据块中包含的行将从csv中随机抽样,但它们会被pandas以原始顺序读取。如果你是用每个数据块的批次来训练你的模型,你可能要考虑随机化每个子集DataFrame来避免招致同样的问题。

© www.soinside.com 2019 - 2024. All rights reserved.