首页 > 解决方案 > 为什么在机器学习模型中所有真阳性都被归类为真阴性?

问题描述

我为数据拟合了一个随机森林模型。我将我的数据集按 70:30 的比例分为训练和测试,并训练了模型。我对测试数据的准确率达到了 80%。然后我拿了一个基准数据集并用该数据集测试了模型。该数据集仅包含具有真实标签的数据 (1)。但是当我使用该模型获得基准数据集的预测时,所有真正的正面都被归类为真正的负面。准确度为 90%。这是为什么?有没有办法解释这个?

X = dataset.iloc[:, 1:11].values    
y=dataset.iloc[:,11].values

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=1,shuffle='true')

XBench_test=benchmarkData.iloc[:, 1:11].values
YBench_test=benchmarkData.iloc[:,11].values

classifier=RandomForestClassifier(n_estimators=35,criterion='entropy',max_depth=30,min_samples_split=2,min_samples_leaf=1,max_features='sqrt',class_weight='balanced',bootstrap='true',random_state=0,oob_score='true')
classifier.fit(X_train,y_train)
y_pred=classifier.predict(X_test)

y_pred_benchmark=classifier.predict(XBench_test)

print("Accuracy on test data: {:.4f}".format(classifier.score(X_test, y_test)))\*This gives 80%*\

print("Accuracy on benchmark data: {:.4f}".format(classifier.score(XBench_test, YBench_test))) \*This gives 90%*\

标签: pythonrandom-forestprediction

解决方案


我将尝试提供一种更好的方法来解释您的结果。在数据集不平衡的情况下,准确性将不是衡量绩效的好方法。

这是一个常见的例子:

想象一下,您患有一种只有 0.01% 的人患有的疾病。如果您预测没有人患有这种疾病,那么您的准确率为 99.99%,但您的模型不是一个好的模型。

在此示例中,您的基准数据集(通常称为测试数据集)似乎具有不平衡的类,并且当您调用 classifier.score 方法时,您的准确度为 90%。在这种情况下,准确性不是解释模型的好方法。相反,您应该查看其他指标。

其他常见的指标可能是查看精确度和召回率以确定模型的执行情况。在这种情况下,由于所有真阳性都被预测为负,因此您的精度和召回率为 0,这意味着您的模型无法很好地区分。

如果您的类别不平衡,则更进一步,检查不同的分数阈值并查看ROC_AUC等指标可能会更好。这些指标查看模型输出的概率分数(sklearn 的 predict_proba)并测试不同的阈值。也许您的模型在较低的阈值下运行良好,并且正面案例的得分始终高于负面案例。

这是关于ROC_AUC的附加文章。

Sci-kit learn 有几个不同的度量分数,您可以使用它们位于此处

这是您可以在代码中实现 ROC AUC 的一种方法。

X = dataset.iloc[:, 1:11].values    
y=dataset.iloc[:,11].values

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=1,shuffle='true')

XBench_test=benchmarkData.iloc[:, 1:11].values
YBench_test=benchmarkData.iloc[:,11].values

classifier=RandomForestClassifier(n_estimators=35,criterion='entropy',max_depth=30,min_samples_split=2,min_samples_leaf=1,max_features='sqrt',class_weight='balanced',bootstrap='true',random_state=0,oob_score='true')
classifier.fit(X_train,y_train)
#use predict_proba
y_pred=classifier.predict_proba(X_test)

y_pred_benchmark=classifier.predict_proba(XBench_test)

from sklearn.metrics import roc_auc_score
## instead of measuring accuracy use ROC AUC)
print("Accuracy on test data: {:.4f}".format(roc_auc_score(X_test, y_test)))\*This gives 80%*\

print("Accuracy on benchmark data: {:.4f}".format(roc_auc_score(XBench_test, YBench_test))) \*This gives 90%*\

推荐阅读