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

时间:2020-02-23 14:41:53  来源:igfitidea点击:

在机器学习领域,通常将数据集分为两个不同的集合。
这些集是训练集和测试集。
最好将培训和测试数据分开。

为什么要拆分数据集?

如果我们不将数据集划分为训练集和测试集,那么最终我们将在相同数据上测试和训练模型。
当我们在训练模型的相同数据上进行测试时,我们倾向于获得良好的准确性。

但是,这并不意味着该模型在看不见的数据上会表现良好。
这被称为机器学习领域的过拟合。

当模型过于精确地表示训练数据集时,就是过度拟合的情况。
这意味着您的模型过于紧密。

训练模型时,过度拟合是一种不良现象。
拟合不足也是如此。

欠拟合是指模型甚至无法表示训练数据集中的数据点。

如何使用sklearn分割数据集?

让我们看看如何使用sklearn将数据集拆分为训练集和测试集。
我们将逐步介绍该过程。

1.导入数据集

首先,将数据集导入Python笔记本。
在本教程中,我们将使用泰坦尼克号数据集作为示例数据集。
您可以从Python的seaborn库中导入titanic数据集。

import seaborn as sns
titanic = sns.load_dataset('titanic')
titanic.head()

泰坦尼克号数据集

2.从数据集中形成输入和输出向量

在继续将数据集分为训练和测试集之前,我们需要从数据集中准备输入和输出向量。

让我们将"幸存"列作为输出。
这意味着将对该模型进行训练,以预测一个幸存的人是否会幸存。

y = titanic.survived
print(y)

输出:

输出

我们还需要从数据集中删除"生存"列以获取输入向量。

x=titanic.drop('survived',axis=1)
x.head()

输出:

输入项

3.确定分配比例

分割比例代表数据的哪一部分将进入训练集,数据的哪一部分将进入测试集。
训练集几乎总是大于测试集。

数据科学家最常用的拆分比率是80:20。

80:20的拆分比例意味着80%的数据将进入训练集,而20%的数据集将进入测试集。

4.执行分割

为了分割数据,我们将使用sklearn库中的train_test_split。

train_test_split根据提供的比率将您的数据随机分配到训练和测试集中。

我们将使用80:20作为分配比例。

我们首先需要从sklearn导入train_test_split。

from sklearn.model_selection import train_test_split

要执行分割使用:

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)

我们提到的测试大小为0.2,这意味着训练大小为0.8,这给我们提供了理想的比率。

5.通过打印训练和测试矢量的形状进行验证

为了验证分割,让我们打印出不同矢量的形状。

print("shape of original dataset :", titanic.shape)
print("shape of input - training set", x_train.shape)
print("shape of output - training set", y_train.shape)
print("shape of input - testing set", x_test.shape)
print("shape of output - testing set", y_test.shape)

输出:

shape of original dataset : (891, 15)
shape of input - training set (712, 14)
shape of output - training set (712,)
shape of input - testing set (179, 14)
shape of output - testing set (179,)

完整的代码

本教程的完整代码如下:

import seaborn as sns
from sklearn.model_selection import train_test_split

#import dataset
titanic = sns.load_dataset('titanic')

#output vector
y = titanic.survived

#input vector
x=titanic.drop('survived',axis=1)

#split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)

#verify
print("shape of original dataset :", titanic.shape)
print("shape of input - training set", x_train.shape)
print("shape of output - training set", y_train.shape)
print("shape of input - testing set", x_test.shape)
print("shape of output - testing set", y_test.shape)