【发布时间】:2021-11-12 19:17:40
【问题描述】:
我正在尝试在 10 折交叉验证中保存每个折叠的多个混淆矩阵实例。 我的代码如下所示:
kf = KFold(n_splits=10, shuffle=True)
conf_matrix = np.zeros([3,3])
for train_index, test_index in kf.split(X):
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
model.fit(X_train, y_train)
pred = model.predict(X_test)
conf_matrix[train_index] = confusion_matrix(y_test, pred)
conf_matrix
但它返回此错误
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-8a1e0e2223f7> in <module>()
9 model.fit(X_train, y_train)
10 pred = model.predict(X_test)
---> 11 conf_matrix[train_index] = confusion_matrix(y_test, pred)
12 # print(confusion_matrix(y_test, pred))
13
ValueError: shape mismatch: value array of shape (3,3) could not be broadcast to indexing result of shape (270,3)
这很奇怪,因为如果我运行 print(confusion_matrix(y_test, pred)) 输出是 3x3 矩阵,看起来像这样:
[[4 2 3]
[4 8 1]
[1 3 4]]
[[3 6 1]
[4 5 1]
[5 1 4]]
[[7 3 4]
[4 4 1]
[0 1 6]]
[[3 1 2]
[2 9 1]
[3 2 7]]
[[4 4 2]
[2 8 2]
[0 2 6]]
[[7 6 1]
[4 4 2]
[0 3 3]]
[[4 1 3]
[2 5 3]
[3 1 8]]
[[1 4 3]
[2 5 1]
[2 3 9]]
[[7 5 2]
[2 3 3]
[2 3 3]]
[[4 2 1]
[2 6 0]
[3 5 7]]
我哪里做错了?
编辑 2:我已经尝试了 @user1424589 的建议,现在像这样更改我的代码
conf_matrix = np.zeros((10,len(y_test),len(y_test))) #10 because I want it to caontain 10 confusion matrix
但它仍然返回相同的错误,它现在返回此错误
ValueError: shape mismatch: value array of shape (3,3) could not be broadcast to indexing result of shape (270,30,30)
【问题讨论】:
标签: python matrix confusion-matrix