使用Python和SVM,我应用了以下两段代码:
首先,我将此代码应用于数据集
from sklearn.metrics import confusion_matrix
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.svm import LinearSVC
model = LinearSVC(class_weight='balanced',C=0.01, penalty='l2').fit(X_, y)
y_preds = model.predict(X_)
report = classification_report( y, y_preds )
print(report)
print(cohen_kappa_score(y, y_preds),'\n', accuracy_score(y, y_preds), \n',confusion_matrix(y, y_preds))
这给了我这样的准确性:0.9485714285714286
第二,我再次将此代码应用于完全相同的数据集
from sklearn.svm import LinearSVC
from sklearn.model_selection import cross_val_score
models = [
LinearSVC(class_weight='balanced',C=0.01, penalty='l2', loss='squared_hinge'),
]
CV = 5
cv_df = pd.DataFrame(index=range(CV * len(models)))
entries = []
for model in models:
model_name = model.__class__.__name__
accuracies = cross_val_score(model, X_, y, scoring='accuracy', cv=CV)
for fold_idx, accuracy in enumerate(accuracies):
entries.append((model_name, fold_idx, accuracy))
cv_df = pd.DataFrame(entries, columns=['model_name', 'fold_idx', 'accuracy'])
cv_df.groupby('model_name').accuracy.mean()
准确性不同:0.797090
我的错误在哪里?
哪个代码正确(如果有)?
如何像第二个代码那样在交叉验证后计算精度和召回率?
答案 0 :(得分:1)
在第一个代码中,您仅执行1次时间预测和准确性计算。在第二个代码中,您进行了5次预测和准确性计算(使用不同的数据集),然后获得准确性得分的平均值/平均值。换句话说,第二个代码给出了更可靠的准确性得分。
关于另一个问题,如果要对多个指标进行交叉验证,则可以使用cross_validate()
代替cross_val_score()
:
scores = cross_validate(model, X, y, scoring=('precision', 'recall'))
print(scores['precision'])
print(scores['recall'])