【问题标题】:Split dataset without using Scikit-Learn train_test_split拆分数据集而不使用 Scikit-Learn train_test_split
【发布时间】:2021-05-10 17:25:27
【问题描述】:

我想在不使用 sklearn 库的情况下拆分我的数据集。以下是我使用过的方法。

我当前的代码:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234)

我尝试了什么:

def non_shuffling_train_test_split(X, y, test_size=0.2):
    i = int((1 - test_size) * X.shape[0]) + 1
    X_train, X_test = np.split(X, [i])
    y_train, y_test = np.split(y, [i])
    return X_train, X_test, y_train, y_test

但是,上面的代码不是随机的。

【问题讨论】:

  • 什么是 X 和 y?熊猫数据框? numpy 数组?
  • 这是熊猫框架,然后这就是我所做的:data = df.to_numpy() X = data[:, :-1] y = data[:, -1] - 1跨度>

标签: python machine-learning scikit-learn


【解决方案1】:

您可以使用np.random.permutation 创建一个随机顺序,然后使用np.take 创建子集,这应该适用于 numpy 数组和 pd 数据帧:

def tt_split(X, y, test_size=0.2):

    i = int((1 - test_size) * X.shape[0]) 
    o = np.random.permutation(X.shape[0])
    
    X_train, X_test = np.split(np.take(X,o,axis=0), [i])
    y_train, y_test = np.split(np.take(y,o), [i])
    return X_train, X_test, y_train, y_test

在 numpy 数组上测试它:

X = np.random.normal(0,1,(50,10))
y = np.random.normal(0,1,(50,))
X_train, X_test, y_train, y_test = tt_split(X,y)
[X_train.shape,y_train.shape]
[(40, 10), (40,)]

在 pandas 数据框上测试:

X = pd.DataFrame(np.random.normal(0,1,(50,10)))
y = pd.Series(np.random.normal(0,1,50))
X_train, X_test, y_train, y_test = tt_split(X,y)
[X_train.shape,y_train.shape]
[(40, 10), (40,)]

【讨论】:

    猜你喜欢
    • 2015-07-14
    • 2020-01-05
    • 2018-12-10
    • 2016-07-13
    • 2015-02-23
    • 2015-08-23
    • 2020-07-14
    相关资源
    最近更新 更多