如何使用Sklearn将数据分成3个或更多零件



我想将数据拆分为分层的火车,测试和验证数据集,但是Sklearn仅提供cross_validation.train_testrongplit,它只能分为2件。如果我想这样做

我该怎么办

如果要使用分层的火车/测试拆分,则可以在sklearn

中使用stratifiedkfold

假设X是您的功能,y是您的标签,基于此处的示例:

from sklearn.model_selection import StratifiedKFold
cv_stf = StratifiedKFold(n_splits=3)
for train_index, test_index in skf.split(X, y):
    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]

update :要将数据拆分为3个不同百分比,请使用numpy.split()这样做:

X_train, X_test, X_validate  = np.split(X, [int(.7*len(X)), int(.8*len(X))])
y_train, y_test, y_validate  = np.split(y, [int(.7*len(y)), int(.8*len(y))])

您也可以多次使用train_test_split来实现此目标。第二次,将其运行在训练输出中,从第一个呼叫到train_test_split

from sklearn.model_selection import train_test_split
def train_test_validate_stratified_split(features, targets, test_size=0.2, validate_size=0.1):
    # Get test sets
    features_train, features_test, targets_train, targets_test = train_test_split(
        features,
        targets,
        stratify=targets,
        test_size=test_size
    )
    # Run train_test_split again to get train and validate sets
    post_split_validate_size = validate_size / (1 - test_size)
    features_train, features_validate, targets_train, targets_validate = train_test_split(
        features_train,
        targets_train,
        stratify=targets_train,
        test_size=post_split_validate_size
    )
    return features_train, features_test, features_validate, targets_train, targets_test, targets_validate

相关内容

  • 没有找到相关文章

最新更新