1、kfold:自己分样本来交叉验证迭代
-
导入模块:from sklearn.model_selection import KFold
-
参数:
KFold(n_splits=3, shuffle=False, random_state=None) ''' n_splits : int, default=3 Number of folds. Must be at least 2. shuffle : boolean, optional Whether to shuffle the data before splitting into batches. random_state : int, RandomState instance or None, optional, default=None If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Used when shuffle == True. '''
n_splits:就是将样本分成多少份。进行k折验证
shuffle:是否在分割成批次之前将数据洗牌。
random_state:如果INT,随机状态是随机数生成器所使用的种子;如果是随机状态实例,随机数是随机数生成器;如果没有,随机数生成器是NP-随机使用的随机状态实例。当洗牌= =真时使用。
-
代码示例
>>> from sklearn.model_selection import KFold >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) >>> y = np.array([1, 2, 3, 4]) >>> kf = KFold(n_splits=2) >>> kf.get_n_splits(X) 2 >>> print(kf) KFold(n_splits=2, random_state=None, shuffle=False) >>> for train_index, test_index in kf.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: [2 3] TEST: [0 1] TRAIN: [0 1] TEST: [2 3]
2、【交叉验证度量】直接交叉验证cross_val_score