数模竞赛代码整理----分类器

news/2024/7/9 8:35:00 标签: sklearn, python, 机器学习

文章目录

  • 数据准备
    • 数据不均衡问题
      • SMOTE过采样
      • EasyEnsembleClassifier
  • 具体的分类器

分类器的实现较为简单,主要从sklearn库中调取需要的函数即可。sklearn yyds!!!

数据准备

数据不均衡问题

比如说本题,分类为0的样本有400多个,但是分类为1的样本有1500多个,此时如果直接使用数据去训练分类器,会产生问题。因为分类器全部判别为1,就会有很高的准确率了。

SMOTE过采样

python"># 首先分割训练集与测试集
from sklearn.model_selection import train_test_split
train_xx, test_xx,train_yy_before, test_yy = train_test_split(xx, yy, test_size= 0.3)

# 定义SMOTE过采样解决数据不均衡问题
from imblearn.over_sampling import SMOTE
smo = SMOTE()
train_xx, train_yy = smo.fit_resample(train_xx, train_yy_before)

print('原始数据:{}'.format(collections.Counter(yy)))
print('测试集:{}'.format(collections.Counter(test_yy)))
print('训练集:{}'.format(collections.Counter(train_yy_before)))
print('过采样的训练集:{}'.format(collections.Counter(train_yy)))

EasyEnsembleClassifier

据说这个集成分类器可以解决不均衡问题,但实际体验下来感觉很脑残,最后还是换成了SMOTE。EasyEnsembleClassifier的使用很简单,直接将原来的分离器传参给其即可:

python">from imblearn.ensemble import EasyEnsembleClassifier
from sklearn.ensemble import AdaBoostClassifier

ee_ada = EasyEnsembleClassifier(n_estimators=20,base_estimator=AdaBoostClassifier())
# ee_ada = AdaBoostClassifier()
ee_ada.fit(train_xx, train_yy)

print("准确率:{}, F-measure:{}".format(ee_ada.score(test_xx, test_yy),
                                    f1_score(test_yy,
                                             ee_ada.predict(test_xx))))
plot_AUC(ee_ada, test_xx, test_yy)

具体的分类器

  • Adaboost
  • XGboost
  • RandomForestClassifier(这个有回归器和分类器,不要弄错)
  • GradientBoostingClassifier
  • DecisionTreeClassifier
  • BernoulliNB
  • svm
  • VotingClassifier(集成分类器,可选软硬投票)

使用起来都很简单,分为三部

  1. 导入相关的包
  2. 实例化
  3. 使用fit(x,y)函数进行训练(y为label)
  4. 使用predict()函数进行预测
  5. 可以使用feature_importances_属性查看各个变量对分类的贡献

下面列出VotingClassifier的实例代码:

python">from sklearn.ensemble import VotingClassifier

clf = VotingClassifier(estimators=[
    ('xgboost',
     XGBClassifier(use_label_encoder=False,
                   eval_metric=['logloss', 'auc', 'error'])),
    ('adaboost', AdaBoostClassifier()),
#     ('random_tree', RandomForestClassifier(n_estimators=30)),
    ('gradient_boost', GradientBoostingClassifier()),
#     ('desision', tree.DecisionTreeClassifier())
],
                       voting='soft')

ee_clf = EasyEnsembleClassifier(n_estimators=20, base_estimator=clf)
ee_clf.fit(train_xx, train_yy)

print("准确率:{}, F-measure:{}".format(ee_clf.score(test_xx, test_yy),
                                    f1_score(test_yy,
                                             ee_clf.predict(test_xx))))
plot_AUC(ee_clf, test_xx, test_yy)

相关的各种包:

python">from sklearn import svm  
from sklearn.ensemble import AdaBoostClassifier

from sklearn.ensemble import VotingClassifier

from sklearn import tree

from sklearn.ensemble import GradientBoostingClassifier

from sklearn.ensemble import RandomForestClassifier

