resample#

sklearn.utils.resample(*arrays, replace=True, n_samples=None, random_state=None, stratify=None, sample_weight=None)[source]#

以一致的方式重新采样数组或稀疏矩阵。

默认策略实现引导程序(bootstrapping)的一个步骤。

参数:
*arrays形状为 (n_samples,) 或 (n_samples, n_outputs) 的数组类序列

可索引数据结构可以是数组、列表、数据框或 scipy 稀疏矩阵,且第一维一致。

replacebool, default=True

实现有放回重采样。当使用非均匀权重进行采样时,必须将其设置为 True:期望具有非常大权重的少数数据点被多次采样,以保留由权重引起的分布。如果为 False,这将实现(切片)随机排列。

n_samplesint, default=None

要生成的样本数量。如果设置为 None,则自动设置为数组的第一维大小。如果 replace 为 False,则不应大于数组的长度。

random_stateint, RandomState instance or None, default=None

确定用于打乱数据的随机数生成器。传递一个 int 值以在多次函数调用中获得可重现的结果。参见 Glossary

stratify{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs), default=None

如果不为 None,则数据以分层方式分割,使用此参数作为类别标签。

sample_weightshape 为 (n_samples,) 的 array-like, default=None

包含与每个样本关联的权重值。值被归一化以使其总和为一,并被解释为采样每个数据点的概率。

在版本 1.7 中新增。

返回:
resampled_arrays形状为 (n_samples,) 或 (n_samples, n_outputs) 的数组类序列

重采样后的集合副本序列。原始数组不受影响。

另请参阅

shuffle

以一致的方式打乱数组或稀疏矩阵。

示例

在同一次运行中可以混合稀疏数组和密集数组

>>> import numpy as np
>>> X = np.array([[1., 0.], [2., 1.], [0., 0.]])
>>> y = np.array([0, 1, 2])

>>> from scipy.sparse import coo_matrix
>>> X_sparse = coo_matrix(X)

>>> from sklearn.utils import resample
>>> X, X_sparse, y = resample(X, X_sparse, y, random_state=0)
>>> X
array([[1., 0.],
       [2., 1.],
       [1., 0.]])

>>> X_sparse
<Compressed Sparse Row sparse matrix of dtype 'float64'
    with 4 stored elements and shape (3, 2)>

>>> X_sparse.toarray()
array([[1., 0.],
       [2., 1.],
       [1., 0.]])

>>> y
array([0, 1, 0])

>>> resample(y, n_samples=2, random_state=0)
array([0, 1])

使用分层的示例

>>> y = [0, 0, 1, 1, 1, 1, 1, 1, 1]
>>> resample(y, n_samples=5, replace=False, stratify=y,
...          random_state=0)
[1, 1, 1, 0, 1]