
本教程探讨了机器学习模型评估中出现相同指标结果的常见原因,尤其是在多模型比较场景下。核心问题往往源于预测变量的错误引用,而非模型性能一致。文章将通过一个具体的文本分类案例,详细解析这种错误,并提供正确的代码实践,强调在模型评估中精确管理变量的重要性。
引言
在机器学习项目的实践中,我们经常需要训练并比较多个模型以找到最佳解决方案。然而,在评估这些模型时,有时会遇到一个令人困惑的现象:不同模型的性能指标(如准确率、F1分数)竟然完全相同。这种看似巧合的结果,往往并非模型性能真的趋同,而是代码中存在细微但关键的错误,最常见的就是变量引用不当。本教程将深入剖析这一问题,并通过一个实际案例展示如何识别并修正此类错误,确保模型评估的准确性。
场景描述:文本分类任务中的指标异常
假设我们正在进行一个文本分类任务,目标是识别HTTP请求中的SQL注入攻击(sqli)或正常请求(norm)。我们使用了一个公开数据集,并计划比较高斯朴素贝叶斯(Gaussian Naive Bayes)、随机森林(Random Forest)和支持向量机(SVM)这三种分类器的性能。
首先,我们加载必要的库并进行数据预处理:
import pandas as pdfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import train_test_splitfrom nltk.corpus import stopwordsfrom sklearn.metrics import accuracy_score, f1_score, classification_reportfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.svm import SVCfrom sklearn.naive_bayes import GaussianNBimport warningswarnings.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}")
输出示例:
神卷标书
神卷标书,专注于AI智能标书制作、管理与咨询服务,提供高效、专业的招投标解决方案。支持一站式标书生成、模板下载,助力企业轻松投标,提升中标率。
39 查看详情
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.9806066633515664F1 Score of Naive Bayes on test set : 0.9735234215885948Classification 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 2011weighted avg 0.98 0.98 0.98 2011
随机森林分类器评估(原始错误代码)
以上就是机器学习模型评估中指标重复的常见陷阱与解决方案:变量引用错误解析的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/582621.html
微信扫一扫
支付宝扫一扫