如何使用 Pandas 从一个数据框创建测试和训练样本?

2025-02-18 09:24:00
admin
原创
35
摘要:问题描述:我有一个相当大的数据框形式的数据集,我想知道如何将数据框分成两个随机样本(80%和20%)进行训练和测试。谢谢!解决方案 1:Scikit Learntrain_test_split是一款不错的工具。它将拆分 numpy 数组和数据框。from sklearn.model_selection imp...

问题描述:

我有一个相当大的数据框形式的数据集,我想知道如何将数据框分成两个随机样本(80%和20%)进行训练和测试。

谢谢!


解决方案 1:

Scikit Learntrain_test_split是一款不错的工具。它将拆分 numpy 数组和数据框。

from sklearn.model_selection import train_test_split

train, test = train_test_split(df, test_size=0.2)

解决方案 2:

我只会使用 numpy 的randn

In [11]: df = pd.DataFrame(np.random.randn(100, 2))

In [12]: msk = np.random.rand(len(df)) < 0.8

In [13]: train = df[msk]

In [14]: test = df[~msk]

只是为了看看这个是否有效:

In [15]: len(test)
Out[15]: 21

In [16]: len(train)
Out[16]: 79

解决方案 3:

Pandas 随机样本也有效

train=df.sample(frac=0.8,random_state=200)
test=df.drop(train.index)

对于相同的random_state值,您将始终在训练和测试集中获得完全相同的数据。这带来了一定程度的可重复性,同时也随机分离了训练和测试数据。

解决方案 4:

我将使用 scikit-learn 自己的 training_test_split,并从索引中生成它

from sklearn.model_selection import train_test_split


y = df.pop('output')
X = df

X_train,X_test,y_train,y_test = train_test_split(X.index,y,test_size=0.2)
X.iloc[X_train] # return dataframe train

解决方案 5:

无需转换为 numpy。只需使用 pandas df 进行拆分,它就会返回 pandas df。

from sklearn.model_selection import train_test_split

train, test = train_test_split(df, test_size=0.2)

如果你想把 x 从 y 中分离出来

X_train, X_test, y_train, y_test = train_test_split(df[list_of_x_cols], df[y_col],test_size=0.2)

如果你想分割整个 df

X, y = df[list_of_x_cols], df[y_col]

解决方案 6:

有很多方法可以创建训练/测试甚至验证样本。

情况 1:train_test_split没有任何选项的经典方式:

from sklearn.model_selection import train_test_split
train, test = train_test_split(df, test_size=0.3)

情况 2:数据集非常小(<500 行):为了通过交叉验证获得所有行的结果。最后,您将对可用训练集的每一行都有一个预测。

from sklearn.model_selection import KFold
kf = KFold(n_splits=10, random_state=0)
y_hat_all = []
for train_index, test_index in kf.split(X, y):
    reg = RandomForestRegressor(n_estimators=50, random_state=0)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf = reg.fit(X_train, y_train)
    y_hat = clf.predict(X_test)
    y_hat_all.append(y_hat)

情况 3a:用于分类的数据集不平衡。根据情况 1,以下是等效解决方案:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.3)

情况 3b:分类目的的数据集不平衡。根据情况 2,以下是等效解决方案:

from sklearn.model_selection import StratifiedKFold
kf = StratifiedKFold(n_splits=10, random_state=0)
y_hat_all = []
for train_index, test_index in kf.split(X, y):
    reg = RandomForestRegressor(n_estimators=50, random_state=0)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf = reg.fit(X_train, y_train)
    y_hat = clf.predict(X_test)
    y_hat_all.append(y_hat)

案例 4:您需要在大数据上创建训练/测试/验证集来调整超参数(60%训练,20%测试和 20%验证)。

from sklearn.model_selection import train_test_split
X_train, X_test_val, y_train, y_test_val = train_test_split(X, y, test_size=0.6)
X_test, X_val, y_test, y_val = train_test_split(X_test_val, y_test_val, stratify=y, test_size=0.5)

解决方案 7:

您可以使用以下代码来创建测试和训练样本:

from sklearn.model_selection import train_test_split
trainingSet, testSet = train_test_split(df, test_size=0.2)

测试规模可能因您想要放入测试和训练数据集的数据百分比而异。

解决方案 8:

有很多有效的答案。再添加一个。来自 sklearn.cross_validation 导入 train_test_split

#gets a random 80% of the entire set
X_train = X.sample(frac=0.8, random_state=1)
#gets the left out portion of the dataset
X_test = X.loc[~df_model.index.isin(X_train.index)]

