AxisError:轴 1 超出维度 1 数组的范围

数据挖掘 支持向量机 机器学习模型 混淆矩阵 python-3.x
2022-02-20 05:31:20

我使用了 svm 分类器。现在我需要构建混淆矩阵。这是我使用的代码。

from sklearn.svm import SVC

svm = SVC(kernel='rbf')

svm.fit(feat_train,np.argmax(Y_train,axis=1))
svm.score(feat_train,np.argmax(Y_train,axis=1))
svm.score(feat_val,np.argmax(Y_val,axis=1))
y_pred = svm.predict(feat_val)
y_pred.shape
(950,)
y_class = np.argmax(y_pred, axis = 1) 
y_check = np.argmax(Y_val, axis = 1) 

cmatrix = confusion_matrix(y_check, y_class)
print(cmatrix)
print('accuracy Score :'),accuracy_score(y_check, y_class) 

print('Report : ')
print(classification_report(y_check, y_class))

我收到以下错误

---------------------------------------------------------------------------
AxisError                                 Traceback (most recent call last)
<ipython-input-102-67006c959068> in <module>
----> 1 y_class = np.argmax(y_pred, axis = 1)
      2 y_check = np.argmax(Y_val, axis = 1)
      3 
      4 cmatrix = confusion_matrix(y_check, y_class)
      5 print(cmatrix)

~\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in argmax(a, axis, out)
   1101 
   1102     """
-> 1103     return _wrapfunc(a, 'argmax', axis=axis, out=out)
   1104 
   1105 

~\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     54 def _wrapfunc(obj, method, *args, **kwds):
     55     try:
---> 56         return getattr(obj, method)(*args, **kwds)
     57 
     58     # An AttributeError occurs if the object does not have

AxisError: axis 1 is out of bounds for array of dimension 1

我认为问题出在 y_pred 上,因为尺寸为 (950,)。请帮我解决这个问题

1个回答
y_class = np.argmax(y_pred, axis = 1)

这里axis = 1代表检查最大值索引列明智你面临错误,因为你正在传递向量(大小,)

y_class = np.argmax(y_pred, axis = 0)

使用上面的代码来消除错误