我想使用numpy数组来构建折叠交叉验证任务的折叠。取出测试片很容易,但我不知道如何返回数组的其余部分,省略了测试片。有没有一种有效的方法来做到这一点?我可以使用numpy数组生成折叠以进行交叉验证吗?
examples = range(50)
classes = range(50)
data = np.array(zip(classes,examples))
test_slice = data[5:10]
train_on_remainder = ??
我想使用numpy数组来构建折叠交叉验证任务的折叠。取出测试片很容易,但我不知道如何返回数组的其余部分,省略了测试片。有没有一种有效的方法来做到这一点?我可以使用numpy数组生成折叠以进行交叉验证吗?
examples = range(50)
classes = range(50)
data = np.array(zip(classes,examples))
test_slice = data[5:10]
train_on_remainder = ??
你可以设置它就像这样:
test_slice, remainder = np.split(data.copy(), [test_size], axis=0)
# run test
remainder[:test_size], test_slice = test_slice, remainder[:test_size].copy()
# run test
remainder[test_size:2*test_size], test_slice = test_slice, remainder[test_size:2*test_size].copy()
# etc.
我不认为你可以用少得多的复制有它。
工作原理:
. full set: | 0 | 1 | 2 | 3 | 4 | 5 |
split (full copy) /\
tst/rem | 0 | | 1 | 2 | 3 | 4 | 5 |
run trial
| 1 | 2 | 3 | 4 | 5 |
swap tst and ^|
first segment: | v
(partial copy) | 0 |
tst/rem | 1 | | 0 | 2 | 3 | 4 | 5 |
run trial
| 0 | 2 | 3 | 4 | 5 |
swap tst and ^|
second segment: | v
(partial copy) | 1 |
tst/rem | 2 | | 0 | 1 | 3 | 4 | 5 |
run trial
| 0 | 1 | 3 | 4 | 5 |
swap tst and ^|
third segment: | v
(partial copy) | 2 |
等。正如你可以看到它几乎是逐字地转移了折。保存许多完整副本。
有点奇怪的问题,如果一个人通常会使用sklearn的train_test_split()
,如果它可用。
编辑:另一种方法可能是
r = np.arange(len(data))
trainX = data[r < 5 | r > 10]
有效的解决方案,我不知道,但尝试这个 建立使用列表理解的索引。
def indx(n, test_slice):
return [x for x in range(n) if, x not in test_slice]
test_slice = set(range(5, 10))
trainX = data[indx(len(data), test_slice))]
当然
您应像sklearn的train_test_split()
如果可用。
split = np.vsplit(data, np.array([5,10]))
'''This will give you a list with 3 elements'''
test_slice = split[1]
train_slice = np.vstack((split[0],split[2]))
[[5 5] [6 6] [7 7] [8 8] [9 9]]
[[0 0] [1 1] [2 2] [3 3] [4 4] [10 10] [11 11] [12 12] [13 13] [14 14] [15 15] [16 16] [17 17] [18 18] ... [47 47] [ 48 48] [49 49]]
两种方法,展示了一维阵列上:
In [64]: data = np.arange(20)
In [65]: test = data[5:10]
In [66]: rest = np.concatenate((data[:5],data[10:]),axis=0)
In [67]: rest
Out[67]: array([ 0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
In [68]:
In [68]: mask = np.zeros(data.shape[0], dtype=bool)
In [69]: mask[5:10] = True
In [70]: test = data[mask]
In [71]: rest = data[~mask]
In [72]: rest
Out[72]: array([ 0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
有一个np.delete
功能
In [75]: np.delete(data, np.arange(5,10))
Out[75]: array([ 0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
内部它使用两种方法我证明之一。
在两侧连接切片;结果将是一个副本。 – hpaulj