将sklearn LOO拆分为pandas数据帧,并将索引作为标签列



我正在尝试(糟糕地(使用sklearn的LOO功能,我想做的是将每个训练分割集附加到一个带有分割索引标签的数据帧列中。因此,使用sklearn页面中的示例,但稍作修改:

import numpy as np
from sklearn.model_selection import LeaveOneOut
x = np.array([1,2])
y = np.array([3,4])
coords = np.column_stack((x,y))
z = np.array([8, 12])
loo = LeaveOneOut()
loo.get_n_splits(coords)
print(loo)
LeaveOneOut()
for train_index, test_index in loo.split(coords):
print("TRAIN:", train_index, "TEST:", test_index)
XY_train, XY_test = coords[train_index], coords[test_index]
z_train, z_test = z[train_index], z[test_index]
print(XY_train, XY_test, z_train, z_test)

哪个返回:

TRAIN: [1] TEST: [0]
[[2 4]] [[1 3]] [12] [8]
TRAIN: [0] TEST: [1]
[[1 3]] [[2 4]] [8] [12]

在我的情况下,我想将每个分割值写入一个数据帧,如下所示:

X    Y   Ztrain    Ztest    split
0    1    2   8         12       0
1    3    4   8         12       0
2    1    2   12        8        1
3    3    4   12        8        1

等等。

这样做的动机是我想尝试稀疏点数据的jacknifeng插值。理想情况下,我想在每个LOO训练集上运行一个插值/网格器,然后将它们叠加。但我很难访问每一组火车,然后在类似网格的东西中使用

对于这里的问题或一般的方法,任何帮助都将不胜感激。

我不太了解数据帧的逻辑,但您可以尝试以下方法来获取数据帧:

df = []
for train_index, test_index in loo.split(coords):
x = pd.DataFrame({'XY_train':coords[train_index][0],
'XY_test':coords[test_index][0],
'Ztrain':z[train_index][0],
'Ztest':z[test_index][0]})
df.append(x)
df = pd.concat(df)
df
XY_train  XY_test  Ztrain  Ztest
0         2        1      12      8
1         4        3      12      8
0         1        2       8     12
1         3        4       8     12

最新更新