解决方案 9:

您还可以考虑分层划分训练集和测试集。分层划分还会随机生成训练集和测试集,但会保留原始类别比例。这使得训练集和测试集更好地反映原始数据集的属性。

import numpy as np  

def get_train_test_inds(y,train_proportion=0.7):
    '''Generates indices, making random stratified split into training set and testing sets
    with proportions train_proportion and (1-train_proportion) of initial sample.
    y is any iterable indicating classes of each observation in the sample.
    Initial proportions of classes inside training and 
    testing sets are preserved (stratified sampling).
    '''

    y=np.array(y)
    train_inds = np.zeros(len(y),dtype=bool)
    test_inds = np.zeros(len(y),dtype=bool)
    values = np.unique(y)
    for value in values:
        value_inds = np.nonzero(y==value)[0]
        np.random.shuffle(value_inds)
        n = int(train_proportion*len(value_inds))

        train_inds[value_inds[:n]]=True
        test_inds[value_inds[n:]]=True

    return train_inds,test_inds

df[train_inds] 和 df[test_inds] 为您提供原始 DataFrame df 的训练和测试集。

解决方案 10:

您可以使用 ~(波浪号运算符)排除使用 df.sample() 采样的行,让 pandas 单独处理索引的采样和过滤,以获得两个集合。

train_df = df.sample(frac=0.8, random_state=100)
test_df = df[~df.index.isin(train_df.index)]

解决方案 11:

只需从 df 中选择范围行即可

row_count = df.shape[0]
split_point = int(row_count*1/5)
test_data, train_data = df[:split_point], df[split_point:]

解决方案 12:

如果您需要根据数据集中的标签列拆分数据,可以使用以下命令:

def split_to_train_test(df, label_column, train_frac=0.8):
    train_df, test_df = pd.DataFrame(), pd.DataFrame()
    labels = df[label_column].unique()
    for lbl in labels:
        lbl_df = df[df[label_column] == lbl]
        lbl_train_df = lbl_df.sample(frac=train_frac)
        lbl_test_df = lbl_df.drop(lbl_train_df.index)
        print '
%s:
---------
total:%d
train_df:%d
test_df:%d' % (lbl, len(lbl_df), len(lbl_train_df), len(lbl_test_df))
        train_df = train_df.append(lbl_train_df)
        test_df = test_df.append(lbl_test_df)

    return train_df, test_df

并使用它:

train, test = split_to_train_test(data, 'class', 0.7)

如果您想控制分割的随机性或者使用一些全局随机种子,您也可以传递 random_state。

解决方案 13:

要分成两个以上的类(例如训练,测试和验证),可以执行以下操作:

probs = np.random.rand(len(df))
training_mask = probs < 0.7
test_mask = (probs>=0.7) & (probs < 0.85)
validatoin_mask = probs >= 0.85


df_training = df[training_mask]
df_test = df[test_mask]
df_validation = df[validatoin_mask]

这将把大约 70% 的数据用于训练,15% 用于测试,15% 用于验证。

解决方案 14:

shuffle = np.random.permutation(len(df))
test_size = int(len(df) * 0.2)
test_aux = shuffle[:test_size]
train_aux = shuffle[test_size:]
TRAIN_DF =df.iloc[train_aux]
TEST_DF = df.iloc[test_aux]

解决方案 15:

import pandas as pd

from sklearn.model_selection import train_test_split

datafile_name = 'path_to_data_file'

data = pd.read_csv(datafile_name)

target_attribute = data['column_name']

X_train, X_test, y_train, y_test = train_test_split(data, target_attribute, test_size=0.8)

解决方案 16:

这是我在需要拆分 DataFrame 时写的。我考虑过使用上面 Andy 的方法,但我不喜欢无法精确控制数据集的大小(即有时是 79,有时是 81,等等)。

def make_sets(data_df, test_portion):
    import random as rnd

    tot_ix = range(len(data_df))
    test_ix = sort(rnd.sample(tot_ix, int(test_portion * len(data_df))))
    train_ix = list(set(tot_ix) ^ set(test_ix))

    test_df = data_df.ix[test_ix]
    train_df = data_df.ix[train_ix]

    return train_df, test_df


train_df, test_df = make_sets(data_df, 0.2)
test_df.head()

解决方案 17:

上面有很多很好的答案,所以我只想再添加一个例子,以防您想仅使用numpy库来指定训练和测试集的确切样本数量。

