python - 每次运行时分类报告都会发生变化
问题描述
我使用下面的代码来获取分类模型的confusion matrix
和classification report
,但每次运行结果都会发生变化!为什么会发生,我该如何解决?
import pandas as pd
import numpy as np
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix
bankdata = pd.read_csv("bill_authentication.csv")
X = bankdata.drop('Class', axis=1)
y = bankdata['Class']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
svclassifier = SVC(kernel='rbf')
svclassifier.fit(X_train, y_train)
y_pred = svclassifier.predict(X_test)
print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
解决方案
您需要设置random_states
为train_test_split
. 如果不设置它,每次运行都会获得不同的随机状态。导致不同的火车测试分裂。从而为您的分类器产生不同的输入,这可能(并且在您的情况下是)导致结果不同。
因此,例如,如果您将 random_state 设置为固定值,您将在运行之间获得相同的结果,因此请更改为这行代码。您设置的精确值random_state
无关紧要,只要它在运行之间是相同的。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=1)
您也可以设置 random_state ,SVC
但仅当probability
参数设置为时才起作用True
。默认情况下设置为False
,因此它不应该影响您的情况。