• 【机器学习】python借助pandas及scikit-learn使用三种方法分割训练集及测试集


    分割方法可以分为分层抽样及随机抽样:
    1.以下3种方法采取的是纯随机抽样的方法做划分。如果数据集足够庞大(特别是相较于属性的数量而言),这种方式通常不错。

    首先加载原始数据:

    import pandas as pd
    
    def load_housing_data(housing_path=HOUSING_PATH):
        csv_path = os.path.join(housing_path, "housing.csv")
        return pd.read_csv(csv_path)
    housing=load_housing_data()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1.使用纯概率法分割,缺点是新增训练数据后要重新分割:

    import numpy as np
    
    # For illustration only. Sklearn has train_test_split()
    def split_train_test(data, test_ratio):
        #生成一个随机排列序列
        shuffled_indices = np.random.permutation(len(data))
        test_set_size = int(len(data) * test_ratio)
        test_indices = shuffled_indices[:test_set_size]
        train_indices = shuffled_indices[test_set_size:]
        #返回行列数据,这里只有行
        return data.iloc[train_indices], data.iloc[test_indices]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    train_set, test_set = split_train_test(housing, 0.2)
    len(train_set)

    2.使用某一列哈希值做分割:

    from zlib import crc32
    
    def test_set_check(identifier, test_ratio):
        return crc32(np.int64(identifier)) & 0xffffffff < test_ratio * 2**32
    
    def split_train_test_by_id(data, test_ratio, id_column):
        ids = data[id_column]
        in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio))
        return data.loc[~in_test_set], data.loc[in_test_set]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    #根据新的列值判断是否进入测试集:要求新增列具有唯一性,如没有可用索引列代替
    housing_with_id = housing.reset_index()
    train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, “index”)

    3.使用scikit-learn的自带分割函数:
    #使用sklearn自带的方法

    from sklearn.model_selection import train_test_split
    train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
    
    • 1
    • 2

    下面以中等收入列进行分层抽样:
    housing[“median_income”].hist()
    housing[“median_income”].describe()
    在这里插入图片描述
    在这里插入图片描述

    import numpy as np
    #按照阈值箱转成分类号
    housing["income_cat"] = pd.cut(housing["median_income"],
                                   bins=[0., 1.5, 3.0, 4.5, 6., np.inf],
                                   labels=[1, 2, 3, 4, 5])
    #计算不同箱内所含的元素数目
    housing["income_cat"].value_counts()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    from sklearn.model_selection import StratifiedShuffleSplit
    #不仅要进行随机打乱,最后选取的测试集和训练集的时候还要考虑样本类别的比例, 也就是我们说的分层抽样
    split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
    #指定需要分层的列,需要用for打开
    for train_index, test_index in split.split(housing, housing["income_cat"]):
        strat_train_set = housing.loc[train_index]
        strat_test_set = housing.loc[test_index]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    如此便完成了分层抽样。

  • 相关阅读:
    迷宫问题(DFS,BFS)
    速卖通批量注册买家号安全吗?怎么弄?
    C#中ThreadPool线程池的使用总结
    [附源码]计算机毕业设计JAVA学生宿舍管理系统
    Android Studio升级Gradle7.4之后Hilt报错的解决
    2022国自然中标至少1篇1区代表作?没中接下来怎么办?
    6.5 - 万维网
    Java服务总在半夜挂,背后的真相竟然是...
    网络原理——TCP/IP--数据链路层,DNS
    Gitea+Jenkins+webhooks-多分支触发+备份构建前端资源
  • 原文地址:https://blog.csdn.net/hh1357102/article/details/126296388