# set the random seed for the reproducibility
np.random.seed(17)

# e.g. number of samples for the training set is 1000
n_train = 1000

# shuffle the indexes
shuffled_indexes = np.arange(len(data_df))
np.random.shuffle(shuffled_indexes)

# use 'n_train' samples for training and the rest for testing
train_ids = shuffled_indexes[:n_train]
test_ids = shuffled_indexes[n_train:]

train_data = data_df.iloc[train_ids]
train_labels = labels_df.iloc[train_ids]

test_data = data_df.iloc[test_ids]
test_labels = data_df.iloc[test_ids]

解决方案 18:

如果您想将其拆分为训练、测试和验证集,您可以使用此功能:

from sklearn.model_selection import train_test_split
import pandas as pd

def train_test_val_split(df, test_size=0.15, val_size=0.45):
    temp, test = train_test_split(df, test_size=test_size)
    total_items_count = len(df.index)
    val_length = total_items_count * val_size
    new_val_propotion = val_length / len(temp.index) 
    train, val = train_test_split(temp, test_size=new_val_propotion)
    return train, test, val

解决方案 19:

样本方法选择一部分数据,您可以先通过传递种子值来对数据进行混洗。

train = df.sample(frac=0.8, random_state=42)

对于测试集,您可以通过训练 DF 的索引删除行,然后重置新 DF 的索引。

test = df.drop(train_data.index).reset_index(drop=True)

解决方案 20:

如果您希望输入一个数据框并输出两个数据框(而不是 numpy 数组),那么这应该可以解决问题:

def split_data(df, train_perc = 0.8):

   df['train'] = np.random.rand(len(df)) < train_perc

   train = df[df.train == 1]

   test = df[df.train == 0]

   split_data ={'train': train, 'test': test}

   return split_data

解决方案 21:

我认为如果您想稍后添加列,您还需要获取一份副本而不是数据框的切片。

msk = np.random.rand(len(df)) < 0.8
train, test = df[msk].copy(deep = True), df[~msk].copy(deep = True)

解决方案 22:

您可以使用 df.as_matrix() 函数并创建 Numpy 数组并传递它。

Y = df.pop()
X = df.as_matrix()
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2)
model.fit(x_train, y_train)
model.test(x_test)

解决方案 23:

对我来说更优雅一点的方法是创建一个随机列,然后根据它进行拆分,这样我们就可以得到适合我们需求并且随机的拆分。

def split_df(df, p=[0.8, 0.2]):
import numpy as np
df["rand"]=np.random.choice(len(p), len(df), p=p)
r = [df[df["rand"]==val] for val in df["rand"].unique()]
return r

解决方案 24:

您需要将 pandas 数据框转换为 numpy 数组,然后将 numpy 数组转换回数据框

 import pandas as pd
df=pd.read_csv('/content/drive/My Drive/snippet.csv', sep='    ')
from sklearn.model_selection import train_test_split

train, test = train_test_split(df, test_size=0.2)
train1=pd.DataFrame(train)
test1=pd.DataFrame(test)
train1.to_csv('/content/drive/My Drive/train.csv',sep="    ",header=None, encoding='utf-8', index = False)
test1.to_csv('/content/drive/My Drive/test.csv',sep="    ",header=None, encoding='utf-8', index = False)

解决方案 25:

在我的例子中,我想用特定的数字将数据框拆分为训练、测试和开发。下面我分享我的解决方案

首先,为数据框分配一个唯一的 id(如果不存在)

import uuid
df['id'] = [uuid.uuid4() for i in range(len(df))]

以下是我的拆分数字:

train = 120765
test  = 4134
dev   = 2816

split 函数

def df_split(df, n):
    
    first  = df.sample(n)
    second = df[~df.id.isin(list(first['id']))]
    first.reset_index(drop=True, inplace = True)
    second.reset_index(drop=True, inplace = True)
    return first, second

现在分为训练、测试、开发

train, test = df_split(df, 120765)
test, dev   = df_split(test, 4134)

解决方案 26:

这就是我所做的:

train_dataset = dataset.sample(frac=0.80, random_state=200)
val_dataset = dataset.drop(train_dataset.index).sample(frac=1.00, random_state=200, ignore_index = True).copy()
train_dataset = train_dataset.sample(frac=1.00, random_state=200, ignore_index = True).copy()
del dataset

解决方案 27:

我使用两种方法实现此目的。

方法 1:

from sklearn.model_selection import train_test_split
#Split the dataset into X and y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

方法 2:

