【问题标题】:Shuffle and split 2 numpy arrays so as to maintain their ordering with respect to each other混洗和拆分 2 个 numpy 数组,以保持它们彼此之间的顺序
【发布时间】:2019-02-27 01:08:47
【问题描述】:

我有 2 个 numpy 数组 X 和 Y,形状 X:[4750, 224, 224, 3] 和 Y:[4750,1]。

X 是训练数据集,Y 是每个条目的正确输出标签。

我想将数据拆分为训练和测试,以验证我的机器学习模型。因此,我想随机拆分它们,以便在对 X 和 Y 应用随机拆分后它们都具有正确的顺序。即,X 的每一行在拆分后正确地具有其相应的标签不变。

我怎样才能达到上述目标?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    我会这样做

    def split(x, y, train_ratio=0.7):
      x_size = x.shape[0]
      train_size = int(x_size * train_ratio)
      test_size = x_size - train_size
      train_indices = np.random.choice(x_size, size=train_size, replace=False)
      mask = np.zeros(x_size, dtype=bool)
      mask[train_indices] = True
      x_train, y_train = x[mask], y[mask]
      x_test, y_test = x[~mask], y[~mask]
      return (x_train, y_train), (x_test, y_test)
    

    我只需(随机)为我的训练集选择所需数量的索引,剩下的将用于测试集。

    然后使用掩码选择训练和测试样本。

    【讨论】:

      【解决方案2】:

      您还可以使用 scikit-learn train_test_split 仅使用 2 行代码来拆分数据:

      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)
      

      【讨论】:

        【解决方案3】:

        sklearn.model_selection.train_test_split是个不错的选择!

        但是要自己制作一个

        import numpy as np
        
        def my_train_test_split(X, Y, train_ratio=0.8):
            """return X_train, Y_train, X_test, Y_test"""
            n = X.shape[0]
            split = int(n * train_ratio)
            index = np.arange(n)
            np.random.shuffle(index)
            return X[index[:split]], Y[index[:split]], X[index[split:]], Y[index[split:]]
        

        【讨论】:

          猜你喜欢
          • 2021-06-26
          • 2020-05-17
          • 2019-04-05
          • 1970-01-01
          • 2017-06-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-27
          相关资源
          最近更新 更多