from sklearn import svm  
from imblearn.ensemble import EasyEnsembleClassifier

from sklearn.ensemble import AdaBoostClassifier

from sklearn import metrics

import xgboost
from xgboost import XGBClassifier

from sklearn.metrics import f1_score, accuracy_score

另外,绘制AUC图的函数

python">from sklearn import metrics

def plot_AUC(model,X_test,y_test):
    probs = model.predict_proba(X_test)
    preds = probs[:,1]
    fpr, tpr, threshold = metrics.roc_curve(y_test, preds)
    roc_auc = metrics.auc(fpr, tpr)

    plt.title('Receiver Operating Characteristic')
    plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)
    plt.legend(loc = 'lower right')
    plt.plot([0, 1], [0, 1],'r--')
    plt.xlim([0, 1])
    plt.ylim([0, 1])
    plt.ylabel('True Positive Rate')
    plt.xlabel('False Positive Rate')
    plt.show()

http://www.niftyadmin.cn/n/1363457.html

相关文章

数模竞赛代码整理----画图

文章目录相关矩阵图折线图AUC条形图箱型图seasns yyds!!!相关矩阵图 import seaborn as sns import numpy as np import matplotlib.pyplot as pltf, ax plt.subplots(figsize (14, 10)) sns.heatmap(data,cmapRdBu, linewidths 0.05, ann…

ORACLE PL/SQL:触发器

ORACLE PL/SQL 触发器 本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触发器 8.1.3 系统触发器 8.2 创建触发器 8.2.1 触发器触发次序 8.2.2 创建DML触发器 8.2.3 创建替代(INSTEAD OF)触发器 8.2.3 创建系统事件触发器 8.2.4 系统触发器事件属性 …

3D信息的分子图自监督表示学习 PRE-TRAINING MOLECULAR GRAPH REPRESENTATION WITH 3D GEOMETRY

原文地址:https://wyliu.com/papers/GraphMVP.pdf 摘要 分子图表示学习是现代药物和材料发现中的一个基本问题。分子图通常由其二维拓扑结构来建模,但最近发现三维几何信息在预测分子功能方面起着更为重要的作用。然而,现实场景中3D信息的缺乏…

webdynpro

-------------------------------------------------------------------------------------WebDynpro For ABAPSAP 标准文件:http://help.sap.com/saphelp_erp2 ... 2b5f68/frameset.htmhttp://help.sap.com/saphelp_nw04 ... 155106/frameset.htmSDN SAP Blog For WebDynpor A…

变分自动编码VAE Auto-Encoding Variational Bayes

原文:Auto-Encoding Variational Bayes 地址:https://arxiv.org/pdf/1312.6114.pdf 1 存在问题 变分贝叶斯(VB)方法涉及到对难处理后验的近似的优化,但公共平均场方法需要期望的解析解w.r.t.(with respect to 的缩写。是 关于&…

20151013知识体系整理,需与20151011相整合

Car car new Car("骑士","黑色",60);//按对应格式定义汽车的相关内荣car.Dangqyl 10; //引用Dangqyl 并赋值car.Jiayou(30); //car.Youh 20;car.Kaiche(100); //定义属性//品牌public String Pinpai;//颜色public String Yanse;//油箱容量in…

对社会信息敏感的预训练方法 LMSOC: An Approach for Socially Sensitive Pretraining

文献地址:https://arxiv.org/pdf/2110.10319.pdf 本文将社会语境(感觉有点像世界知识)考虑到了NLP的模型之中,基于时间和地理位置两个社会语境构建了数据集,与基线对比,在MRR上的改进超过了100%。 模型的实…

Android Fragment 生命周期及其正确使用(建议使用自定义View替换Fragment)

使用Fragment 官方例子中显示: 例如:一个学生Fragment,需要传入studentId,进行http请求显示,那么setArguments后防止杀掉Fragment后,参数为0,显示不了数据。 1 public static StudentFragment n…