簡體   English   中英

Python:如何將數據采樣到Test and Train數據集中?

[英]Python: How to sample data into Test and Train datasets?

我一直在使用CSV數據來實現我的腳本,並希望將數據采樣到兩個數據集中:

  1. 測試數據
  2. 訓練數據

我想以85%和15%的分區對數據集進行采樣,並希望輸出兩個CSV文件Test.csv和Train.csv

我希望它在基礎Python中做,並且不想使用任何其他外部模塊,如Numpy,SciPy,Pandas或Scikitlearn。 任何人都可以幫助我按百分比隨機抽樣數據。 此外,我將獲得可能具有隨機觀察數的數據集。 到目前為止,我剛剛閱讀了關於熊貓和各種其他模塊的數據,以百分比為基礎對數據進行采樣,並且沒有針對我的問題找到任何具體的解決方案。

此外,我想在兩個文件中保留CSV的標題。 因為標題會使每一行都可訪問,並可用於進一步分析。

使用random.shuffle創建數據集的隨機排列並根據需要對其進行切片:

import random
random.shuffle(data)
train = data[:int(len(data)*0.85)]
test = data[len(train):]

由於您請求了一個特定的解決方案,將一個可能很大的CSV文件分區為兩個文件用於培訓和測試數據,我還將展示如何使用類似於上述一般方法的方法來完成:

import random

# Count lines
with open('data.csv','r') as csvf:
    linecount = sum(1 for lines in csvf if line.strip() != '')

# Create index sets for training and test data
indices = list(range(linecount))
random.shuffle(indices)
ind_test = set(indices[:int(linecount*0.15)])
del indices

# Partition CSV file
with open('data.csv','r') as csvf, open('train.csv','w') as trainf, open('test.csv','w') as testf:
    i = 0
    for line in csvf:
        if line.strip() != '':
            if i in ind_test:
                testf.write(line.strip() + '\n')
            else:
                trainf.write(line.strip() + '\n')

因此,我假設CSV文件每行包含一個觀察。

這將創建一個准確的85:15分割。 如果不太准確的分區對你來說是好的,那么Peter Wood的解決方案會更有效率。

使用隨機模塊中random函數得到01之間均勻分布的隨機數。

如果> .85寫入訓練數據,否則測試數據。 請參閱如何在python中模擬偏置硬幣的翻轉?

import random

with open(input_file) as data:
    with open(test_output, 'w') as test:
        with open(train_output, 'w') as train:
            header = next(data)
            test.write(header)
            train.write(header)
            for line in data:
                if random.random() > 0.85:
                    train.write(line)
                else:
                    test.write(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM