Python:在2个数据集中拆分数据集

时间:2017-11-06 19:31:03

标签: python python-3.x numpy

鉴于2个数据集,训练和测试,我想将训练数据集分为xtrain和ytrain,并测试xtest和ytest。我有octave的代码

X_tr = D_tr(:, 1:end-1);
y_tr = D_tr(:, end);
X_ts = D_ts(:, 1:end-1);
y_ts = D_ts(:, end);

但无法理解如何将其转换为python

1 个答案:

答案 0 :(得分:0)

使用sklearn.model_selection.train_test_split

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = \
    train_test_split(X, y, test_size=0.33, random_state=42)

演示:如何使用np.split(水平)分割数据集:

In [68]: TR = np.random.randint(10, size=(5,5))

In [69]: TR
Out[69]:
array([[2, 9, 9, 0, 3],
       [5, 5, 6, 0, 3],
       [7, 1, 6, 1, 0],
       [5, 0, 2, 0, 4],
       [2, 5, 9, 4, 2]])

In [70]: X_tr, y_tr = np.split(TR, [-1], axis=1)

In [71]: X_tr
Out[71]:
array([[2, 9, 9, 0],
       [5, 5, 6, 0],
       [7, 1, 6, 1],
       [5, 0, 2, 0],
       [2, 5, 9, 4]])

In [72]: y_tr
Out[72]:
array([[3],
       [3],
       [0],
       [4],
       [2]])

PS将使用相同的技术来分割测试数据集