
作者:韩信子@ShowMeAI
教程地址:https://www.showmeai.tech/tutorials/41
本文地址:https://www.showmeai.tech/article-detail/210
声明:版权所有,转载请联系平台与作者并注明出处
收藏ShowMeAI查看更多精彩内容
1.AutoML与自动化机器学习
在前序系列文章中大家跟着ShowMeAI一起学习了如何构建机器学习应用。我们构建一个机器学习模型解决方案baseline很容易,但模型选择和泛化性能优化是一项艰巨的任务。选择合适的模型并是一个需要高计算成本、时间和精力的过程。
针对上述问题就提出了AutoML,AutoML(Automated machine learning)是自动化构建端到端机器学习流程,解决实际场景问题的过程。

在本篇内容中我们将介绍到微软开发的高效轻量级自动化机器学习框架FLAML(A Fast and Lightweight AutoML Library)。
2.FLAML介绍
2.1 FLAML特点
官方网站对FLAML的特点总结如下:
- 对于分类和回归等常见的机器学习任务,FLAML可以在消耗尽量少的资源前提下,快速找到高质量模型。它支持经典机器学习模型和深度神经网络。
- 它很容易定制或扩展。用户可以有很灵活的调整与定制模式:
- 最小定制(设定计算资源限制)
- 中等定制(例如设定scikit-learn学习器、搜索空间和度量标准)
- 完全定制(自定义训练和评估代码)。
- 它支持快速且低消耗的自动调优,能够处理大型搜索空间。 FLAML 由 Microsoft Research 发明的新的高效益超参数优化和学习器选择方法支撑。
2.2 安装方法
我们可以通过pip轻松安装上FLAML
pip install flaml
有一些可选的安装选项,如下:
(1) Notebook示例支持
如果大家要跑官方的 notebook代码示例,安装时添加[notebook]选项:
pip install flaml[notebook]
(2) 更多模型学习器支持
- 如果我们希望flaml支持catboost模型,安装时添加[catboost]选项
pip install flaml[catboost]
- 如果我们希望flaml支持vowpal wabbit ,安装时添加[vw]选项
pip install flaml[vw]
- 如果我们希望flaml支持时间序列预估器prophet和statsmodels,安装时可以添加[forecast]
pip install flaml[forecast]
(3) 分布式调优支持
- ray
pip install flaml[ray]
- nni
pip install flaml[nni]
- blendsearch
pip install flaml[blendsearch]
3.FLAML使用示例
3.1 全自动模式
下面我们用一个场景数据案例(二分类)来演示FLAML工具库的全自动模式。(大家可以在jupyter notebook中运行下列的代码,关于IDE与环境配置大家可以参考ShowMeAI文章 图解python | 安装与环境设置)。
!pip install flaml[notebook]
(1) 加载数据和预处理
我们从 OpenML 下载航空公司数据集 Airlines dataset。 这个数据集的建模任务是在给定预定起飞信息的情况下预测给定航班是否会延误。
from flaml.data import load_openml_dataset
X_train, X_test, y_train, y_test = load_openml_dataset(dataset_id=1169, data_dir='./')

从运行结果可以看到训练集测试集及标签的维度信息。
(2) 运行 FLAML全自动模式
下面我们直接运行 FLAML automl 全自动模式,实际在运行配置中,我们可以指定 任务类型、时间预算、误差度量、学习者列表、是否下采样、重采样策略类型等。 如果不作任何设定的话,所有这些参数都会使用默认值(例如,默认分类器是 [lgbm, xgboost, xgb_limitdepth, catboost, rf, extra_tree, lrl1])。
# 导入工具库并初始化AutoML对象
from flaml import AutoML
automl = AutoML()
# 参数设定
settings = {
"time_budget": 240, # 总时间上限(单位秒)
"metric": 'accuracy', # 候选可以是: 'r2', 'rmse', 'mae', 'mse', 'accuracy', 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'log_loss', 'mape', 'f1', 'ap', 'ndcg', 'micro_f1', 'macro_f1'
"task": 'classification', # 任务类型
"log_file_name": 'airlines_experiment.log', # flaml日志文件
"seed": 7654321, # 随机种子
}
# 运行自动化机器学习
automl.fit(X_train=X_train, y_train=y_train, **settings)


从上述运行结果可以看出,自动机器学习过程,对[lgbm, xgboost, xgb_limitdepth, catboost, rf, extra_tree, lrl1]这些候选模型进行了实验,并运行出了对应的结果。
(3) 最优模型与评估结果

print('Best ML leaner:', automl.best_estimator)
print('Best hyperparmeter config:', automl.best_config)
print('Best accuracy on validation data: {0:.4g}'.format(1-automl.best_loss))
print('Training duration of best run: {0:.4g} s'.format(automl.best_config_train_time))
运行结果如下
Best ML leaner: lgbm
Best hyperparmeter config: {'n_estimators': 1071, 'num_leaves': 25, 'min_child_samples': 36, 'learning_rate': 0.10320258241974468, 'log_max_bin': 10, 'colsample_bytree': 1.0, 'reg_alpha': 0.0009765625, 'reg_lambda': 0.08547376339713011, 'FLAML_sample_size': 364083}
Best accuracy on validation data: 0.6696
Training duration of best run: 9.274 s
可以通过运行完毕的automl对象属性,取出对应的「最优模型」、「最佳模型配置」、「评估准则结果」等信息。在这里最优的模型是1071颗树构建而成的一个LightGBM模型。
更进一步,我们可以通过下面的代码,取出最优模型,并用它对测试集进行预测。
# 最佳模型
automl.model.estimator
运行结果如下
LGBMClassifier(learning_rate=0.10320258241974468, max_bin=1023,
min_child_samples=36, n_estimators=1071, num_leaves=25,
reg_alpha=0.0009765625, reg_lambda=0.08547376339713011,
verbose=-1)
(4) 模型存储与加载
# 模型存储与持久化
import pickle
with open('automl.pkl', 'wb') as f:
pickle.dump(automl, f, pickle.HIGHEST_PROTOCOL)
# 模型加载
with open('automl.pkl', 'rb') as f:
automl = pickle.load(f)
# 对测试集进行预估
y_pred = automl.predict(X_test)
print('Predicted labels', y_pred)
print('True labels', y_test)
y_pred_proba = automl.predict_proba(X_test)[:,1]
运行结果如下:
Predicted labels ['1' '0' '1' ... '1' '0' '0']
True labels 118331 0
328182 0
335454 0
520591 1
344651 0
..
367080 0
203510 1
254894 0
296512 1
362444 0
Name: Delay, Length: 134846, dtype: category
Categories (2, object): ['0' < '1']
可以看到,automl得到的最佳模型,对测试集预估的方式,和自己建模得到的模型是一样的。
# 测试集效果评估
from flaml.ml import sklearn_metric_loss_score
print('accuracy', '=', 1 - sklearn_metric_loss_score('accuracy', y_pred, y_test))
print('roc_auc', '=', 1 - sklearn_metric_loss_score('roc_auc', y_pred_proba, y_test))
print('log_loss', '=', sklearn_metric_loss_score('log_loss', y_pred_proba, y_test))
评估结果如下:
accuracy = 0.6720332824110467
roc_auc = 0.7253276908529442
log_loss = 0.6034449031876942
402



被折叠的 条评论
为什么被折叠?



