zoukankan      html  css  js  c++  java
  • StratifiedShuffleSplit 交叉验证

    python中数据集划分函数StratifiedShuffleSplit的使用

    文章开始先讲下交叉验证,这个概念同样适用于这个划分函数

    1.交叉验证(Cross-validation)
    交叉验证是指在给定的建模样本中,拿出其中的大部分样本进行模型训练,生成模型,留小部分样本用刚建立的模型进行预测,并求这小部分样本的预测误差,记录它们的平方加和。这个过程一直进行,直到所有的样本都被预测了一次而且仅被预测一次,比较每组的预测误差,选取误差最小的那一组作为训练模型。下图所示

    这里写图片描述

    2.StratifiedShuffleSplit函数的使用
    官方文档
    用法:

    from  sklearn.model_selection import StratifiedShuffleSplit
    StratifiedShuffleSplit(n_splits=10,test_size=None,train_size=None, random_state=None)

    2.1 参数说明

    参数 n_splits是将训练数据分成train/test对的组数,可根据需要进行设置,默认为10

    参数test_size和train_size是用来设置train/test对中train和test所占的比例。例如:
    1.提供10个数据num进行训练和测试集划分
    2.设置train_size=0.8 test_size=0.2
    3.train_num=num*train_size=8 test_num=num*test_size=2
    4.即10个数据,进行划分以后8个是训练数据,2个是测试数据

    *:train_num≥2,test_num≥2 ;test_size+train_size可以小于1*

    参数 random_state控制是将样本随机打乱

    2.2 函数作用描述
    1.其产生指定数量的独立的train/test数据集划分数据集划分成n组。
    2.首先将样本随机打乱,然后根据设置参数划分出train/test对。
    3.其创建的每一组划分将保证每组类比比例相同。即第一组训练数据类别比例为2:1,则后面每组类别都满足这个比例

    2.3 具体实现

    from sklearn.model_selection import StratifiedShuffleSplit
    import numpy as np
    X = np.array([[1, 2], [3, 4], [1, 2], [3, 4],
                  [1, 2],[3, 4], [1, 2], [3, 4]])#训练数据集8*2
    y = np.array([0, 0, 1, 1,0,0,1,1])#类别数据集8*1
    
    ss=StratifiedShuffleSplit(n_splits=5,test_size=0.25,train_size=0.75,random_state=0)#分成5组,测试比例为0.25,训练比例是0.75
    
    for train_index, test_index in ss.split(X, y):
       print("TRAIN:", train_index, "TEST:", test_index)#获得索引值
       X_train, X_test = X[train_index], X[test_index]#训练集对应的值
       y_train, y_test = y[train_index], y[test_index]#类别集对应的值
    

    运行结果:
    这里写图片描述

    从结果看出,1.训练集是6个,测试集是2,与设置的所对应;2.五组中每组对应的类别比例相同

    from:https://blog.csdn.net/m0_38061927/article/details/76180541

  • 相关阅读:
    Unity The Method Signature Matching Rule
    Unity The Property Matching Rule
    Unity The Type Matching Rule
    Unity The Custom Attribute Matching Rule
    Unity The Member Name Matching Rule
    Unity No Policies
    Unity The Return Type Matching Rule
    Unity The Parameter Type Matching Rule
    Unity The Namespace Matching Rule
    关于TSQL递归查询的(转)
  • 原文地址:https://www.cnblogs.com/bonelee/p/9091982.html
Copyright © 2011-2022 走看看