我不是一个专业用户。我知道我可以获得混淆矩阵,但我希望在分类之后能够获得一份错误分类的行的列表,以便于进一步研究。
在StackOverflow上,我找到了这个在scikit-learn的SVM评分函数中是否可以获取错误预测的列表,但我不确定是否完全理解了其中的内容。
这是一个示例代码。
# 导入必要的库
from sklearn import datasets
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
# 加载iris数据集
iris = datasets.load_iris()
# X -> 特征, y -> 标签
X = iris.data
y = iris.target
# 将X, y分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0)
# 训练一个线性SVM分类器
from sklearn.svm import SVC
svm_model_linear = SVC(kernel = 'linear', C = 1).fit(X_train, y_train)
svm_predictions = svm_model_linear.predict(X_test)
# 模型在X_test上的准确率
accuracy = svm_model_linear.score(X_test, y_test)
# 创建混淆矩阵
cm = confusion_matrix(y_test, svm_predictions)
为了遍历行并找出错误的行,所提出的解决方案是:
predictions = clf.predict(inputs)
for input, prediction, label in zip(inputs, predictions, labels):
if prediction != label:
print(input, 'has been classified as ', prediction, 'and should be ', label)
我不明白“input”/“inputs”是什么意思。如果我将这段代码适应到我的代码中,像这样:
for input, prediction, label in zip (X_test, svm_predictions, y_test):
if prediction != label:
print(input, 'has been classified as ', prediction, 'and should be ', label)
我得到了:
[6. 2.7 5.1 1.6] has been classified as 2 and should be 1
第6行是错误的行吗?6.之后的数字是什么?我之所以问这个问题,是因为我正在使用一个比这个数据集更大的数据集,所以我想确保我做的是正确的事情。我不能发布另一个数据集,但问题是那里我得到了类似这样的结果:
(0, 253) 0.5339655767137572 (0, 601) 0.27665553856928027 (0, 1107) 0.7989633757962163 has been classified as 7 and should be 3 (0, 885) 0.3034934766501018 (0, 1295) 0.6432561790864061 (0, 1871) 0.7029318585026516 has been classified as 7 and should be 6 (0, 1020) 1.0 has been classified as 3 and should be 8
当我计算这个最后输出的每一行时,我得到了测试集行数的两倍…所以我不确定我是否在分析完全错误的预测结果列表…
回答:
第6行是错误的行吗?6.之后的数字是什么?
不 – [6. 2.7 5.1 1.6]
是实际的样本(即它的特征)。为了获取错误行的索引,我们应该稍微修改for
循环:
for idx, input, prediction, label in zip(enumerate(X_test), X_test, svm_predictions, y_test):
if prediction != label:
print("No.", idx[0], 'input,',input, ', has been classified as', prediction, 'and should be', label)
结果现在是
No. 37 input, [ 6. 2.7 5.1 1.6] , has been classified as 2 and should be 1
这意味着X_test[37]
,也就是[ 6. 2.7 5.1 1.6]
,被我们的SVM预测为2,而它的真实标签是1。
让我们确认这个读数:
X_test[37]
# array([ 6. , 2.7, 5.1, 1.6])
svm_predictions[37]
# 2
y_test[37]
# 1
这个结果与你的混淆矩阵cm
一致,确实显示X_test
中只有一个样本被错误分类:
cm
# result:
array([[13, 0, 0],
[ 0, 15, 1],
[ 0, 0, 9]], dtype=int64)
一个更优雅的for
循环,因为枚举已经包括了样本本身,可以是:
for idx, prediction, label in zip(enumerate(X_test), svm_predictions, y_test):
if prediction != label:
print("Sample", idx, ', has been classified as', prediction, 'and should be', label)
这将给出
Sample (37, array([ 6. , 2.7, 5.1, 1.6])) , has been classified as 2 and should be 1