sklearn-数据集划分

一般我们划分数据集都是用sklearn.model_selection里的函数,当然也可以人工划分

一、train_test_split

最常用的是train_test_split()函数,用来随机划分样本数据为训练集和测试集。

优点:

随机客观的划分数据,减少人为因素

使用:

x_train, x_test,  y_train, y_test = train_test_split(data, label, test_size = 0.3, random_state = 7)

参数解释 :

data:待划分样本数据
label:待划分样本数据的标签
test_size:测试数据占样本数据的比例,若整数则是测试数据数量
random_state: 设置随机数种子,保证每次都是同一个随机数。如果为0或者不填,则每次得到数据都不一样。


二、StratifiedShuffleSplit

当我们遇到每类样本不均衡或类别数较多,可以采用StratifiedShuffleSplit(),将数据集的每一类样本的数据等分。
StratifiedShuffleSplit(n_splits=1, test_size=0.2, train_size=0.8, random_state=7)

参数解释:

n_splits: 将训练数据分成train/test对的组数,可根据需要进行设置,默认为10.
test_size: 设置test所占的比例
train_size: 设置train所占的比例
random_state: 设置随机种子

函数描述:

1、将样本随机打乱,然后根据设置参数划分出train/test对

2、产生指定数量的独立的train/test数据集,即划分数据集为n组
3、其创建的每一组划分将保证每组类别比例相同。 即第一组训练数据类别比例为2:1,则后面每组类别都满足这个比例

具体实现:

import numpy as np
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import OneHotEncoder

data = np.load('train_onehot.npy')
xs, ys = np.split(data, (-1,), axis=1)

le =OneHotEncoder()
ys = le.fit_transform(ys).toarray()

sss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, train_size=0.8, random_state=7)

for train_index, test_index in sss.split(xs, ys):
    print('Train',train_index,'test',test_index)
    x_train, x_test = xs[train_index], xs[test_index]
    y_train, y_test = ys[train_index], ys[test_index]
    print(x_train.shape, y_train.shape)
    print(x_test.shape, y_test.shape)

结果:
Train [42052  5207 29735 ... 29149 37525 13731] test [25315  8368     4 ...  5782 38231 23396]
(34470, 85) (34470, 10)
(8618, 85) (8618, 10)

 
 

 
 

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/80468011