训练/测试Split Python

时间:2018-12-28 05:45:22

标签: python numpy machine-learning

有250个随机生成的数据点,其获取方式如下:

[X, y] = getDataSet()  # getDataSet() randomly generates 250 data points

X看起来像:

[array([[-2.44141527e-01, 8.39016956e-01],
        [ 1.37468561e+00, 4.97114860e-01],
        [ 3.08071887e-02, -2.03260255e-01],...

y看起来像:

y is array([[0.],
            [0.],
            [0.],...

(它也包含1s)

因此,我正在尝试将[X,y]分为训练和测试集。假设训练集是随机选择的120个随机生成的数据点。这是我生成训练集的方式:

nTrain = 120

maxIndex = len(X)
randomTrainingSamples = np.random.choice(maxIndex, nTrain, replace=False)
trainX = X[randomTrainingSamples, :]  # training samples
trainY = y[randomTrainingSamples, :]  # labels of training samples    nTrain X 1

现在,我似乎无法弄清楚的是如何获取测试集,这是训练集中未包含的其他130个随机生成的数据点:

testX =  # testing samples
testY =  # labels of testing samples nTest x 1

建议深表感谢。谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用sklearn.model_selection.train_test_split

import numpy as np
from sklearn.model_selection import train_test_split

X, y = np.ndarray((250, 2)), np.ndarray((250, 1))

trainX, testX, trainY, testY = train_test_split(X, y, test_size= 130)

trainX.shape
# (120, 2)
testX.shape
# (130, 2)
trainY.shape
# (120, 1)
testY.shape
# (130, 1)

答案 1 :(得分:1)

您可以尝试一下。

randomTestingSamples = [i for i in range(maxIndex) if i not in randomTrainingSamples]
testX =  X[randomTestingSamples, :]  # testing samples
testY =  y[randomTestingSamples, :]  # labels of testing samples nTest x 1

答案 2 :(得分:0)

您可以随机整理索引,并选择前120个作为训练,然后选择130个作为测试

random_index = np.random.shuffle(np.arange(len(X)))
randomTrainingSamples = random_index[:120]
randomTestSamples = random_index[120:250]

trainX = X[randomTrainingSamples, :] 
trainY = y[randomTrainingSamples, :] 

testX = X[randomTestSamples, :]
testY = y[randomTestSamples, :]