AutoGluon-教程2-提升更高精度
写在前面
接上一节喽,链接:
订正
关于predict.显示的模型一般是最优模型,而最优模型可由predictor.get_model_best()获得
训练模型(加入验证集)
# 加载训练集
from autogluon.tabular import TabularDataset, TabularPredictor
import numpy as np
train_data = TabularDataset('https://autogluon.s3.amazonaws.com/datasets/Inc/train.csv')
subsample_size = 500 # subsample subset of data for faster demo, try setting this to much larger values
train_data = train_data.sample(n=subsample_size, random_state=0)
print(train_data.head())
# 加载验证集和测试集
new_data = TabularDataset('https://autogluon.s3.amazonaws.com/datasets/Inc/test.csv')
test_data = new_data[5000:].copy() # this should be separate data in your applications
y_test = test_data[label]
test_data_nolabel = test_data.drop(columns=[label]) # delete label column
val_data = new_data[:5000].copy()
# 定义评估指标,accuracy是默认的
metric = 'accuracy' # we specify eval-metric just for demo (unnecessary as it's the default)
选定特定分类器
predictor.predict(test_data, model='LightGBM')
如何获取指定分类器的参数
all_models = predictor.get_model_names()
model_to_use = all_models[i]
specific_model = predictor._trainer.load_model(model_to_use)
# Objects defined below are dicts of various information (not printed here as they are quite large):
model_info = specific_model.get_info()
predictor_information = predictor.info()
这边我看了model_info,里面就是
这个应该就是模型的具体信息了,着实有点多,让人眼花缭乱。
额外部分
输出预测概率
pred_probs = predictor.predict_proba(test_data_nolab)
pred_probs.head(5)
在测试集上定义其他输出标准
predictor.leaderboard(test_data, extra_metrics=['accuracy', 'balanced_accuracy', 'log_loss'], silent=True)
可以选择的输出有’[‘accuracy’, ‘acc’, ‘balanced_accuracy’, ‘mcc’, ‘roc_auc’, ‘roc_auc_ovo_macro’, ‘average_precision’, ‘log_loss’, ‘nll’, ‘pac_score’, ‘precision’, ‘precision_macro’, ‘precision_micro’, ‘precision_samples’, ‘precision_weighted’, ‘recall’, ‘recall_macro’, ‘recall_micro’, ‘recall_samples’, ‘recall_weighted’, ‘f1’, ‘f1_macro’, ‘f1_micro’, ‘f1_samples’, ‘f1_weighted’, ‘r2’, ‘mean_squared_error’, ‘mse’, ‘root_mean_squared_error’, ‘rmse’, ‘mean_absolute_error’, ‘mae’, ‘median_absolute_error’, ‘spearmanr’, ‘pearsonr’, ‘pinball_loss’, ‘pinball’, ‘soft_log_loss’]’,兄弟,眼睛花不花,哈哈哈。
拟合过程中发生了什么
results = predictor.fit_summary()
这张图的score_val代表的是模型在验证集的性能表现,而pred_time_则表示在集上预测所花的时间,还有就是fit_*拟合的时间
更高的输出精度(参数设置)
增加训练时间的一般都会增加输出精度
- time_limit : 模型训练的最长等待时间,通常不设置
- eval_metric: 评估指标,AUC还是精度等
- presets: 默认为’medium_quality_faster_train’,损失了精度但是速度比较快。要是设置为“best_quality”,则会做bagging和stacking以提高性能
- Tuning_data: 这个作为验证集数据的参数,官网建议如果没有特别的理由时不加,让机器自己从训练集中分割出一小部分验证集,这边值得一提的是机器还能自己根据数据使用分层抽样等,可以说是非常人性化了。
- holdout_frac:这个参数指定从训练集出分割出多少比例的验证集
- num_bag_folds = 5-10,这个应该是类似k倍交叉验证,会增加训练时间
- num_stack_levels = 1-3,stacking 水平
- num_bag_sets:减少方差,但是增加训练时间
time_limit = 60 # for quick demonstration only, you should set this to longest time you are willing to wait (in seconds)
metric = 'roc_auc' # specify your evaluation metric here
predictor = TabularPredictor(label, eval_metric=metric).fit(train_data, time_limit=time_limit, presets='best_quality')
predictor.leaderboard(test_data, silent=True)
定义搜索空间
import autogluon.core as ag
nn_options = { # specifies non-default hyperparameter values for neural network models
'num_epochs': 10, # number of training epochs (controls training time of NN models)
'learning_rate': ag.space.Real(1e-4, 1e-2, default=5e-4, log=True), # learning rate used in training (real-valued hyperparameter searched on log-scale)
'activation': ag.space.Categorical('relu', 'softrelu', 'tanh'), # activation function used in NN (categorical hyperparameter, default = first entry)
'layers': ag.space.Categorical([100], [1000], [200, 100], [300, 200, 100]), # each choice for categorical hyperparameter 'layers' corresponds to list of sizes for each NN layer to use
'dropout_prob': ag.space.Real(0.0, 0.5, default=0.1), # dropout probability (real-valued hyperparameter)
}
gbm_options = { # specifies non-default hyperparameter values for lightGBM gradient boosted trees
'num_boost_round': 100, # number of boosting rounds (controls training time of GBM models)
'num_leaves': ag.space.Int(lower=26, upper=66, default=36), # number of leaves in trees (integer hyperparameter)
}
hyperparameters = { # hyperparameters of each model type
'GBM': gbm_options,
'NN': nn_options, # NOTE: comment this line out if you get errors on Mac OSX
} # When these keys are missing from hyperparameters dict, no models of that type are trained
time_limit = 2*60 # train various models for ~2 min
num_trials = 5 # try at most 5 different hyperparameter configurations for each type of model
search_strategy = 'auto' # to tune hyperparameters using Bayesian optimization routine with a local scheduler
hyperparameter_tune_kwargs = { # HPO is not performed unless hyperparameter_tune_kwargs is specified
'num_trials': num_trials,
'scheduler' : 'local',
'searcher': search_strategy,
}
predictor = TabularPredictor(label=label, eval_metric=metric).fit(
train_data, tuning_data=val_data, time_limit=time_limit,
hyperparameters=hyperparameters, hyperparameter_tune_kwargs=hyperparameter_tune_kwargs,
)
这部分就是根据自己的需求个性化定义一下搜索空间了,然后由于定义了搜索空间,所以这模型就只有nn和GBM了
训练结果
y_pred = predictor.predict(test_data_nolabel)
print("Predictions: ", list(y_pred)[:5])
perf = predictor.evaluate(test_data, auxiliary_metrics=False)
results = predictor.fit_summary()
可以看到准确率只有0.29,下面是其他模型的准确率
模型的解释性(特征的重要性)
芜湖,特征的重要性来喽。
predictor.feature_importance(test_data)
这样如果你需要进行特征工程或缩小特征的话,也可以运行这部分代码哦。我是一般在深度学习不过滤特征的,机器学习过程会过滤特征。
减少时间操作
# 模型启用
predictor.persist_models()
num_test = 20
preds = np.array(['']*num_test, dtype='object')
for i in range(num_test):
datapoint = test_data_nolabel.iloc[[i]]
pred_numpy = predictor.predict(datapoint, as_pandas=False)
preds[i] = pred_numpy[0]
perf = predictor.evaluate_predictions(y_test[:num_test], preds, auxiliary_metrics=True)
print("Predictions: ", preds)
# 释放内存
predictor.unpersist_models() # free memory by clearing models, future predict() calls will load models from disk
默认情况下,autogluon一次将模型加载到内存中,只有在预测所需时才能成为内存。这种策略对于stacking/bagging是强大的,但导致预测时间较慢。如果计划反复进行预测(例如,在一次的新数据点而不是一个大型测试数据集上),可以首先指定推理所需的所有模型应加载到内存中,如上所示。当然可以指定特定的分类器或全部的分类器模型
我是用不上这个功能了,感觉
删除模型中部分分类器
additional_ensembles = predictor.fit_weighted_ensemble(expand_pareto_frontier=True)
print("Alternative ensembles you can use for prediction:", additional_ensembles)
predictor.leaderboard(only_pareto_frontier=True, silent=True)
model_for_prediction = additional_ensembles[0]
predictions = predictor.predict(test_data, model=model_for_prediction)
predictor.delete_models(models_to_delete=additional_ensembles, dry_run=False) # delete these extra models so they don't affect rest of tutorial
将交叉验证的模型整合到一块去
refit_model_map = predictor.refit_full()
print("Name of each refit-full model corresponding to a previous bagged ensemble:")
print(refit_model_map)
predictor.leaderboard(test_data, silent=True)
这边说这么做是可以大大降低memory/latency requirements (but may also reduce accuracy)
,因为最后整合了所有交叉模型,也就是利用了所有的数据,后面也就没有模型的验证评估了(原先的验证集是从训练集分出的一小块数据)
参数部分
- hyperparameters: 选择’very_light’,“‘light’”,“toy”
- time_limit: 选择比较短的时间
- excluded_model_types:去掉某些已知的训练比较慢的模型
- presets :跟上面精度提高的类似,不过是选用了不同的参数以达到不同的效果
presets = ['good_quality_faster_inference_only_refit', 'optimize_for_deployment']
predictor_light = TabularPredictor(label=label, eval_metric=metric).fit(train_data, presets=presets, time_limit=30)
excluded_model_types = ['KNN', 'NN', 'custom']
predictor_light = TabularPredictor(label=label, eval_metric=metric).fit(train_data, excluded_model_types=excluded_model_types, time_limit=30,
presets=presets,hyperparameters='very_light')
碰到内存不够怎么办
- 设置num_bag_sets = 1(也可以尝试大于1)。
- 设定excluded_model_types = [‘KNN’, ‘XT’ ,‘RF’](或这些模型的某些子集)。
- 尝试不同的presets。
- 设置HyperParameters
硬盘空间不够怎么办
- 删除之前保存过模型的文件夹
- 调用predictor.save_space()来删除fit生成的中间文件
- 只保留最优模型,调用语句
predictor.delete_models(models_to_keep='best', dry_run=False)
- 把optimize_for_deployment加到presets 中
当然,降低磁盘空间的同时,也会使模型的搭建倾向于准确率略小,实际上这是一个时间空间与准确率的权衡
写在后面
大概通过这两篇的写作,我好像对这个模块有一个大致的了解了,接下来看下它对于kaggle竞赛项目的指导作用后,我就要转战第二部分图像预测
部分了,希望我的小破电脑能hold住