簡體   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