sklearn.utils.resample?

sklearn.utils.resample(*arrays, **options)

源碼

以一致的方式重新采樣數組或稀疏矩陣

默認策略實現引導過程的一個步驟

參數 說明
*arrays sequence of indexable data-structures
可索引的數據結構可以是數組,列表,數據框或具有一致的第一維的稀疏稀疏矩陣。
返回值 說明
resampled_arrays sequence of indexable data-structures
集合的重新采樣序列。 原始陣列不受影響。
其他參數 說明
replace boolean, True by default
實現替換的重采樣。 如果為False,則將實現(切片)隨機排列。
n_samples int, None by default
要生成的樣本數。 如果為“無”,則會自動設置為數組的第一維。 如果replace為False,則它不應大于數組的長度。
random_state int, RandomState instance or None, optional (default=None)
確定用于對數據進行混排的隨機數生成。 在多個函數調用中傳遞可重復的結果。 請參閱詞匯表
stratify array-like or None (default=None)
如果不為None,則以分層的方式分割數據,并將其用作類標簽。

另見:

sklearn.utils.shuffle

示例:

可以在同一運行中混合使用稀疏數組和密集數組:

>>> X = np.array([[1.0.], [2.1.], [0.0.]])
>>> y = np.array([012])

>>> 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
<3x2 sparse matrix of type '<... 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>

>>> X_sparse.toarray()
array([[1.0.],
       [2.1.],
       [1.0.]])

>>> y
array([010])

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

使用分層的例子:

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