繁体   English   中英

随机分割数据以进行此功能的训练和测试

[英]Randomize the splitting of data for training and testing for this function

我编写了一个函数,根据总大小的百分比将numpy ndarrays x_datay_data分为训练和测试数据。

这是函数:

def split_data_into_training_testing(x_data, y_data, percentage_split):
    number_of_samples = x_data.shape[0]
    p = int(number_of_samples * percentage_split)

    x_train = x_data[0:p]
    y_train = y_data[0:p]

    x_test = x_data[p:]
    y_test = y_data[p:]

    return x_train, y_train, x_test, y_test

在此功能中,数据的顶部将进入根据percentage_split设置的训练数据集,数据样本的底部将进入测试数据集。 在将数据拆分输入机器学习模型之前,如何使其更加随机化?

假设您有理由自己执行此操作而不是使用sklearn.train_test_split ,则可以sklearn.train_test_split索引数组(这使训练数据保持不变)并在其上进行索引。

def split_data_into_training_testing(x_data, y_data, split, shuffle=True):
    idx = np.arange(len(x_data))
    if shuffle:
        np.random.shuffle(idx)

    p = int(len(x_data) * split)
    x_train = x_data[idx[:p]]
    x_test = x_data[idx[p:]]
    ...  # Similarly for y_train and y_test.

    return x_train, x_test, y_train, y_test

您可以创建带有p随机选择的真实元素的蒙版,并以此方式对数组进行索引。 我将通过改组可用索引的数组来创建掩码:

ind = np.arange(number_of_samples)
np.random.shuffle(ind)
ind_train = np.sort(ind[:p])
ind_test = np.sort(ind[p:])
x_train = x_data[ind_train]
y_train = y_data[ind_train]
x_test = x_data[ind_test]
y_test = y_data[ind_test]

仅当原始数据在x中单调增加或减少并且您希望保持这种方式时,才需要对索引进行排序。 否则, ind_train = ind[:p]就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM