
本教程探讨了机器学习模型评估中出现相同指标结果的常见原因,尤其是在多模型比较场景下。核心问题往往源于预测变量的错误引用,而非模型性能一致。文章将通过一个具体的文本分类案例,详细解析这种错误,并提供正确的代码实践,强调在模型评估中精确管理变量的重要性。
在机器学习项目的实践中,我们经常需要训练并比较多个模型以找到最佳解决方案。然而,在评估这些模型时,有时会遇到一个令人困惑的现象:不同模型的性能指标(如准确率、F1分数)竟然完全相同。这种看似巧合的结果,往往并非模型性能真的趋同,而是代码中存在细微但关键的错误,最常见的就是变量引用不当。本教程将深入剖析这一问题,并通过一个实际案例展示如何识别并修正此类错误,确保模型评估的准确性。
假设我们正在进行一个文本分类任务,目标是识别HTTP请求中的SQL注入攻击(sqli)或正常请求(norm)。我们使用了一个公开数据集,并计划比较高斯朴素贝叶斯(Gaussian Naive Bayes)、随机森林(Random Forest)和支持向量机(SVM)这三种分类器的性能。
首先,我们加载必要的库并进行数据预处理:
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from nltk.corpus import stopwords
from sklearn.metrics import accuracy_score, f1_score, classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
import warnings
warnings.filterwarnings('ignore')
# 1. 加载和预处理数据
df = pd.read_csv("payload_mini.csv", encoding='utf-16')
# 筛选出目标类别
df = df[(df['attack_type'] == 'sqli') | (df['attack_type'] == 'norm')]
X = df['payload']
y = df['label']
# 使用CountVectorizer进行特征提取
vectorizer = CountVectorizer(min_df=2, max_df=0.8, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(X.values.astype('U')).toarray()
# 划分训练集和测试集,设置random_state以确保结果可复现
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(f"X_train shape: {X_train.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"X_test shape: {X_test.shape}")
print(f"y_test shape: {y_test.shape}")输出示例:
X_train shape: (8040, 1585) y_train shape: (8040,) X_test shape: (2011, 1585) y_test shape: (2011,)
接下来,我们分别训练和评估高斯朴素贝叶斯和随机森林模型。
nb_clf = GaussianNB()
nb_clf.fit(X_train, y_train)
y_pred_nb = nb_clf.predict(X_test) # 使用y_pred_nb存储朴素贝叶斯的预测结果
print(f"Accuracy of Naive Bayes on test set : {accuracy_score(y_pred_nb, y_test)}")
print(f"F1 Score of Naive Bayes on test set : {f1_score(y_pred_nb, y_test, pos_label='anom')}")
print("\nClassification Report (Naive Bayes):")
print(classification_report(y_test, y_pred_nb))输出示例:
Accuracy of Naive Bayes on test set : 0.9806066633515664
F1 Score of Naive Bayes on test set : 0.9735234215885948
Classification Report (Naive Bayes):
precision recall f1-score support
anom 0.97 0.98 0.97 732
norm 0.99 0.98 0.98 1279
accuracy 0.98 2011
macro avg 0.98 0.98 0.98 2011
weighted avg 0.98 0.98 0.98 2011以上就是机器学习模型评估中指标重复的常见陷阱与解决方案:变量引用错误解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号