亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ValueError:需要至少一個數組與 sklearn cross_val_predict

ValueError:需要至少一個數組與 sklearn cross_val_predict

慕婉清6462132 2023-07-11 16:31:13
我正在嘗試使用 SVM 分類器使用自定義交叉驗證折疊來建模二元分類問題,但它給了我錯誤 **需要至少一個數組來連接 ** 與 cross_val_predict。該代碼在 cros_val_predict 中的 cv=3 下工作正常,但是當我使用 custom_cv 時,它會出現此錯誤。下面是代碼:from sklearn.model_selection import LeavePOutimport numpy as npfrom sklearn.svm import SVCfrom time import *from sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import cross_val_predict,cross_val_scoreclf = SVC(kernel='linear',C=25)X = np.array([[1, 2], [3, 4], [5, 6], [7, 8],[9,10]])y = np.array([0,1,1,0,0])lpo = LeavePOut(2)print(lpo.get_n_splits(X))LeavePOut(p=2)test_index_list=[]train_index_list=[]for train_index, test_index in lpo.split(X,y):    if(y[test_index[0]]==y[test_index[1]]):    pass  else:    print("TRAIN:", train_index, "TEST:", test_index)    X_train, X_test = X[train_index], X[test_index]    y_train, y_test = y[train_index], y[test_index]    train_index_list.append(train_index)    test_index_list.append(test_index)custom_cv = zip(train_index_list, test_index_list)scores = cross_val_score(clf, X, y, cv=custom_cv)print(scores)print('accuracy:',scores.mean())predicted=cross_val_predict(clf,X,y,cv=custom_cv) # error with this lineprint('Confusion matrix:',confusion_matrix(labels, predicted))以下是錯誤的完整跟蹤:ValueError                                Traceback (most recent call last)<ipython-input-11-d78feac932b2> in <module>()     31 print(scores)     32 print('accuracy:',scores.mean())---> 33 predicted=cross_val_predict(clf,X,y,cv=custom_cv)     34      35 print('Confusion matrix:',confusion_matrix(labels, predicted))關于如何解決此錯誤有什么建議嗎?
查看完整描述

1 回答

?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

這里有2個錯誤:

  1. 如果您想重用zip對象,請創建一個列表。該物體在使用一次后就會耗盡。你可以這樣修復它:

custom_cv?=?[*zip(train_index_list,?test_index_list)]
  1. 交叉驗證列表cross_val_predict應該是實際數組的分區(每個樣本應該只屬于一個測試集)。就你而言,事實并非如此。如果您考慮一下,堆疊交叉驗證列表的輸出將產生長度為6 的數組,而原始y的長度為 5。您可以像這樣實現自定義交叉驗證預測:

def custom_cross_val_predict(clf, X, y, cv):

? ? y_pred, y_true = [], []

? ? for tr_idx, vl_idx in cv:

? ? ? ? X_tr, y_tr = X[tr_idx], y[tr_idx]

? ? ? ? X_vl, y_vl = X[vl_idx], y[vl_idx]

? ? ? ? clf.fit(X_tr, y_tr)

? ? ? ? y_true.extend(y_vl)

? ? ? ? y_pred.extend(clf.predict(X_vl))

? ? ? ??

? ? return y_true, y_pred


labels, predicted = custom_cross_val_predict(clf,X,y,cv=custom_cv)

print('Confusion matrix:',confusion_matrix(labels, predicted))


查看完整回答
反對 回復 2023-07-11
  • 1 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號