潍坊做网站好看,网站推广优化方式,官方网站投诉平台,wdcp拒绝访问网站#x1f44b; 工具系列#xff1a;PyCaret介绍_多分类代码示例
PyCaret 介绍
PyCaret是一个开源的、低代码的Python机器学习库#xff0c;可以自动化机器学习工作流程。它是一个端到端的机器学习和模型管理工具#xff0c;可以大大加快实验周期并提高生产效率。
与其他开… 工具系列PyCaret介绍_多分类代码示例
PyCaret 介绍
PyCaret是一个开源的、低代码的Python机器学习库可以自动化机器学习工作流程。它是一个端到端的机器学习和模型管理工具可以大大加快实验周期并提高生产效率。
与其他开源机器学习库相比PyCaret是一个替代低代码库可以用几行代码代替数百行代码。这使得实验速度指数级增加效率更高。PyCaret本质上是围绕几个机器学习库和框架如scikit-learn、XGBoost、LightGBM、CatBoost、spaCy、Optuna、Hyperopt、Ray等的Python封装。
PyCaret的设计和简洁性受到了Gartner首次使用的公民数据科学家这一新兴角色的启发。公民数据科学家是能够执行简单和中等复杂的分析 任务的高级用户而以前这些任务需要更多的技术专长。
# 导入pycaret库
import pycaret# 打印pycaret库的版本号
pycaret.__version__3.0.0快速开始
PyCaret的分类模块是一个监督式机器学习模块用于将元素分类到不同的组中。其目标是预测离散且无序的分类标签。
一些常见的用例包括预测客户是否违约是或否、预测客户流失客户会离开还是留下以及发现的疾病阳性或阴性。
该模块可用于二分类或多分类问题。它提供了几种预处理功能通过设置函数来准备建模数据。它拥有超过18种可直接使用的算法和多个绘图功能用于分析训练模型的性能。
在PyCaret中典型的工作流程按照以下5个步骤顺序进行
设置 ➡️ 比较模型 ➡️ 分析模型 ➡️ 预测 ➡️ 保存模型
# 从pycaret数据集模块加载示例数据集
from pycaret.datasets import get_data
data get_data(iris)设置
此函数初始化训练环境并创建转换流水线。在执行PyCaret中的任何其他函数之前必须调用设置函数。它只有两个必需的参数即data和target。所有其他参数都是可选的。
# 导入pycaret分类模块和初始化设置
from pycaret.classification import *# 初始化设置
# data: 数据集包含特征和目标变量
# target: 目标变量的名称
# session_id: 用于重现实验结果的随机种子
s setup(data, targetspecies, session_id123)一旦设置成功执行它将显示包含实验级别信息的信息网格。
会话ID 一个伪随机数在所有函数中分布为种子以便以后可以重现。如果没有传递session_id则会自动生成一个随机数并分发给所有函数。 目标类型 二进制、多类别或回归。目标类型会自动检测。 标签编码 当目标变量为字符串类型例如’Yes’或’No’而不是1或0时它会自动将标签编码为1和0并显示映射关系0No1Yes供参考。在本教程中不需要进行标签编码因为目标变量是数值类型。 原始数据形状 在进行任何转换之前的原始数据形状。 转换后的训练集形状 转换后的训练集形状。 转换后的测试集形状 转换后的测试集形状。 数值特征 被视为数值的特征数量。 分类特征 被视为分类的特征数量。
PyCaret的API
PyCaret有两套可以使用的API。 (1) 函数式API如上所示和 (2) 面向对象的API。
使用面向对象的API时您将导入一个类并执行该类的方法而不是直接执行函数。
# 导入ClassificationExperiment类并初始化该类
from pycaret.classification import ClassificationExperiment
exp ClassificationExperiment()# 检查exp的类型pycaret.classification.oop.ClassificationExperiment# 初始化实验设置
exp.setup(data, targetspecies, session_id123)
# data: 数据集用于训练和测试模型
# target: 目标变量即要预测的变量
# session_id: 实验的会话ID用于复现实验结果pycaret.classification.oop.ClassificationExperiment at 0x22362e4bd00你可以使用任何一种方法即函数式或面向对象编程并且可以在两组API之间来回切换。方法的选择不会影响结果并且已经进行了一致性测试。
比较模型
该函数使用交叉验证训练和评估模型库中所有可用的估计器的性能。该函数的输出是一个带有平均交叉验证分数的评分表。可以使用get_metrics函数访问CV期间评估的指标。可以使用add_metric和remove_metric函数添加或删除自定义指标。
# 比较基准模型# 使用compare_models()函数比较不同的基准模型并返回最佳模型best compare_models()Processing: 0%| | 0/69 [00:00?, ?it/s]# 比较模型
exp.compare_models()Processing: 0%| | 0/69 [00:00?, ?it/s]注意函数式API和面向对象API之间的输出是一致的。本笔记本中的其余函数将只使用函数式API显示。
分析模型
您可以使用plot_model函数来分析训练模型在测试集上的性能。在某些情况下可能需要重新训练模型。
# 调用函数绘制混淆矩阵
plot_confusion_matrix(best)# 绘制AUC曲线
# 参数best是训练好的模型
# 参数plotauc表示绘制AUC曲线
plot_model(best, plotauc)# 绘制特征重要性图
# best是训练好的模型
# plot参数设置为feature表示绘制特征重要性图
plot_model(best, plotfeature)# 使用help函数查看plot_model函数的文档字符串以了解可用的绘图选项
help(plot_model)Help on function plot_model in module pycaret.classification.functional:plot_model(estimator, plot: str auc, scale: float 1, save: bool False, fold: Union[int, Any, NoneType] None, fit_kwargs: Union[dict, NoneType] None, plot_kwargs: Union[dict, NoneType] None, groups: Union[str, Any, NoneType] None, verbose: bool True, display_format: Union[str, NoneType] None) - Union[str, NoneType]This function analyzes the performance of a trained model on holdout set.It may require re-training the model in certain cases.Example------- from pycaret.datasets import get_data juice get_data(juice) from pycaret.classification import * exp_name setup(data juice, target Purchase) lr create_model(lr) plot_model(lr, plot auc)estimator: scikit-learn compatible objectTrained model objectplot: str, default aucList of available plots (ID - Name):* pipeline - Schematic drawing of the preprocessing pipeline* auc - Area Under the Curve* threshold - Discrimination Threshold* pr - Precision Recall Curve* confusion_matrix - Confusion Matrix* error - Class Prediction Error* class_report - Classification Report* boundary - Decision Boundary* rfe - Recursive Feature Selection* learning - Learning Curve* manifold - Manifold Learning* calibration - Calibration Curve* vc - Validation Curve* dimension - Dimension Learning* feature - Feature Importance* feature_all - Feature Importance (All)* parameter - Model Hyperparameter* lift - Lift Curve* gain - Gain Chart* tree - Decision Tree* ks - KS Statistic Plotscale: float, default 1The resolution scale of the figure.save: bool, default FalseWhen set to True, plot is saved in the current working directory.fold: int or scikit-learn compatible CV generator, default NoneControls cross-validation. If None, the CV generator in the fold_strategyparameter of the setup function is used. When an integer is passed,it is interpreted as the n_splits parameter of the CV generator in thesetup function.fit_kwargs: dict, default {} (empty dict)Dictionary of arguments passed to the fit method of the model.plot_kwargs: dict, default {} (empty dict)Dictionary of arguments passed to the visualizer class.- pipeline: fontsize - intgroups: str or array-like, with shape (n_samples,), default NoneOptional group labels when GroupKFold is used for the cross validation.It takes an array with shape (n_samples, ) where n_samples is the numberof rows in training dataset. When string is passed, it is interpreted asthe column name in the dataset containing group labels.verbose: bool, default TrueWhen set to False, progress bar is not displayed.display_format: str, default NoneTo display plots in Streamlit (https://www.streamlit.io/), set this to streamlit.Currently, not all plots are supported.Returns:Path to saved file, if any.Warnings--------- Estimators that does not support predict_proba attribute cannot be used forAUC and calibration plots.- When the target is multiclass, calibration, threshold, manifold and rfeplots are not available.- When the max_features parameter of a trained model object is not equal tothe number of samples in training set, the rfe plot is not available.一种替代plot_model函数的方法是evaluate_model。它只能在Notebook中使用因为它使用了ipywidget。
evaluate_model(best)interactive(children(ToggleButtons(descriptionPlot Type:, icons(,), options((Pipeline Plot, pipelin…预测
predict_model 函数会在数据框中返回 prediction_label 和 prediction_score预测类别的概率作为新的列。当数据为 None默认值时它会使用在设置函数期间创建的测试集进行评分。
# 预测测试集数据
# 使用之前训练好的模型对测试集数据进行预测
holdout_pred predict_model(best)# 展示预测结果的数据框# 使用head()函数显示数据框的前几行默认显示前5行holdout_pred.head()相同的函数可以用于预测未见数据集上的标签。让我们创建原始数据的副本并删除“Class变量”。然后我们可以使用没有标签的新数据框进行评分。
# 复制数据并删除Class变量# 复制原始数据到新的数据集new_data
new_data data.copy()# 在新数据集new_data中删除species列axis1表示按列删除
new_data.drop(species, axis1, inplaceTrue)# 显示新数据集new_data的前几行数据
new_data.head()# 使用预训练的模型对新数据进行预测
predictions predict_model(best, datanew_data)# 显示预测结果的前几行
predictions.head()保存模型
最后您可以使用pycaret的save_model函数将整个流水线保存到磁盘上以供以后使用。
# 调用save_model函数将最佳模型保存为名为my_first_pipeline的文件
save_model(best, my_first_pipeline)Transformation Pipeline and Model Successfully Saved(Pipeline(memoryFastMemory(locationC:\Users\owner\AppData\Local\Temp\joblib),steps[(label_encoding,TransformerWrapperWithInverse(excludeNone, includeNone,transformerLabelEncoder())),(numerical_imputer,TransformerWrapper(excludeNone,include[sepal_length, sepal_width,petal_length, petal_width],transformerSimpleImputer(add_indicatorF...fill_valueNone,missing_valuesnan,strategymost_frequent,verbosedeprecated))),(trained_model,LogisticRegression(C1.0, class_weightNone, dualFalse,fit_interceptTrue, intercept_scaling1,l1_ratioNone, max_iter1000,multi_classauto, n_jobsNone,penaltyl2, random_state123,solverlbfgs, tol0.0001, verbose0,warm_startFalse))],verboseFalse),my_first_pipeline.pkl)# 加载模型
loaded_best_pipeline load_model(my_first_pipeline)# 加载已经训练好的最佳模型# 返回已加载的最佳模型的结果Transformation Pipeline and Model Successfully Loaded详细的函数功能概述
✅ 设置
这个函数在PyCaret中初始化实验并根据传入函数的所有参数创建转换流水线。在执行任何其他函数之前必须调用设置函数。它接受两个必需参数data和target。所有其他参数都是可选的并用于配置数据预处理流水线。 # 设置数据集和目标变量
# data: 数据集
# target: 目标变量即要预测的变量
# session_id: 用于重现实验结果的随机种子
s setup(data, targetspecies, session_id123)要访问由设置函数创建的所有变量例如转换后的数据集、随机状态等您可以使用get_config方法。
# 获取所有可用的配置信息
get_config(){USI,X,X_test,X_test_transformed,X_train,X_train_transformed,X_transformed,_available_plots,_ml_usecase,data,dataset,dataset_transformed,exp_id,exp_name_log,fix_imbalance,fold_generator,fold_groups_param,fold_shuffle_param,gpu_n_jobs_param,gpu_param,html_param,idx,is_multiclass,log_plots_param,logging_param,memory,n_jobs_param,pipeline,seed,target_param,test,test_transformed,train,train_transformed,variable_and_property_keys,variables,y,y_test,y_test_transformed,y_train,y_train_transformed,y_transformed}# 获取X_train_transformed的配置信息
get_config(X_train_transformed)# 打印当前的种子值
print(当前的种子值为: {}.format(get_config(seed)))# 使用set_config函数来改变种子值
set_config(seed, 786)
print(新的种子值为: {}.format(get_config(seed)))The current seed is: 123
The new seed is: 786所有的预处理配置和实验设置/参数都传递给setup函数。要查看所有可用的参数请检查docstring
# help(setup)# 初始化设置设置normalize为True
# 参数data为数据集target为目标变量的名称session_id为随机种子normalize为是否对数据进行归一化处理normalize_method为归一化方法
s setup(data, targetspecies, session_id123, normalizeTrue, normalize_methodminmax)# 获取X_train_transformed的配置信息并查看sepal_length列的直方图# 使用get_config函数获取X_train_transformed的配置信息
config get_config(X_train_transformed)# 获取sepal_length列并绘制直方图
config[sepal_length].hist()AxesSubplot:请注意所有的值都在0和1之间 - 这是因为我们在setup函数中传递了normalizeTrue。如果你不记得它与实际数据的比较方式没问题 - 我们也可以使用get_config来访问非转换的值然后进行比较。请参见下面的内容并注意x轴上的值范围并将其与上面的直方图进行比较。
# 获取配置文件中的X_train数据集并选择其中的sepal_length列
X_train get_config(X_train)[sepal_length]# 绘制sepal_length列的直方图
X_train.hist()AxesSubplot:✅ 比较模型
该函数使用交叉验证训练和评估模型库中所有可用的估计器的性能。该函数的输出是一个带有平均交叉验证分数的评分网格。可以使用get_metrics函数访问CV期间评估的指标。可以使用add_metric和remove_metric函数添加或删除自定义指标。
# 比较模型函数用于选择最佳模型
best compare_models()Processing: 0%| | 0/69 [00:00?, ?it/s]compare_models 默认使用模型库中的所有估计器除了 TurboFalse 的模型。要查看所有可用的模型您可以使用函数 models()。
# 使用transformers库中的models()函数来获取可用的模型列表
available_models models()# 打印可用的模型列表
print(available_models)你可以在compare_models中使用include和exclude参数只训练选择的模型或通过在exclude参数中传递模型id来排除特定的模型。
# 使用compare_models函数比较不同的决策树模型
# include参数指定了要比较的模型包括决策树dt、随机森林rf、极端随机树et、梯度提升树gbc、XGBoostxgboost、LightGBMlightgbm和CatBoostcatboost
compare_tree_models compare_models(include[dt, rf, et, gbc, xgboost, lightgbm, catboost])Processing: 0%| | 0/33 [00:00?, ?it/s]compare_tree_models功能上面的函数返回训练好的模型对象作为输出。评分网格只显示不返回。如果您需要访问评分网格可以使用pull函数访问数据框。
# 从数据源中获取比较树模型结果的数据compare_tree_models_results pull()默认情况下compare_models函数返回基于sort参数中定义的指标的最佳性能模型。让我们修改我们的代码返回基于Recall的前3个最佳模型。
# 使用compare_models函数来比较不同模型的性能
# sort参数设置为Recall表示按照召回率对模型进行排序
# n_select参数设置为3表示选择召回率最高的3个模型
best_recall_models_top3 compare_models(sortRecall, n_select3)Processing: 0%| | 0/71 [00:00?, ?it/s]# 定义一个列表用于存储前三个Recall最高的模型的名称
best_recall_models_top3[QuadraticDiscriminantAnalysis(priorsNone, reg_param0.0,store_covarianceFalse, tol0.0001),LinearDiscriminantAnalysis(covariance_estimatorNone, n_componentsNone,priorsNone, shrinkageNone, solversvd,store_covarianceFalse, tol0.0001),KNeighborsClassifier(algorithmauto, leaf_size30, metricminkowski,metric_paramsNone, n_jobs-1, n_neighbors5, p2,weightsuniform)]一些在compare_models中可能非常有用的其他参数包括
foldcross_validationbudget_timeerrorsprobability_thresholdparallel
您可以查看函数的文档字符串以获取更多信息。
# help(compare_models)✅ 实验日志记录
PyCaret与许多不同类型的实验记录器集成默认为’mlflow’。要在PyCaret中启用实验跟踪您可以设置log_experiment和experiment_name参数。它将根据定义的记录器自动跟踪所有指标、超参数和工件。
# 设置实验
# data: 数据集
# target: 目标变量
# log_experiment: 是否记录实验日志到mlflow
# experiment_name: 实验名称
s setup(data, targetClass variable, log_experimentmlflow, experiment_nameiris_experiment)# 比较模型# 使用compare_models()函数来比较不同的模型找出最佳的模型best compare_models()# start mlflow server on localhost:5000
# !mlflow ui默认情况下PyCaret使用MLFlow记录器可以使用log_experiment参数进行更改。以下记录器可用
mlflowwandbcomet_mldagshub
您可能会发现有用的其他与日志记录相关的参数有
experiment_custom_tagslog_plotslog_datalog_profile
有关更多信息请查看setup函数的文档字符串。
# help(setup)✅ 创建模型
该函数使用交叉验证训练和评估给定估计器的性能。该函数的输出是一个包含每个折叠的CV分数的评分网格。可以使用get_metrics函数访问CV期间评估的指标。可以使用add_metric和remove_metric函数添加或删除自定义指标。可以使用models函数访问所有可用的模型。
# 查看所有可用的模型
models()# 使用默认的折叠数fold10训练逻辑回归模型
lr create_model(lr)Processing: 0%| | 0/4 [00:00?, ?it/s]功能以上返回训练好的模型对象作为输出。评分表格仅显示而不返回。如果您需要访问评分表格可以使用pull函数来访问数据框。
# 从pull()函数中获取lr_results变量的值
lr_results pull()# 打印lr_results的数据类型
print(type(lr_results))# 打印lr_results的值
print(lr_results)class pandas.core.frame.DataFrame# 创建一个逻辑回归模型并设置交叉验证的折数为3
lr create_model(lr, fold3)Processing: 0%| | 0/4 [00:00?, ?it/s]# 定义一个函数create_model用于训练逻辑回归模型并设置特定的模型参数
# 参数说明
# - model_type: 模型类型这里为逻辑回归模型使用缩写lr表示
# - C: 正则化强度的倒数用于控制模型的复杂度数值越小表示正则化强度越大默认为0.5
# - l1_ratio: L1正则化的比例用于控制L1正则化的强度数值越大表示L1正则化的强度越大默认为0.15
create_model(model_type, C0.5, l1_ratio0.15): Processing: 0%| | 0/4 [00:00?, ?it/s]# 定义一个函数create_model用于训练逻辑回归模型并返回训练得分和交叉验证得分
create_model(lr, return_train_scoreTrue)Processing: 0%| | 0/4 [00:00?, ?it/s]一些在create_model中可能非常有用的其他参数有
cross_validationenginefit_kwargsgroups
您可以查看函数的文档字符串以获取更多信息。
# help(create_model)✅ 调整模型
该函数用于调整模型的超参数。该函数的输出是一个通过交叉验证得到的得分网格。根据 optimize 参数中定义的指标选择最佳模型。可以使用 get_metrics 函数访问在交叉验证期间评估的指标。可以使用 add_metric 和 remove_metric 函数添加或删除自定义指标。 # 使用默认参数创建一个决策树模型
dt create_model(dt)Processing: 0%| | 0/4 [00:00?, ?it/s]# 调整决策树模型的超参数# 使用tune_model函数对决策树模型进行超参数调整并将调整后的模型保存在tuned_dt变量中。
tuned_dt tune_model(dt)Processing: 0%| | 0/7 [00:00?, ?it/s]Fitting 10 folds for each of 10 candidates, totalling 100 fits可以在optimize参数中定义要优化的度量标准默认为’Accuracy’。此外还可以通过custom_grid参数传递自定义调整的网格。
dt# 定义调参网格
dt_grid {max_depth : [None, 2, 4, 6, 8, 10, 12]}# 使用自定义网格和优化指标为F1来调整模型
tuned_dt tune_model(dt, custom_grid dt_grid, optimize F1)Processing: 0%| | 0/7 [00:00?, ?it/s]Fitting 10 folds for each of 7 candidates, totalling 70 fits# 使用tune_model函数对决策树模型进行调参
# 返回调参后的决策树模型和调参器对象
tuned_dt, tuner tune_model(dt, return_tunerTrue)# 注意为了访问调参器对象需要将return_tuner参数设置为TrueProcessing: 0%| | 0/7 [00:00?, ?it/s]Fitting 10 folds for each of 10 candidates, totalling 100 fits# 创建一个决策树模型对象tuned_dt# 创建一个tuner对象# tuner object
tuner默认的搜索算法是sklearn中的RandomizedSearchCV。可以通过使用search_library和search_algorithm参数来进行更改。
# 使用Optuna库来调整决策树模型dt
# 调整后的模型保存在tuned_dt中
tuned_dt tune_model(dt, search_libraryoptuna)Processing: 0%| | 0/7 [00:00?, ?it/s][32m[I 2023-02-16 14:39:11,277][0m Searching the best hyperparameters using 105 samples...[0m
[32m[I 2023-02-16 14:39:18,586][0m Finished hyperparemeter search![0m有关所有可用的search_library和search_algorithm的更多详细信息请查看docstring。在tune_model中您可能会发现一些其他非常有用的参数
choose_bettern_iterearly_stoppinggroups
您可以查看函数的docstring以获取更多信息。
# help(tune_model)✅ 集成模型
该函数对给定的估计器进行集成。该函数的输出是一个包含按折叠计算的CV分数的评分网格。可以使用get_metrics函数访问在CV期间评估的指标。可以使用add_metric和remove_metric函数添加或删除自定义指标。
# 使用Bagging方法对决策树模型dt进行集成
ensemble_model(dt, methodBagging)Processing: 0%| | 0/6 [00:00?, ?it/s]# 调用ensemble_model函数传入决策树模型dt和方法参数为Boosting
ensemble_model(dt, methodBoosting)Processing: 0%| | 0/6 [00:00?, ?it/s]一些在ensemble_model中可能非常有用的其他参数包括
choose_bettern_estimatorsgroupsfit_kwargsprobability_thresholdreturn_train_score
您可以查看函数的文档字符串以获取更多信息。
# help(ensemble_model)✅ 混合模型
该函数用于训练一个软投票/多数规则分类器该分类器选择在estimator_list参数中传递的模型。该函数的输出是一个带有交叉验证分数的评分网格。可以使用get_metrics函数访问在CV期间评估的指标。可以使用add_metric和remove_metric函数添加或删除自定义指标。
# 定义一个变量best_recall_models_top3用于存储基于召回率的前三个模型的信息
best_recall_models_top3[QuadraticDiscriminantAnalysis(priorsNone, reg_param0.0,store_covarianceFalse, tol0.0001),LinearDiscriminantAnalysis(covariance_estimatorNone, n_componentsNone,priorsNone, shrinkageNone, solversvd,store_covarianceFalse, tol0.0001),KNeighborsClassifier(algorithmauto, leaf_size30, metricminkowski,metric_paramsNone, n_jobs-1, n_neighbors5, p2,weightsuniform)]# blend_models函数用于将最佳召回率的前三个模型进行融合# 参数best_recall_models_top3是一个包含最佳召回率的前三个模型的列表# 代码调用blend_models函数并传入参数best_recall_models_top3将返回值赋给变量blend_modelsblend_models(best_recall_models_top3)Processing: 0%| | 0/6 [00:00?, ?it/s]一些在blend_models中可能非常有用的其他参数包括
choose_bettermethodweightsfit_kwargsprobability_thresholdreturn_train_score
您可以查看函数的文档字符串以获取更多信息。
# help(blend_models)✅ 堆叠模型
该函数在estimator_list参数中传递的选择的估计器上训练一个元模型。该函数的输出是一个包含每个折叠的CV分数的评分网格。可以使用get_metrics函数访问CV期间评估的指标。可以使用add_metric和remove_metric函数添加或删除自定义指标。
# stack_models函数用于堆叠多个模型# 参数
# best_recall_models_top3一个包含了最佳召回率的前三个模型的列表# 算法流程
# 1. 创建一个新的模型用于堆叠多个模型
# 2. 将best_recall_models_top3列表中的模型添加到新的模型中
# 3. 返回堆叠后的模型
stack_models(best_recall_models_top3)Processing: 0%| | 0/6 [00:00?, ?it/s]一些在stack_models中可能非常有用的其他参数包括
choose_bettermeta_modelmethodrestackprobability_thresholdreturn_train_score
您可以查看函数的文档字符串以获取更多信息。
# help(stack_models)✅ 绘制模型
功能说明
该函数用于分析在保留集上训练模型的性能。在
# plot class report
plot_model(best, plot class_report)# 绘制模型的分类报告图表
# 参数best表示要绘制的模型
# 参数plot表示要绘制的图表类型这里选择分类报告图表
# 参数scale表示图表的缩放比例这里选择缩放比例为2
plot_model(best, plotclass_report, scale2)# 导入所需的库
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report# 绘制分类报告图表并保存
# 参数best为模型对象
# 参数plot为要绘制的图表类型这里选择class_report表示绘制分类报告图表
# 参数save为是否保存图表这里设置为True表示保存图表
plot_model(best, plot class_report, saveTrue)
Class Report.png一些在plot_model中可能非常有用的其他参数包括
fit_kwargsplot_kwargsgroupsdisplay_format
您可以查看函数的文档字符串以获取更多信息。
# help(plot_model)✅ 解释模型
该函数分析训练模型生成的预测结果。该函数中的大多数图表是基于SHAPShapley Additive exPlanations实现的。有关更多信息请参阅https://shap.readthedocs.io/en/latest/
# 使用lightgbm算法创建一个分类模型
lightgbm create_model(lightgbm)Processing: 0%| | 0/4 [00:00?, ?it/s]# 使用interpret_model函数对模型进行解释
# 参数lightgbm表示使用的模型是lightgbm模型
# 参数plot表示是否绘制模型的摘要图默认为True
interpret_model(lightgbm, plotsummary)# 使用interpret_model函数来解释lightgbm模型
# 参数plotreason表示绘制解释图表observation1表示解释测试集中的第一个观察值
interpret_model(lightgbm, plotreason, observation1)一些在interpret_model中可能非常有用的其他参数包括
plotfeatureuse_train_dataX_new_sampley_new_samplesave
您可以查看函数的文档字符串以获取更多信息。
# help(interpret_model)✅ 获取排行榜
该函数返回当前设置中所有训练模型的排行榜。
# 获取排行榜
lb get_leaderboard()
lbProcessing: 0%| | 0/58 [00:00?, ?it/s]# 根据F1值选择最佳模型
# 使用sort_values方法对数据框lb按照F1列进行降序排序
# 使用[Model]索引获取排序后的数据框的Model列
# 使用iloc[0]获取排序后的Model列的第一个元素即F1值最高的模型名称
lb.sort_values(byF1, ascendingFalse)[Model].iloc[0]一些在get_leaderboard中可能非常有用的其他参数包括
finalize_modelsfit_kwargsmodel_onlygroups
您可以查看函数的docstring以获取更多信息。
# help(get_leaderboard)✅ AutoML
该函数根据优化参数返回当前设置中所有训练模型中的最佳模型。可以使用get_metrics函数访问评估的指标。
automl()✅ 仪表盘
仪表盘功能用于为训练模型生成交互式仪表盘。该仪表盘是使用ExplainerDashboard实现的。更多信息请查看Explainer Dashboard.
# 定义一个名为dashboard的函数
# 参数dt表示数据表display_format表示显示格式默认为inline# 函数功能用于显示数据表的仪表板# 参数说明
# - dt: 数据表即要显示的数据
# - display_format: 显示格式可以是inline或者其他格式默认为inline# 返回值无# 代码实现
# 通过调用dashboard函数可以将数据表以指定的显示格式显示在仪表板上。默认情况下数据表以inline格式显示。
dashboard(dt, display_format inline)Note: model_outputprobability, so assuming that raw shap output of DecisionTreeClassifier is in probability space...
Generating self.shap_explainer shap.TreeExplainer(model)
Building ExplainerDashboard..
The explainer object has no decision_trees property. so setting decision_treesFalse...
Warning: calculating shap interaction values can be slow! Pass shap_interactionFalse to remove interactions tab.
Generating layout...
Calculating shap values...
Calculating prediction probabilities...
Calculating metrics...
Calculating confusion matrices...
Calculating classification_dfs...
Calculating roc auc curves...
Calculating pr auc curves...
Calculating liftcurve_dfs...
Calculating shap interaction values... (this may take a while)
Reminder: TreeShap computational complexity is O(TLD^2), where T is the number of trees, L is the maximum number of leaves in any tree and D the maximal depth of any tree. So reducing these will speed up the calculation.
Calculating dependencies...
Calculating permutation importances (if slow, try setting n_jobs parameter)...
Calculating pred_percentiles...
Calculating predictions...
Reminder: you can store the explainer (including calculated dependencies) with explainer.dump(explainer.joblib) and reload with e.g. ClassifierExplainer.from_file(explainer.joblib)
Registering callbacks...
Starting ExplainerDashboard inline (terminate it with ExplainerDashboard.terminate(8050))✅创建应用程序
此函数创建一个用于推理的基本 gradio 应用程序。
# 创建一个Gradio应用# 参数
# - best: 一个模型或函数用于处理输入并生成输出create_app(best) # 调用create_app函数传入参数best用于创建一个Gradio应用Running on local URL: http://127.0.0.1:7860To create a public link, set shareTrue in launch().✅ 创建API
该函数接受一个输入模型并创建一个用于推理的POST API。
# 创建API
# 参数
# - best: 最佳模型
# - api_name: API的名称默认为my_first_api
create_api(best, api_namemy_first_api)API successfully created. This function only creates a POST API, it doesnt run it automatically. To run your API, please run this command -- !python my_first_api.py# 导入必要的库
from flask import Flask, request, jsonify# 创建一个Flask应用
app Flask(__name__)# 创建一个路由用于处理POST请求
app.route(/api, methods[POST])
def my_api():# 获取请求中的数据data request.get_json()# 从请求数据中获取名字name data[name]# 从请求数据中获取年龄age data[age]# 计算出出生年份birth_year 2021 - int(age)# 构建响应数据response {name: name,birth_year: birth_year}# 返回响应数据return jsonify(response)# 运行应用
if __name__ __main__:app.run()# 导入必要的库
import flask
from flask import request, jsonify# 创建一个Flask应用
app flask.Flask(__name__)# 设置应用的路由
app.route(/, methods[GET])
def home():return h1Welcome to my first API!/h1# 设置应用的路由
app.route(/api, methods[GET])
def api():# 创建一个字典data {name: John, age: 30, city: New York}# 将字典转换为JSON格式return jsonify(data)# 运行应用
if __name__ __main__:app.run(debugTrue)✅ 创建Docker
该函数用于创建用于将API端点投入生产的Dockerfile和requirements.txt文件。
# 定义一个函数create_docker用于创建一个名为my_first_api的Docker容器
def create_docker(name):# 导入所需的模块import docker# 创建一个Docker客户端对象client docker.from_env()# 检查是否存在同名的容器if name in [container.name for container in client.containers.list()]:# 如果存在同名容器则打印提示信息并返回print(容器已存在)return# 创建一个新的容器container client.containers.create(imageubuntu:latest, # 使用最新版本的Ubuntu镜像namename, # 设置容器的名称为传入的参数namedetachTrue # 在后台运行容器)# 启动容器container.start()# 打印容器的ID和名称print(f容器ID: {container.id})print(f容器名称: {container.name})Writing requirements.txt
Writing Dockerfile
Dockerfile and requirements.txt successfully created.To build image you have to run -- !docker image build -f Dockerfile -t IMAGE_NAME:IMAGE_TAG .# 检查使用魔术命令创建的DockerFile文件# 指定基础镜像为python:3.7
FROM python:3.7# 设置工作目录为/app
WORKDIR /app# 将当前目录下的所有文件复制到/app目录下
COPY . /app# 安装依赖包
RUN pip install -r requirements.txt# 设置环境变量
ENV FLASK_APPapp.py# 暴露容器的端口号
EXPOSE 5000# 运行flask应用
CMD [flask, run, --host0.0.0.0]# 检查使用魔术命令创建的requirements.txt文件# 导入所需的模块
import os
import subprocess# 定义一个函数用于检查requirements.txt文件是否存在
def check_requirements_file():# 检查当前目录下是否存在requirements.txt文件if os.path.exists(requirements.txt):print(requirements.txt文件已存在)else:print(requirements.txt文件不存在)# 定义一个函数用于安装requirements.txt文件中列出的所有依赖项
def install_requirements():# 检查当前目录下是否存在requirements.txt文件if os.path.exists(requirements.txt):# 使用subprocess模块执行命令安装requirements.txt文件中列出的所有依赖项subprocess.call([pip, install, -r, requirements.txt])print(所有依赖项已成功安装)else:print(requirements.txt文件不存在无法安装依赖项)# 调用函数检查requirements.txt文件是否存在
check_requirements_file()# 调用函数安装requirements.txt文件中列出的所有依赖项
install_requirements()✅ 完善模型
该函数在整个数据集上训练给定的模型包括保留集。
# 将模型进行最终化处理
final_best finalize_model(best)# 定义一个变量final_best用于存储最终的最佳结果final_best None✅ 转换模型
该函数将训练好的机器学习模型的决策函数转换为不同的编程语言如Python、C、Java、Go、C#等。如果您想要将模型部署到无法安装正常Python堆栈以支持模型推断的环境中这非常有用。
# 将学习到的函数转换为Java代码
# 调用convert_model函数将决策树模型(dt)转换为Java代码
# 设置language参数为java表示转换为Java语言的代码
# 打印输出转换后的Java代码结果public class Model {public static double[] score(double[] input) {double[] var0;if (input[2] 0.23275858908891678) {var0 new double[] {1.0, 0.0, 0.0};} else {if (input[2] 0.62931028008461) {if (input[0] 0.180555522441864) {var0 new double[] {0.0, 0.0, 1.0};} else {var0 new double[] {0.0, 1.0, 0.0};}} else {if (input[2] 0.6637930274009705) {if (input[1] 0.3958333134651184) {var0 new double[] {0.0, 0.0, 1.0};} else {var0 new double[] {0.0, 1.0, 0.0};}} else {if (input[3] 0.6666666269302368) {if (input[3] 0.6041666567325592) {var0 new double[] {0.0, 0.0, 1.0};} else {if (input[0] 0.6388888359069824) {var0 new double[] {0.0, 1.0, 0.0};} else {var0 new double[] {0.0, 0.0, 1.0};}}} else {var0 new double[] {0.0, 0.0, 1.0};}}}}return var0;}
}✅ 部署模型
此函数在云上部署整个机器学习流程。
AWS: 在AWS S3上部署模型时必须使用命令行界面配置环境变量。要配置AWS环境变量请在终端中输入aws configure命令。以下信息是必需的可以使用您的Amazon控制台帐户的身份和访问管理IAM门户生成
AWS访问密钥IDAWS秘密密钥访问默认区域名称可以在AWS控制台的全局设置下看到默认输出格式必须留空
GCP: 要在Google Cloud Platform‘gcp’上部署模型必须使用命令行或GCP控制台创建项目。创建项目后您必须创建一个服务帐户并将服务帐户密钥下载为JSON文件以在本地环境中设置环境变量。了解更多信息https://cloud.google.com/docs/authentication/production
Azure: 要在Microsoft Azure‘azure’上部署模型必须在本地环境中设置用于连接字符串的环境变量。转到Azure门户上的存储帐户设置以访问所需的连接字符串。 AZURE_STORAGE_CONNECTION_STRING作为环境变量必需 了解更多信息https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python?toc%2Fpython%2Fazure%2FTOC.json
# 在AWS S3上部署模型
# 部署模型函数deploy_model()用于将模型部署到AWS S3上
# 参数best表示要部署的模型
# 参数model_name表示在AWS上部署的模型的名称这里设置为my_first_platform_on_aws
# 参数platform表示要部署到的平台这里设置为aws
# 参数authentication是一个字典用于身份验证
# 字典中的bucket表示要部署到的AWS S3存储桶的名称这里设置为pycaret-test# 从AWS S3加载模型
# 从AWS S3加载名为my_first_platform_on_aws的模型
# 使用AWS平台加载模型
# 鉴权信息为{bucket : pycaret-test}
# 加载模型并赋值给loaded_from_aws变量✅ 保存/加载模型
这个函数将转换流水线和训练好的模型对象保存到当前工作目录中以pickle文件的形式供以后使用。
# 保存模型
# 使用save_model函数将最佳模型保存为my_first_model文件Transformation Pipeline and Model Successfully Saved(Pipeline(memoryFastMemory(locationC:\Users\owner\AppData\Local\Temp\joblib),steps[(label_encoding,TransformerWrapperWithInverse(excludeNone, includeNone,transformerLabelEncoder())),(numerical_imputer,TransformerWrapper(excludeNone,include[sepal_length, sepal_width,petal_length, petal_width],transformerSimpleImputer(add_indicatorF...transformerSimpleImputer(add_indicatorFalse,copyTrue,fill_valueNone,missing_valuesnan,strategymost_frequent,verbosedeprecated))),(normalize,TransformerWrapper(excludeNone, includeNone,transformerMinMaxScaler(clipFalse,copyTrue,feature_range(0,1)))),(trained_model,QuadraticDiscriminantAnalysis(priorsNone, reg_param0.0,store_covarianceFalse,tol0.0001))],verboseFalse),my_first_model.pkl)# 加载模型
loaded_from_disk load_model(my_first_model) # 从磁盘上加载名为my_first_model的模型文件并将其存储在变量loaded_from_disk中
loaded_from_disk # 打印加载的模型Transformation Pipeline and Model Successfully Loaded✅ 保存/加载实验
该函数将实验中的所有变量保存在磁盘上以便以后恢复而无需重新运行设置函数。
# 保存实验
save_experiment(my_experiment)# 从磁盘加载实验
exp_from_disk load_experiment(my_experiment, datadata)本代码链接
https://download.csdn.net/download/wjjc1017/88643312