大师兄的数据分析学习笔记(二十):分类集成(二)

2022-08-05  本文已影响0人  superkmi

大师兄的数据分析学习笔记(十九):分类集成(一)
大师兄的数据分析学习笔记(二十一):线性回归

三、集成方法

2. 提升法
2.1 Adaboost
  • 假设有m个点:Given: \{x_1,y_1\}......\{x_m,y_m\} where x_i \in X,y_i\in Y = \{-1,+1\}
  • 把每个点加初始权值:Initialize D_1(i) = 1/m
  • 循环以下过程:For t = 1......T:
  • 先训练一个弱的分类器D_t.
  • 将分类器D_t的错分点相加为\epsilon_t\epsilon_t=Pr_{i-D_t}[h_t(x_i)\neq y_i]
  • 并通过计算获得分类器的权值\alpha_t\alpha_t=\frac{1}{2}\ln(\frac{1-\epsilon_t}{\epsilon_t})
  • 最后更新每个样本的权值,如果分对了,就乘以\epsilon^{-\alpha_t},否则乘以\epsilon^{\alpha_t}, 其中Z为正规化的权值:D_{t+i}(i) = \frac{D_t(i)exp(-\alpha_t y_i h_t(x_i))}{Z_t}
  • 最终将所有的分类器权值相加,获得判别函数H(x)=sign(\sum_{t=1}^T\alpha_t h_t(x))
  • 精度高,灵活可调。
  • 不容易过拟合
  • 简化特征工程流程
2.2 代码实现
>>>import os
>>>import pandas as pd
>>>import numpy as np
>>>from sklearn.model_selection import train_test_split
>>>from sklearn.metrics import  accuracy_score,recall_score,f1_score
>>>from sklearn.ensemble import RandomForestClassifier
>>>from sklearn.ensemble import AdaBoostClassifier

>>>models = []
>>>models.append(("Adaboost",AdaBoostClassifier()))

>>>df = pd.read_csv(os.path.join(".", "data", "WA_Fn-UseC_-HR-Employee-Attrition.csv"))
>>>X_tt,X_validation,Y_tt,Y_validation = train_test_split(df.JobLevel,df.JobSatisfaction,test_size=0.2)
>>>X_train,X_test,Y_train,Y_test = train_test_split(X_tt,Y_tt,test_size=0.25)

>>>for clf_name,clf in models:
>>>    clf.fit(np.array(X_train).reshape(-1,1),np.array(Y_train).reshape(-1,1))
>>>    xy_lst = [(X_train,Y_train),(X_validation,Y_validation),(X_test,Y_test)]
>>>    for i in range(len(xy_lst)):
>>>        X_part = xy_lst[i][0]
>>>        Y_part = xy_lst[i][1]
>>>        Y_pred = clf.predict(np.array(X_part).reshape(-1,1))
>>>        print(i)
>>>        print(clf_name,"-ACC",accuracy_score(Y_part,Y_pred))
>>>        print(clf_name,"-REC",recall_score(Y_part,Y_pred,average='macro'))
>>>        print(clf_name,"-F1",f1_score(Y_part,Y_pred,average='macro'))
>>>        print("="*40)
0
Adaboost -ACC 0.32086167800453513
Adaboost -REC 0.25459624710099094
Adaboost -F1 0.14092363813679895
========================================
1
Adaboost -ACC 0.3197278911564626
Adaboost -REC 0.250404717853839
Adaboost -F1 0.14941771039332014
========================================
2
Adaboost -ACC 0.30272108843537415
Adaboost -REC 0.2570685434516524
Adaboost -F1 0.14118955654427223
========================================
上一篇 下一篇

猜你喜欢

热点阅读