最优化超参数
导入库
from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint
AdaBoost模型
- 训练参数
ada_param = {'n_estimators': [10, 50, 100, 200, 400], 'learning_rate': [0.1, 0.05]}
- 模型训练
randomizedSearchAda = RandomizedSearchCV(estimator=adaMod, param_distributions=ada_param, n_iter=5, scoring='roc_auc', cv=None, verbose=2).fit(X_train, Y_train) RandomizedSearchCV参数说明,clf1设置训练的学习器 param_dist字典类型,放入参数搜索范围 scoring = 'roc_auc',精度评价方式设定为“roc_auc“ n_iter=300,训练300次,数值越大,获得的参数精度越大,但是搜索时间越长 n_jobs = -1,使用所有的CPU进行训练,默认为1,使用1个CPU
模型训练情况:
Fitting 5 folds for each of 5 candidates, totalling 25 fits [Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers. [CV] n_estimators=10, learning_rate=0.1 .............................. [Parallel(n_jobs=1)]: Done 1 out of 1 | elapsed: 0.5s remaining: 0.0s [CV] ............... n_estimators=10, learning_rate=0.1, total= 0.5s [CV] n_estimators=10, learning_rate=0.1 .............................. [CV] ............... n_estimators=10, learning_rate=0.1, total= 0.5s [CV] n_estimators=10, learning_rate=0.1
该算法返回:
randomizedSearchAda.best_params_, randomizedSearchAda.best_score_ best_params_ = {'n_estimators': 200, 'learning_rate': 0.1} 输出最优训练器的精度 best_score_ = 0.8583
GB模型
gbParams = {'loss': ['deviance', 'exponential'],'n_estimators': [10, 50, 100, 200, 400],'max_depth': randint(1, 5),'learning_rate': [0.1, 0.05]}
randomizedSearchGB = RandomizedSearchCV(estimator=gbMod, param_distributions=gbParams, n_iter=10,scoring='roc_auc', cv=None, verbose=2).fit(X_train, Y_train) randomizedSearchGB.best_params_, randomizedSearchGB.best_score_
训练的过程
Fitting 5 folds for each of 1 candidates, totalling 5 fits [Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers. [CV] learning_rate=0.1, loss=exponential, max_depth=2, n_estimators=200 [CV] learning_rate=0.1, loss=exponential, max_depth=2, n_estimators=200, total= 12.4s [CV] learning_rate=0.1, loss=exponential, max_depth=2, n_estimators=200 [Parallel(n_jobs=1)]: Done 1 out of 1 | elapsed: 12.4s remaining: 0.0s [CV] learning_rate=0.1, loss=exponential, max_depth=2, n_estimators=200, total= 12.8s
randomizedSearchGB.best_params_, randomizedSearchGB.best_score_ best_params_= {'learning_rate': 0.1, 'loss': 'exponential', 'max_depth': 2, 'n_estimators': 200} best_score_=0.8634
用最优的分类容再训练数据
bestGbModFitted = randomizedSearchGB.best_estimator_.fit(X_train, Y_train) bestAdaModFitted = randomizedSearchAda.best_estimator_.fit(X_train, Y_train)
再评估模型
cvDictHPO = cvDictGen(functions=[bestGbModFitted, bestAdaModFitted], scr='roc_auc') cvDictHPO: {'GradientBoostingClassifier': [0.8266652916225066, 0.0051271698988066315], 'AdaBoostClassifier': [0.8551661366453513, 0.003975186847574813]}
数据标准化
cvDictNormalize(cvDictHPO) cvDictNormalized: {'GradientBoostingClassifier': ['1.00', '1.00'], 'AdaBoostClassifier': ['1.03', '0.78']}
画ROC曲线
代码
def plotCvRocCurve(X, y, classifier, nfolds=5): # 导入roc_curve(roc曲线库)、auc面积库 from sklearn.metrics import roc_curve, auc # 导入StratifiedKFold k折交叉拆分 分层采样,确保训练集,测试集中各类别样本的比例与原始数据集中相同 from sklearn.model_selection import StratifiedKFold # 导入画图 pyplot库 import matplotlib.pyplot as plt # cv = StratifiedKFold(y, n_folds=nfolds) cv = StratifiedKFold(n_splits=4, random_state=0, shuffle=True) mean_tpr = 0.0 # 在指定的间隔内返回均匀间隔的数字 # numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) # 0-1之间 100个数字 均匀间隔的数字 mean_fpr = np.linspace(0, 1, 100) all_tpr = [] # for i, (train, test) in enumerate(cv): i = 0 # 分层拆分数据集 为 训练集和测试集 确保拆分后的数据集和原始数据中的比例相同 for train, test in cv.split(X, y): # 使用 梯度提升树GradientBoostingClassifier算法 训练数据 # 使用测试数据进行预测 probas_ = classifier.fit(X.iloc[train], y.iloc[train]).predict_proba(X.iloc[test]) # 根据预测结果和实际结果计算阈值、fpr(实际样本中预测错误的样本比例)、tpr(等于recall 实际的样本中预测正确的样本所在比例) # 假如阈值是 0.2 小于0.2的值 认为是错误的 大于0.2的值表示正确的 则就可以计算这个阈值下的tpr和fpr了 fpr, tpr, thresholds = roc_curve(y.iloc[test], probas_[:, 1]) # 一维线性插值. # 返回离散数据的一维分段线性插值结果. # # 参数 # x: 数组 # 待插入数据的横坐标 # 横坐标是fpr 纵坐标tpr mean_tpr += np.interp(mean_fpr, fpr, tpr) mean_tpr[0] = 0.0 roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc)) i = i+1 plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') # mean_tpr /= len(cv) mean_tpr /= cv.n_splits mean_tpr[-1] = 1.0 mean_auc = auc(mean_fpr, mean_tpr) plt.plot(mean_fpr, mean_tpr, 'k--', label='Mean ROC (area = %0.2f)' % mean_auc, lw=2) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('CV ROC curve') plt.legend(loc="lower right") fig = plt.gcf() fig.set_size_inches(15, 5) plt.show()