假設我有以下資料:
y = np.ones(10)
y[-5:] = 0
X = pd.DataFrame({'a':np.random.randint(10,20, size=(10)),
'b':np.random.randint(80,90, size=(10))})
X
a b
0 11 82
1 19 82
2 15 80
3 15 86
4 14 82
5 18 87
6 13 83
7 12 83
8 10 82
9 18 87
將其拆分為 5 倍可得到以下指數:
kf = KFold()
data = list(kf.split(X,y))
data
[(array([2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1])),
(array([0, 1, 4, 5, 6, 7, 8, 9]), array([2, 3])),
(array([0, 1, 2, 3, 6, 7, 8, 9]), array([4, 5])),
(array([0, 1, 2, 3, 4, 5, 8, 9]), array([6, 7])),
(array([0, 1, 2, 3, 4, 5, 6, 7]), array([8, 9]))]
但我想進一步準備data ,以便組織包含以下格式的實際值:
data =
[(train1,trainlabel1,test1,testlabel1),
(train2,trainlabel2,test2,testlabel2),
..,
(train5,trainlabel5,test5,testlabel5)]
預期輸出(來自給定的 MWE):
[array([
(array([[15,80],[15,86],[14,82],[18,87],[13,83],[12,83],[10,82],[18,87]]), array([[1],[1],[1],[0],[0],[0],[0],[0])]), #fold1 train/label
(array([[11,82],[19,82]]), array([[1],[1]])), #fold1 test/label
(array([[11,82],[19,82],[14,82],[18,87],[13,83],[12,83],[10,82],[18,87]]),array([[1],[1],[1],[0],[0],[0],[0],[0]])), #fold2 train/label
(array([[15,80],[15,86]]),array([[1],[1]])) #fold2 test/label
....
])]
uj5u.com熱心網友回復:
實際上@hotuagia 的答案是正確的。您收到此錯誤是因為您嘗試訪問其中的元素,y其中使用的loc是資料幀屬性的陣列。一個方便的方法是轉換y為熊貓Dataframe或Series在傳遞到KFold.
所以:
y = np.ones(10)
y[-5:] = 0
X = pd.DataFrame({'a':np.random.randint(10,20, size=(10)),
'b':np.random.randint(80,90, size=(10))})
# y- array to pandas df or series
y = pd.DataFrame(y) # or pd.Series(y)
然后繼續@hotuagia的回答:
for train_idx, test_idx in KFold(n_splits=2).split(X):
x_train = X.loc[train_idx]
x_test = X.loc[test_idx]
y_train = y.loc[train_idx]
y_test = y.loc[test_idx]
uj5u.com熱心網友回復:
如您所知,KFold().split(data)按折疊回傳選定的索引。要選擇帶有索引串列的 Pandas.DataFrame 行,最簡單的方法是loc 方法。
for train_idx, test_idx in KFold(n_splits=2).split(X):
x_train = X.loc[train_idx]
x_test = X.loc[test_idx]
y_train = y.loc[train_idx]
y_test = y.loc[test_idx]
然后,您可以將子集資料幀添加到串列中
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347340.html
