Python 如何将数据集拆分为训练集和测试集

Python 如何将数据集拆分为训练集和测试集

在本教程中,我们将学习如何使用Python编程将数据集拆分为训练集和测试集。

介绍

在创建机器学习和深度学习模型时,我们可能会遇到同时使用同一数据集进行训练和评估的情况。在这种情况下,我们可能希望将数据集分成不同的组或集,并将每个集用于一个任务或特定的过程(例如训练)。在这种情况下,我们可以使用训练/测试集。

训练集和测试集的需求

这是一种非常基本且简单的预处理技术。机器学习模型常见的问题之一是过拟合或欠拟合。过拟合是指模型在训练数据上表现很好,但在未见过的样本上无法泛化。这可能是因为模型从数据中学到了噪声。

另一个问题是欠拟合,即模型在训练数据上表现不佳,因此无法很好地泛化。这可能是因为训练数据较少。

为了解决这些问题,最简单的技术之一就是将数据集分成训练集和测试集。训练集用于训练模型或学习模型参数。测试集通常用于评估模型在未见数据集上的性能。

一些术语

训练集

用于训练模型的数据集的一部分。一般来说,这部分数据集可占整个数据集的70%,但用户可以尝试其他百分比,如60%或80%,具体取决于使用情况。这部分数据集用于学习和拟合模型的参数。

测试集

用于评估模型的数据集的一部分。一般来说,这部分数据集可占整个数据集的30%,但用户可以尝试其他百分比,如40%或20%,具体取决于使用情况。

通常,我们将数据集按照70:30或80:20等比例划分为训练集和测试集。

在Python中拆分数据集为训练集和测试集

有三种基本的方法可以实现数据集的拆分:

  • 使用sklearn的train_test_split
  • 使用numpy索引
  • 使用pandas

让我们简要介绍每种方法。

1. 使用sklearn的train_test_split

示例:

import numpy as np
from sklearn.model_selection import train_test_split
x = np.arange(0, 50).reshape(10, 5)
y = np.array([0, 1, 1, 0, 1, 0, 0, 1, 1, 0])
x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.3,
random_state=4)

print("Shape of x_train is ",x_train.shape)
print("Shape of x_test is ",x_test.shape)
print("Shape of y_train is ",y_train.shape)
print("Shape of y_test is ",x_test.shape)

输出

Shape of x_train is (7, 5)
Shape of x_test is (3, 5)
Shape of y_train is (7,)
Shape of y_test is (3, 5)

2. 使用numpy索引

示例

import numpy as np
x = np.random.rand(100, 5)
y = np.random.rand(100,1)
x_train, x_test = x[:80,:], x[80:,:]
y_train, y_test = y[:80,:], y[80:,:]

print("Shape of x_train is ",x_train.shape)
print("Shape of x_test is ",x_test.shape)
print("Shape of y_train is ",y_train.shape)
print("Shape of y_test is ",x_test.shape)

输出

Shape of x_train is (80, 5)
Shape of x_test is (20, 5)
Shape of y_train is (80, 1)
Shape of y_test is (20, 5)

3. 使用pandas的样本

示例

import pandas as pd 
import numpy as np 
data = np.random.randint(10,25,size=(5,3)) 
df = pd.DataFrame(data, columns=['col1','col2','col3']) 
train_df = df.sample(frac=0.8, random_state=100) 
test_df = df[~df.index.isin(train_df.index)] 

print("Dataset shape : {}".format(df.shape)) 
print("Train dataset shape : {}".format(train_df.shape)) 
print("Test dataset shape : {}".format(test_df.shape))

输出

Dataset shape : (5, 3) Train dataset shape : (4, 3) Test dataset shape : (1, 3)

结论

在Python和机器学习任务中,训练测试拆分是非常重要的预处理步骤。它有助于防止过拟合和欠拟合的问题。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程