内存有效的方法将大型numpy数组拆分为列车和测试

use*_*926 9 python arrays scikit-learn

我有一个大的numpy数组,当我运行scikit learn's train_test_split将数组拆分为训练和测试数据时,我总是遇到内存错误.什么是一种更有效的内存分裂方法,以及为什么train_test_split会导致这种情况?

以下代码导致内存错误并导致崩溃

import numpy as np
from sklearn.cross_validation import train_test_split

X = np.random.random((10000,70000))
Y = np.random.random((10000,))
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state=42)
Run Code Online (Sandbox Code Playgroud)

use*_*926 6

我试过的一种方法是将X存储在pandas数据帧和shuffle中

X = X.reindex(np.random.permutation(X.index))
Run Code Online (Sandbox Code Playgroud)

因为我尝试时遇到了相同的内存错误

np.random.shuffle(X)
Run Code Online (Sandbox Code Playgroud)

然后,我将pandas数据帧转换回numpy数组并使用此函数,我可以获得一个火车测试分割

#test_proportion of 3 means 1/3 so 33% test and 67% train
def shuffle(matrix, target, test_proportion):
    ratio = int(matrix.shape[0]/test_proportion) #should be int
    X_train = matrix[ratio:,:]
    X_test =  matrix[:ratio,:]
    Y_train = target[ratio:,:]
    Y_test =  target[:ratio,:]
    return X_train, X_test, Y_train, Y_test

X_train, X_test, Y_train, Y_test = shuffle(X, Y, 3)
Run Code Online (Sandbox Code Playgroud)

这个现在适用,当我想进行k-fold交叉验证时,我可以迭代循环k次并随机播放pandas数据帧.虽然现在已经足够了,为什么numpy和sci-kit学习shuffle和train_test_split的实现会导致大数组的内存错误?


sis*_*sem 6

使用 sklearn 拆分方法并减少内存使用的另一种方法是生成 X 的索引向量并在该向量上拆分。之后您可以选择您的条目,例如将训练和测试分割写入磁盘。

import h5py
import numpy as np
from sklearn.cross_validation import train_test_split

X = np.random.random((10000,70000))
Y = np.random.random((10000,))

x_ids = list(range(len(X)))
x_train_ids, x_test_ids, Y_train, Y_test = train_test_split(x_ids, Y, test_size = 0.33, random_state=42)

# Write

f = h5py.File('dataset/train.h5py', 'w')
f.create_dataset(f"inputs", data=X[x_train_ids], dtype=np.int)
f.create_dataset(f"labels", data=Y_train, dtype=np.int)
f.close()

f = h5py.File('dataset/test.h5py', 'w')
f.create_dataset(f"inputs", data=X[x_test_ids], dtype=np.int)
f.create_dataset(f"labels", data=Y_test, dtype=np.int)
f.close()

# Read

f = h5py.File('dataset/train.h5py', 'r')
X_train = np.array(f.get('inputs'), dtype=np.int)
Y_train = np.array(f.get('labels'), dtype=np.int)
f.close()

f = h5py.File('dataset/test.h5py', 'r')
X_test = np.array(f.get('inputs'), dtype=np.int)
Y_test = np.array(f.get('labels'), dtype=np.int)
f.close()
Run Code Online (Sandbox Code Playgroud)


tab*_*ata 5

我遇到了类似的问题。

正如@user1879926 所提到的,我认为 shuffle 是内存耗尽的主要原因。

并且,由于'Shuffle' 被认为是引用的 model_selection.train_test_split的无效参数,sklearn 0.19 中的 train_test_split具有禁用随机播放的选项。

所以,我认为你可以通过添加 shuffle=False 选项来避免内存错误。