LeavePGroupsOut#

class sklearn.model_selection.LeavePGroupsOut(n_groups)[原始碼]#

留 P 個組別的交叉驗證器。

根據第三方提供的組別,提供用於分割資料的訓練/測試索引。此組別資訊可用於將樣本的任意特定領域分層編碼為整數。

例如,組別可以是樣本的收集年份,從而允許針對基於時間的分割進行交叉驗證。

LeavePGroupsOut 和 LeaveOneGroupOut 的區別在於,前者使用分配給 p 個不同組別值的所有樣本來構建測試集,而後者則使用分配給相同組別的所有樣本。

請參閱 使用者指南 以了解更多資訊。

參數:
n_groupsint

在測試分割中要排除的組別數量(p)。

另請參閱

GroupKFold

具有非重疊組別的 K 折疊疊代器變體。

範例

>>> import numpy as np
>>> from sklearn.model_selection import LeavePGroupsOut
>>> X = np.array([[1, 2], [3, 4], [5, 6]])
>>> y = np.array([1, 2, 1])
>>> groups = np.array([1, 2, 3])
>>> lpgo = LeavePGroupsOut(n_groups=2)
>>> lpgo.get_n_splits(X, y, groups)
3
>>> lpgo.get_n_splits(groups=groups)  # 'groups' is always required
3
>>> print(lpgo)
LeavePGroupsOut(n_groups=2)
>>> for i, (train_index, test_index) in enumerate(lpgo.split(X, y, groups)):
...     print(f"Fold {i}:")
...     print(f"  Train: index={train_index}, group={groups[train_index]}")
...     print(f"  Test:  index={test_index}, group={groups[test_index]}")
Fold 0:
  Train: index=[2], group=[3]
  Test:  index=[0 1], group=[1 2]
Fold 1:
  Train: index=[1], group=[2]
  Test:  index=[0 2], group=[1 3]
Fold 2:
  Train: index=[0], group=[1]
  Test:  index=[1 2], group=[2 3]
get_metadata_routing()[原始碼]#

取得此物件的中繼資料路由。

請檢查 使用者指南 以了解路由機制的工作原理。

返回:
routingMetadataRequest

一個封裝路由資訊的 MetadataRequest

get_n_splits(X=None, y=None, groups=None)[原始碼]#

返回交叉驗證器中的分割疊代次數。

參數:
Xobject

始終被忽略,為了相容性而存在。

yobject

始終被忽略,為了相容性而存在。

groupsarray-like of shape (n_samples,)

將資料集分割為訓練/測試集時使用的樣本組別標籤。必須始終指定此「groups」參數來計算分割次數,但可以省略其他參數。

返回:
n_splitsint

返回交叉驗證器中的分割疊代次數。

set_split_request(*, groups: bool | None | str = '$UNCHANGED$') LeavePGroupsOut[原始碼]#

請求傳遞給 split 方法的中繼資料。

請注意,僅當 enable_metadata_routing=True 時,此方法才相關(請參閱 sklearn.set_config)。請參閱 使用者指南 以了解路由機制的工作原理。

每個參數的選項為

  • True:請求中繼資料,如果提供,則傳遞給 split。如果未提供中繼資料,則忽略該請求。

  • False:不請求中繼資料,並且元估計器不會將其傳遞給 split

  • None:不請求中繼資料,如果使用者提供,則元估計器會引發錯誤。

  • str:中繼資料應使用此給定的別名而不是原始名稱傳遞給元估計器。

預設值 (sklearn.utils.metadata_routing.UNCHANGED) 保留現有的請求。這允許您更改某些參數的請求,而不更改其他參數的請求。

在 1.3 版中新增。

注意

僅當此估計器用作元估計器的子估計器時,此方法才相關,例如在 Pipeline 內部使用。否則,它沒有任何效果。

參數:
groupsstr、True、False 或 None,預設值為 sklearn.utils.metadata_routing.UNCHANGED

splitgroups 參數的中繼資料路由。

返回:
selfobject

更新的物件。

split(X, y=None, groups=None)[原始碼]#

產生索引以將資料分割為訓練集和測試集。

參數:
X類陣列 (array-like),形狀為 (n_samples, n_features)

訓練資料,其中 n_samples 是樣本數量,而 n_features 是特徵數量。

y類陣列 (array-like),形狀為 (n_samples,),預設為 None

用於監督式學習問題的目標變數。

groupsarray-like of shape (n_samples,)

將資料集分割為訓練/測試集時,使用的樣本群組標籤。

產生:
trainndarray

該分割的訓練集索引。

testndarray

該分割的測試集索引。