ML之FE:特征工程中常用的五大数据集划分方法(特殊类型数据分割,如时间序列数据分割法)讲解及其代码

简介: ML之FE:特征工程中常用的五大数据集划分方法(特殊类型数据分割,如时间序列数据分割法)讲解及其代码


目录

特殊类型数据分割

5.1、时间序列数据分割TimeSeriesSplit


 

 

特殊类型数据分割

5.1、时间序列数据分割TimeSeriesSplit

class TimeSeriesSplit Found at: sklearn.model_selection._split

 

class TimeSeriesSplit(_BaseKFold):

    """Time Series cross-validator .. versionadded:: 0.18

    

    Provides train/test indices to split time series data samples that are observed at fixed time intervals, in train/test sets. In each split, test indices must be higher than before, and thus shuffling in cross validator is inappropriate. This cross-validation object is a variation of :class:`KFold`.  In the kth split, it returns first k folds as train set and the (k+1)th fold as test set.

    Note that unlike standard cross-validation methods, successive training sets are supersets of those that come before them.

    Read more in the :ref:`User Guide <cross_validation>`.

    

    Parameters

    ----------

    n_splits : int, default=5. Number of splits. Must be at least 2. .. versionchanged:: 0.22 . ``n_splits`` default value changed from 3 to 5.

    max_train_size : int, default=None. Maximum size for a single training set.

 

 

 

 

 

 

提供训练/测试索引,以分割时间序列数据样本,在训练/测试集中,在固定的时间间隔观察。在每次分割中,测试索引必须比以前更高,因此在交叉验证器中变换是不合适的。这个交叉验证对象是KFold 的变体。在第k次分割中,它返回第k次折叠作为序列集,返回第(k+1)次折叠作为测试集。

注意,与标准的交叉验证方法不同,连续训练集是之前那些训练集的超集。

更多信息请参见:ref: ' User Guide <cross_validation> '。</cross_validation>

 

参数

----------

n_splits :int,默认=5。数量的分裂。必须至少是2. ..versionchanged:: 0.22。' ' n_split ' ' '默认值从3更改为5。

max_train_size : int,默认None。单个训练集的最大容量。

    Examples

    --------

    >>> import numpy as np

    >>> from sklearn.model_selection import TimeSeriesSplit

    >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])

    >>> y = np.array([1, 2, 3, 4, 5, 6])

    >>> tscv = TimeSeriesSplit()

    >>> print(tscv)

    TimeSeriesSplit(max_train_size=None, n_splits=5)

    >>> for train_index, test_index in tscv.split(X):

    ...     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]

    TRAIN: [0] TEST: [1]

    TRAIN: [0 1] TEST: [2]

    TRAIN: [0 1 2] TEST: [3]

    TRAIN: [0 1 2 3] TEST: [4]

    TRAIN: [0 1 2 3 4] TEST: [5]

    

    Notes

    -----

    The training set has size ``i * n_samples // (n_splits + 1) + n_samples % (n_splits + 1)`` in the ``i``th split, with a test set of size ``n_samples//(n_splits + 1)``, where ``n_samples`` is the number of samples.

 

    """

    @_deprecate_positional_args

    def __init__(self, n_splits=5, *, max_train_size=None):

        super().__init__(n_splits, shuffle=False, random_state=None)

        self.max_train_size = max_train_size

    

    def split(self, X, y=None, groups=None):

        """Generate indices to split data into training and test set.

 

        Parameters

        ----------

        X : array-like of shape (n_samples, n_features). Training data, where n_samples is the number of samples and n_features is the number of features.

 

        y : array-like of shape (n_samples,). Always ignored, exists for compatibility.

 

        groups : array-like of shape (n_samples,). Always ignored, exists for compatibility.

 

        Yields

        ------

        train : ndarray. The training set indices for that split.

 

        test : ndarray. The testing set indices for that split.

        """

        X, y, groups = indexable(X, y, groups)

        n_samples = _num_samples(X)

        n_splits = self.n_splits

        n_folds = n_splits + 1

        if n_folds > n_samples:

            raise ValueError(

                ("Cannot have number of folds ={0} greater than the number of samples: {1}."). format(n_folds, n_samples))

        indices = np.arange(n_samples)

        test_size = n_samples // n_folds

        test_starts = range(test_size + n_samples % n_folds, n_samples,

         test_size)

        for test_start in test_starts:

            if self.max_train_size and self.max_train_size < test_start:

                yield indices[test_start - self.max_train_size:test_start], indices

                 [test_start:test_start + test_size]

            else:

                yield indices[:test_start], indices[test_start:test_start + test_size]

 

    Examples

    --------

    >>> import numpy as np

    >>> from sklearn.model_selection import TimeSeriesSplit

    >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])

    >>> y = np.array([1, 2, 3, 4, 5, 6])

    >>> tscv = TimeSeriesSplit()

    >>> print(tscv)

    TimeSeriesSplit(max_train_size=None, n_splits=5)

    >>> for train_index, test_index in tscv.split(X):

    ...     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]

    TRAIN: [0] TEST: [1]

    TRAIN: [0 1] TEST: [2]

    TRAIN: [0 1 2] TEST: [3]

    TRAIN: [0 1 2 3] TEST: [4]

    TRAIN: [0 1 2 3 4] TEST: [5]

    

    Notes

    -----

    The training set has size ``i * n_samples // (n_splits + 1) + n_samples % (n_splits + 1)`` in the ``i``th split, with a test set of size ``n_samples//(n_splits + 1)``, where ``n_samples`` is the number of samples.

 

    """

    @_deprecate_positional_args

    def __init__(self, n_splits=5, *, max_train_size=None):

        super().__init__(n_splits, shuffle=False, random_state=None)

        self.max_train_size = max_train_size

    

    def split(self, X, y=None, groups=None):

        """Generate indices to split data into training and test set.

 

        Parameters

        ----------

        X : array-like of shape (n_samples, n_features). Training data, where n_samples is the number of samples and n_features is the number of features.

 

        y : array-like of shape (n_samples,). Always ignored, exists for compatibility.

 

        groups : array-like of shape (n_samples,). Always ignored, exists for compatibility.

 

        Yields

        ------

        train : ndarray. The training set indices for that split.

 

        test : ndarray. The testing set indices for that split.

        """

        X, y, groups = indexable(X, y, groups)

        n_samples = _num_samples(X)

        n_splits = self.n_splits

        n_folds = n_splits + 1

        if n_folds > n_samples:

            raise ValueError(

                ("Cannot have number of folds ={0} greater than the number of samples: {1}."). format(n_folds, n_samples))

        indices = np.arange(n_samples)

        test_size = n_samples // n_folds

        test_starts = range(test_size + n_samples % n_folds, n_samples,

         test_size)

        for test_start in test_starts:

            if self.max_train_size and self.max_train_size < test_start:

                yield indices[test_start - self.max_train_size:test_start], indices

                 [test_start:test_start + test_size]

            else:

                yield indices[:test_start], indices[test_start:test_start + test_size]

 


相关实践学习
基于MaxCompute的热门话题分析
Apsara Clouder大数据专项技能认证配套课程:基于MaxCompute的热门话题分析
相关文章
|
Java 调度 开发者
JDK 21中的虚拟线程:轻量级并发的新篇章
本文深入探讨了JDK 21中引入的虚拟线程(Virtual Threads)概念,分析了其背后的设计哲学,以及与传统线程模型的区别。文章还将讨论虚拟线程如何简化并发编程,提高资源利用率,并展示了一些使用虚拟线程进行开发的示例。
1983 4
|
小程序 Java 关系型数据库
基于微信小程序的智慧养老服务系统
本系统基于Java、MySQL和Spring Boot技术,构建高效、安全的养老院管理系统,提升信息处理速度与管理规范性,实现数据自动化备份与网络化管理,助力养老机构信息化升级。
|
7月前
|
人工智能 弹性计算 数据库
阿里云首购特惠活动解析:新用户可参与轻量应用服务器抢购,老用户同享特惠云服务器
2026年阿里云新老用户首购特惠活动解析:新用户可享轻量应用服务器抢购价,2核2G/200M/40G ESSD仅38元/年,2核4G配置9.9元/月起,支持OpenClaw镜像一键部署AI助理。老用户同享99计划长效特惠:e实例99元/年、u1实例199元/年,新购续费同价至2027年3月。此外,u2i实例享3折、九代实例6.4折等首购优惠。
|
9月前
|
自然语言处理 数据挖掘 BI
Python 生成 PowerPoint 演示文件图表教程
本文教你用Python(python-pptx库)自动化生成PPT图表:从安装配置、创建柱状图/折线图/饼图/散点图,到读取Excel数据、批量制图、美化样式与排版。告别重复手工操作,提升运营、财务、咨询等岗位的报表效率。(239字)
1323 2
|
机器学习/深度学习 人工智能 监控
AI视频监控技术的核心优势与实践
AI视频监控技术结合了计算机视觉、深度学习和大数据分析,能够实时分析监控画面,识别异常行为和场景变化。其核心在于从“被动记录”转型为“主动识别”,提升监控效率并减少安全隐患。主要应用场景包括泳池管理、健身器械区域、人员密度预警和异常事件检测。系统架构支持多种摄像头设备,采用边缘计算和Docker部署,具备实时性、高准确率和扩展性等优势。未来将优化复杂场景适应性和实时计算负载,进一步提高系统性能。
3924 7
|
监控 算法 5G
uwb定位技术原理
UWB(超宽带)定位技术利用极宽的频带(3.1-10.6GHz)和纳秒级脉冲,通过测量信号飞行时间(ToF)或到达时间差(TDOA)实现高精度(厘米级)定位。其抗干扰性强、穿透力好、低功耗,适用于工业自动化、智能家居、医疗健康和智能安防等领域。UWB技术可有效应对信号遮挡和多径效应等问题,提供稳定可靠的室内定位解决方案。
2459 0
|
安全 Java 编译器
switch语句,到底隐藏了多少坑?
在Java编程中,switch语句以简洁高效著称,但也暗藏陷阱。遗忘`break`会导致意外的“贯穿”执行,须在每个case后添加`break`以终止流程。switch表达式的类型有限制,如float和double不被接受,需转换为整数类型或采用其他策略。遗漏`default`子句可能造成逻辑漏洞,应始终考虑不匹配情况以增强代码健壮性。正确运用这些技巧,能让代码更稳健优雅。
761 2
|
监控 JavaScript Linux
Linux系统之部署Homepage个人导航页
【5月更文挑战第13天】Linux系统之部署Homepage个人导航页
1999 1
|
JavaScript Linux
在Linux系统安装Node.js
在Linux系统安装Node.js

热门文章

最新文章