from sklearn.model_selection import train_test_split
#Split the dataset into X and y
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, random_state=42)

此外,对于较大的数据帧,请查看英特尔® Modin 分发版(而非 pandas)(https://www.intel.com/content/www/us/en/developer/tools/oneapi/distribution-of-modin.html#gs.1dtwen)和英特尔® Scikit-learn 扩展https://www.intel.com/content/www/us/en/developer/tools/oneapi/scikit-learn.html#gs.1dtvml)。这些框架优化将有助于加速英特尔硬件的性能。

解决方案 28:

这个怎么样?df 是我的数据框

total_size=len(df)

train_size=math.floor(0.66*total_size) (2/3 part of my dataset)

#training dataset
train=df.head(train_size)
#test dataset
test=df.tail(len(df) -train_size)

解决方案 29:

我会使用 K 折交叉验证。事实证明,train_test_split它的效果比以下文章要好得多: https: //scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html

解决方案 30:

将 df 拆分为训练、验证、测试。给定一个增强数据的 df,仅选择依赖列和独立列。将最近行的 10%(使用“日期”列)分配给 test_df。将剩余行的 10% 随机分配给validate_df,其余行分配给 train_df。不要重新索引。检查所有行是否均唯一分配。仅使用原生 python 和 pandas 库。

方法 1:将行分成训练、验证、测试数据框。

train_df = augmented_df[dependent_and_independent_columns]
test_df = train_df.sort_values('dates').tail(int(len(augmented_df)*0.1)) # select latest 10% of dates for test data
train_df = train_df.drop(test_df.index) # drop rows assigned to test_df
validate_df = train_df.sample(frac=0.1) # randomly assign 10%
train_df = train_df.drop(validate_df.index) # drop rows assigned to validate_df
assert len(augmented_df) == len(set(train_df.index).union(validate_df.index).union(test_df.index)) # every row must be uniquely assigned to a df

方法 2:当验证必须是训练的子集时拆分行(fastai)

train_validate_test_df = augmented_df[dependent_and_independent_columns]
test_df = train_validate_test_df.loc[augmented_df.sort_values('dates').tail(int(len(augmented_df)*0.1)).index] # select latest 10% of dates for test data
train_validate_df = train_validate_test_df.drop(test_df.index) # drop rows assigned to test_df
validate_df = train_validate_df.sample(frac=validate_ratio) # assign 10% to validate_df
train_df = train_validate_df.drop(validate_df.index) # drop rows assigned to validate_df
assert len(augmented_df) == len(set(train_df.index).union(validate_df.index).union(test_df.index)) # every row must be uniquely assigned to a df
# fastai example usage
dls = fastai.tabular.all.TabularDataLoaders.from_df(
train_validate_df, valid_idx=train_validate_df.index.get_indexer_for(validate_df.index))
相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1324  
  IPD研发管理体系作为一种先进的研发管理理念和方法,对于打造优质产品体验起着至关重要的作用。它涵盖了从产品规划、研发、上市到生命周期管理的全流程,通过整合资源、优化流程、加强团队协作等方式,确保产品能够精准满足用户需求,提升用户满意度和忠诚度。IPD研发管理体系的核心原则IPD研发管理体系以市场驱动为核心原则。这意味着...
IPD集成产品开发   8  
  IPD(Integrated Product Development)产品开发流程作为一种先进的产品开发管理模式,在众多企业中得到广泛应用。它强调跨部门团队协作、并行工程以及基于市场的产品开发理念,旨在提高产品开发效率、缩短产品上市时间、提升产品质量。而成本控制在产品开发过程中至关重要,关乎企业的利润空间和市场竞争力。...
华为IPD流程   6  
  IPD(Integrated Product Development)产品开发流程作为一种先进的产品开发管理模式,在众多企业中得到了广泛应用。它从多个维度对产品开发过程进行优化和整合,为企业创新提供了强大的支撑。通过实施IPD产品开发流程,企业能够更加高效地将创意转化为具有市场竞争力的产品,从而在激烈的市场竞争中占据优...
华为IPD流程管理   10  
  华为作为全球知名的科技企业,其产品质量在市场上有口皆碑。华为IPD产品开发流程在确保产品质量方面发挥了至关重要的作用。IPD(Integrated Product Development)即集成产品开发,是一套先进的、成熟的产品开发管理思想、模式和方法。它打破了传统产品开发中各部门之间的壁垒,强调跨部门团队协作,从产品...
IPD集成产品开发流程   9  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用