我使用下面的代码来获取分类模型的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))发布于 2020-10-29 04:14:59
您需要为train_test_split设置random_states。如果不设置它,每次运行都会得到不同的随机状态。从而导致不同的列车测试分裂。从而导致分类器的不同输入,这可能(在您的情况下是)导致结果不同。
例如,如果您将random_state设置为固定值,您将在两次运行之间获得相同的结果,因此请更改为此行代码。您将random_state设置为的精确值并不重要,只要它在两次运行之间是相同的。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=1)您也可以为SVC设置random_state,但这只在probability参数设置为True时起作用。默认情况下设置为False,因此不会影响您的大小写。
https://stackoverflow.com/questions/64579303
复制相似问题