python - 如何构建混淆矩阵?
问题描述
我有以下代码,它绘制了 KNN 算法的嵌套与非嵌套交叉验证。
# Number of random trials
NUM_TRIALS = 30
# Load the dataset
X_iris = X.values
y_iris = y
# Set up possible values of parameters to optimize over
p_grid = {"n_neighbors": [1, 5, 10]}
# We will use a Support Vector Classifier with "rbf" kernel
svm = KNeighborsClassifier()
# Arrays to store scores
non_nested_scores = np.zeros(NUM_TRIALS)
nested_scores = np.zeros(NUM_TRIALS)
# Loop for each trial
for i in range(NUM_TRIALS):
# Choose cross-validation techniques for the inner and outer loops,
# independently of the dataset.
# E.g "GroupKFold", "LeaveOneOut", "LeaveOneGroupOut", etc.
inner_cv = KFold(n_splits=4, shuffle=True, random_state=i)
outer_cv = KFold(n_splits=4, shuffle=True, random_state=i)
# Non_nested parameter search and scoring
clf = GridSearchCV(estimator=svm, param_grid=p_grid, cv=inner_cv)
clf.fit(X_iris, y_iris)
non_nested_scores[i] = clf.best_score_
# Nested CV with parameter optimization
nested_score = cross_val_score(clf, X=X_iris, y=y_iris, cv=outer_cv)
nested_scores[i] = nested_score.mean()
score_difference = non_nested_scores - nested_scores
preds=clf.best_estimator_.predict(X_test)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, preds)
one, two, three, four,five,six,seven,eight,nine = confusion_matrix(y_test, preds).ravel()
我遇到的问题是混淆矩阵绘图,我遇到了以下错误:
ValueError Traceback (most recent call last)
<ipython-input-22-13536688e18b> in <module>()
45 from sklearn.metrics import confusion_matrix
46 cm = confusion_matrix(y_test, preds)
---> 47 one, two, three, four,five,six,seven,eight,nine = confusion_matrix(y_test, preds).ravel()
48 cm = [[one,two],[three,four],[five,six],[seven,eight],[nine,eight]]
49 ax= plt.subplot()
ValueError: too many values to unpack (expected 9)
我不知道如何解决这个问题。我的数据集中有 9 个目标变量,存储在 y 中。
[11 11 11 ... 33 33 33] #the target variables being : 11,12,13,21,22,23,31,32,33
这是我的特征数据集的头部:
Duration Grand Mean Max Mean Activation
0 64 136.772461 178.593750
1 67 193.445196 258.515625
2 67 112.382929 145.765625
解决方案
混淆矩阵由“cm = chaos_matrix(y_test, preds)”构建,其中 cm 是 9x9 矩阵(因为目标变量中有 9 个不同的标签)。如果你想绘制它,你可以使用plot_confusion_matrix 函数。没有必要解开它。如果你解开它,9x9 矩阵将被转换为 81 个值,并且你将它解包为赋值左侧的 9 个变量。这就是您收到“太多值无法解包(预期为 9)”错误的原因。
推荐阅读
- python - 如何创建一个函数,向我显示分类列中具有 0 的行和唯一的数字列中的 ows?
- html - reCAPTCHA 是否可以在没有域名的 html 中工作?
- arrays - 使用 Swift 5.2 解码 JSON 会引发错误“预期解码数组
而是找到了一本字典。” - python - 稳定的 Softmax 函数返回错误的输出
- ocaml - 是否可以在 OCaml 中创建 solib
- c++ - zmq_send() 通过多个连接发送到哪里?
- python - Pygame打开窗口并立即崩溃
- javascript - 类型错误:arr.map 不是函数
- python - Django request.POST.get() 返回无
- python - pymongo:如何将字段插入到已经存在的文档中