
Automl Skill
- 6 installs
- 1 repo stars
- Updated March 16, 2026
- yejinlei/automl-skill
Helps with ai & agent building tasks.
About
automl-skill is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- automl-skill
- AI & Agent Building
- AI-coding skill
Automl Skill by the numbers
- 6 all-time installs (skills.sh)
- Ranked #12,825 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 27, 2026 (Skillselion catalog sync)
npx skills add https://github.com/yejinlei/automl-skill --skill automl-skillAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 6 |
|---|---|
| repo stars | ★ 1 |
| Last updated | March 16, 2026 |
| Repository | yejinlei/automl-skill ↗ |
What it does
Helps with ai & agent building tasks.
Files
PyCaret AutoML 技能指南 | PyCaret AutoML Skill Guide
本技能帮助用户使用 PyCaret 快速构建端到端的机器学习工作流。PyCaret 是一个开源的低代码机器学习库,可以将数百行代码简化为几行。
This skill helps users build end-to-end machine learning workflows using PyCaret, an open-source low-code ML library that simplifies hundreds of lines of code into just a few lines.
核心功能 | Core Capabilities
- 自动化模型选择 - 自动比较多个模型并选择最佳模型
- 自动化超参数调优 - 使用 Optuna/Hyperopt 自动优化模型参数
- 自动化特征工程 - 自动进行数据预处理、特征转换和特征选择
- 模型集成 - 支持 Bagging、Boosting、Stacking、Blending
- 模型可解释性 - 支持 SHAP、Permutation Importance 等解释方法
- 模型部署就绪 - 生成可复现的生产级 Pipeline
- 统计推断增强 - 支持置信区间、假设检验、统计显著性分析
---
统计推断增强 | Statistical Enhancement (statsmodels)
当需要统计推断、假设检验、置信区间时,可以使用 statsmodels 补充 PyCaret:
线性回归模型
import statsmodels.api as sm
# OLS 回归(带统计显著性)
X = sm.add_constant(X) # 添加截距
model = sm.OLS(y, X).fit()
print(model.summary()) # R², F检验, P值, 置信区间广义线性模型 (GLM)
# 二项分布 GLM (Logistic 回归)
glm_model = sm.GLM(y, X, family=sm.families.Binomial()).fit()
# 泊松回归 (计数数据)
poisson_model = sm.GLM(y, X, family=sm.families.Poisson()).fit()假设检验
from scipy import stats
# t 检验
t_stat, p_value = stats.ttest_ind(group1, group2)
# 卡方检验
chi2, p_value, dof, expected = stats.chi2_contingency(contingency_table)
# ANOVA
f_stat, p_value = stats.f_oneway(*groups)时间序列分析
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.statespace.sarimax import SARIMAX
# ARIMA 模型
arima_model = ARIMA(train_data, order=(1,1,1)).fit()
forecast = arima_model.forecast(steps=12)
# 季节性 SARIMAX
sarimax_model = SARIMAX(data, order=(1,1,1), seasonal_order=(1,1,1,12)).fit()统计诊断
# 残差自相关检验 (Durbin-Watson)
from statsmodels.stats.stattools import durbin_watson
dw = durbin_watson(model.resid)
# 异方差检验
from statsmodels.stats.diagnostic import het_breuschpagan
bp_test = het_breuschpagan(model.resid, model.model.exog)
# 正态性检验
from scipy import stats
shapiro_stat, shapiro_p = stats.shapiro(model.resid)混合效应模型 (随机效应)
# 混合线性模型 (Panel Data / 多层次数据)
from statsmodels.regression.mixed_linear_model import MixedLM
mixed_model = MixedLM(y, X, groups=group_var).fit()PyCaret + statsmodels 组合使用
# 1. 用 PyCaret 快速建模和选择模型
from pycaret.classification import *
clf = setup(data, target='target')
best = compare_models()
tuned = tune_model(best)
# 2. 用 statsmodels 做统计推断
import statsmodels.api as sm
# 获取 PyCaret 模型的特征和预测
X_with_const = sm.add_constant(X_test)
sm_model = sm.Logit(y_test, X_with_const).fit(disp=0)
print(sm_model.summary()) # 系数显著性 P值---
支持的机器学习任务 | Supported ML Tasks
| 模块 | Module | 任务类型 | Task Type | 参考文档 |
|---|---|---|---|---|
| pycaret.classification | Classification | 二分类、多分类 | Binary, Multi-class | classification.md |
| pycaret.regression | Regression | 回归预测 | Regression | regression.md |
| pycaret.clustering | Clustering | 无监督聚类 | Unsupervised Clustering | clustering.md |
| pycaret.anomaly | Anomaly Detection | 异常检测 | Outlier Detection | anomaly.md |
| pycaret.time_series | Time Series | 时间序列预测 | Time Series Forecasting | time_series.md |
| pycaret.nlp | NLP | 文本分类、主题建模 | Text Classification, Topic Modeling | nlp.md |
| pycaret.arules | Association Rules | 关联规则挖掘 | Market Basket Analysis | association_rules.md |
---
快速开始 | Quick Start
1. 选择您的任务类型
根据您的机器学习任务,选择相应的模块:
- 分类问题 → 使用
pycaret.classification - 回归问题 → 使用
pycaret.regression - 客户分群 → 使用
pycaret.clustering - 异常检测 → 使用
pycaret.anomaly - 时间预测 → 使用
pycaret.time_series - 文本分析 → 使用
pycaret.nlp - 购物篮分析 → 使用
pycaret.arules
2. 标准 AutoML 工作流 | Standard AutoML Workflow
完整的 AutoML 工作流程包含以下步骤:
Step 1: 数据收集与加载 | Data Collection & Loading
# 数据加载
import pandas as pd
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
# 或使用 PyCaret 内置数据集
from pycaret.classification import get_data
data = get_data('breast_cancer')Step 2: 数据理解与探索 | Data Understanding & EDA
# 基本信息
print(f"数据形状: {data.shape}")
print(f"数据类型:\n{data.dtypes}")
# 缺失值分析
missing = data.isnull().sum()
missing_pct = (missing / len(data) * 100).round(2)
print(f"缺失值比例:\n{pd.concat([missing, missing_pct], axis=1)}")
# 目标变量分布
data['target'].value_counts()
# 数值特征统计
data.describe()Step 3: 数据预处理 | Data Preprocessing (setup 中自动完成)
# 初始化环境 - 数据预处理配置
clf = setup(
data,
target='target',
# ===== 缺失值处理 =====
numeric_imputation='mean', # 数值型: mean/median/mode/knn/iterative
categorical_imputation='mode', # 类别型: mode/constant
# ===== 异常值处理 =====
remove_outliers=True, # 移除异常值
outliers_method='iforest', # iforest/ee/lof
outliers_threshold=0.05, # 异常值比例
# ===== 类别不平衡处理 =====
fix_imbalance=True, # 处理类别不平衡
fix_imbalance_method='SMOTE', # SMOTE/ADASYN/RandomOverSampler
# ===== 数据类型指定 =====
numeric_features=['age', 'income', 'score'],
categorical_features=['city', 'gender', 'occupation'],
date_features=['Date', 'created_at'],
session_id=42
)Step 4: 特征工程 | Feature Engineering (setup 中自动完成)
clf = setup(
data,
target='target',
# ===== 特征缩放 =====
normalize=True, # 归一化
normalize_method='zscore', # zscore/minmax/maxabs/robust
# ===== 特征变换 =====
transformation=True, # 变换使数据更接近正态分布
transformation_method='yeo-johnson', # yeo-johnson/quantile
# ===== 特征选择 =====
feature_selection=True, # 特征选择
feature_selection_method='classic', # classic/univariate/sequential
n_features_to_select=0.2, # 选择20%最重要特征
# ===== 降维 =====
pca=True, # PCA降维
pca_method='linear', # linear/kernel/incremental
pca_components=0.95, # 保留95%方差
# ===== 多重共线性处理 =====
remove_multicollinearity=True,
multicollinearity_threshold=0.9,
# ===== 特征编码 =====
ordinal_features={'education': ['high_school', 'bachelor', 'master', 'phd']},
high_cardinality_features='frequency', # 处理高基数类别特征
# ===== 特征交互 =====
polynomial_features=True,
polynomial_degree=2,
# ===== 分箱(离散化) =====
bin_numeric_features=['age', 'income'],
session_id=42
)Step 5: 模型选择 | Model Selection
# 比较所有模型
best_model = compare_models()
# 指定模型列表比较
best_model = compare_models(include=['lr', 'rf', 'xgboost', 'catboost', 'lightgbm'])
# 快速模式(排除耗时模型)
best_model = compare_models(turbo=True)
# 按特定指标排序
best_model = compare_models(sort='F1') # 对于不平衡数据Step 6: 模型训练 | Model Training
# 创建模型
model = create_model('rf')
# 指定模型参数
model = create_model('xgboost', n_estimators=100, max_depth=5)Step 7: 超参数调优 | Hyperparameter Tuning
# 自动调优
tuned_model = tune_model(model)
# 自定义调优
tuned_model = tune_model(
model,
custom_grid={
'n_estimators': [100, 200, 300],
'max_depth': [3, 5, 7, None],
'learning_rate': [0.01, 0.1, 0.3]
},
optimize='Accuracy', # 分类: Accuracy/AUC/Recall/Precision/F1/MCC
# 回归: RMSE/MSE/MAE/R2/RMSLE/MAPE
choose_better=True, # 返回更好的模型
n_iter=50 # 迭代次数
)Step 8: 模型评估 | Model Evaluation
# 交互式评估
evaluate_model(tuned_model)
# 各种评估图表
plot_model(tuned_model, plot='auc') # ROC曲线
plot_model(tuned_model, plot='confusion_matrix') # 混淆矩阵
plot_model(tuned_model, plot='classification_report') # 分类报告
plot_model(tuned_model, plot='learning_curve') # 学习曲线
plot_model(tuned_model, plot='feature') # 特征重要性
plot_model(tuned_model, plot='residuals') # 残差图(回归)
plot_model(tuned_model, plot='error') # 预测误差
# 交叉验证结果
results = pull() # 获取当前实验结果Step 9: 模型解释 | Model Interpretation
# SHAP 解释
interpret_model(tuned_model)
# Permutation Importance
interpret_model(tuned_model, plot='correlation')
# 局部解释
interpret_model(tuned_model, plot='reason', observation=0)Step 10: 模型集成 | Model Ensemble
# Bagging
bagged = ensemble_model(tuned_model, method='Bagging')
# Boosting
boosted = ensemble_model(tuned_model, method='Boosting')
# 融合多个模型
blended = blend_models(
estimator_list=['lr', 'dt', 'rf', 'xgboost'],
method='soft', # soft/hard
weights=[1, 2, 3, 2] # 各模型权重
)
# 堆叠
stacked = stack_models(
estimator_list=['lr', 'dt', 'rf'],
meta_model='xgboost',
restack=False # 是否允许基础模型使用原始特征
)Step 11: 最终模型训练与预测 | Final Model Training & Prediction
# 在全部数据上训练最终模型
final_model = finalize_model(tuned_model)
# 预测
predictions = predict_model(final_model, data=test)
# 预测概率(分类)
predictions = predict_model(
final_model,
data=test,
probability_threshold=0.7 # 自定义阈值
)Step 12: 模型保存与部署 | Model Save & Deployment
# 保存模型(包含完整Pipeline)
save_model(final_model, 'my_model')
# 保存实验配置
save_experiment('my_experiment')
# 加载模型
loaded_model = load_model('my_model')
# 部署到云平台
deploy_model(
final_model,
platform='aws', # aws/gcp/azure
authentication={
'bucket': 'my-bucket'
}
)
# 创建Web应用
create_app(final_model, app_path='app.py')
# 创建REST API
create_api(final_model, api_name='predict', api_file='predict.py')
# 创建Docker
create_docker('my_model', docker_path='Dockerfile')---
AutoML 完整流程示例 | Complete AutoML Pipeline Example
from pycaret.classification import *
import pandas as pd
# ========== Step 1: 数据加载 ==========
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
# ========== Step 2: 数据探索 ==========
print(f"训练集: {train.shape}, 测试集: {test.shape}")
print(f"缺失值:\n{train.isnull().sum()}")
print(f"目标分布:\n{train['target'].value_counts()}")
# ========== Step 3-4: 数据预处理 + 特征工程 ==========
clf = setup(
train,
target='target',
# 数据预处理
numeric_imputation='median',
categorical_imputation='mode',
remove_outliers=True,
outliers_method='iforest',
fix_imbalance=True,
fix_imbalance_method='SMOTE',
# 特征工程
normalize=True,
normalize_method='zscore',
feature_selection=True,
n_features_to_select=0.3,
remove_multicollinearity=True,
polynomial_features=True,
polynomial_degree=2,
# 划分配置
train_size=0.8,
fold_strategy='stratifiedkfold',
fold=5,
session_id=42
)
# ========== Step 5: 模型选择 ==========
best = compare_models(sort='AUC')
# ========== Step 6-7: 训练与调优 ==========
tuned = tune_model(best, optimize='AUC', n_iter=30)
# ========== Step 8-9: 评估与解释 ==========
evaluate_model(tuned)
interpret_model(tuned)
# ========== Step 10: 集成(可选) ==========
# ensemble = ensemble_model(tuned)
# ========== Step 11: 最终预测 ==========
final = finalize_model(tuned)
predictions = predict_model(final, data=test)
# ========== Step 12: 保存 ==========
save_model(final, 'best_model')---
通用 API 参考 | Common API Reference
详细内容请参考 utilities.md
数据加载
from pycaret.classification import get_data
# 列出数据集
all_datasets = get_data('index')
# 加载数据集
data = get_data('breast_cancer')配置管理
from pycaret.classification import get_config, set_config
# 获取配置
X_train = get_config('X_train')
# 设置配置
set_config('seed', 123)模型操作
# 比较模型
best = compare_models()
# 创建模型
model = create_model('rf')
# 调优模型
tuned = tune_model(model)
# 集成
ensemble = ensemble_model(model)
# 预测
predictions = predict_model(model, data=new_data)
# 保存/加载
save_model(model, 'my_model')
loaded = load_model('my_model')---
详细文档索引 | Detailed Documentation Index
| 模块 | 包含内容 | 文件 |
|---|---|---|
| 参数深度分析 | setup参数选择指南、决策树、实战配置 | setup_parameters_deep_dive.md |
| Classification | setup 参数、模型列表、评估指标、工作流 | classification.md |
| Regression | setup 参数、回归模型、评估指标、工作流 | regression.md |
| Time Series | 时间序列特有参数、预测、季节性 | time_series.md |
| Clustering | 聚类算法、轮廓系数、分配标签 | clustering.md |
| Anomaly | 异常检测算法、可视化 | anomaly.md |
| NLP | 主题模型、文本处理、词云 | nlp.md |
| Association Rules | 关联规则、支持度、置信度 | association_rules.md |
| Utilities | 通用函数、部署、应用生成 | utilities.md |
---
代码模板 | Code Templates
分类任务模板
from pycaret.classification import *
data = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
clf = setup(data, target='target', train_size=0.8)
best = compare_models()
tuned = tune_model(best)
ensemble = ensemble_model(tuned)
predictions = predict_model(ensemble, data=test)
save_model(ensemble, 'classifier')回归任务模板
from pycaret.regression import *
data = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
reg = setup(data, target='price', normalize=True)
best = compare_models()
tuned = tune_model(best, optimize='RMSE')
predictions = predict_model(tuned, data=test)
save_model(tuned, 'regressor')时间序列模板
from pycaret.time_series import *
data = get_data('airline')
ts = setup(data, fh=12, seasonal_period=12)
best = compare_models()
model = create_model('arima')
predictions = predict_model(model, fh=24)---
最佳实践 | Best Practices
1. 数据预处理: 使用 normalize=True, remove_outliers=True 等参数 2. 模型选择: 用 compare_models(turbo=True) 快速验证 3. 超参数调优: 根据时间预算设置 n_iter 4. 模型集成: 复杂任务使用 ensemble_model 或 stack_models 5. 生产部署: 使用 finalize_model() 在全量数据上训练
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# Virtual Environment
venv/
ENV/
env/
.venv
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
{
"skill_name": "automl-skill",
"evals": [
{
"id": 1,
"prompt": "使用 PyCaret 构建一个分类模型,数据集是 breast_cancer,目标是预测 target 列。我需要完整的 AutoML 流程,包括数据预处理(归一化、异常值处理、特征选择)、模型比较、超参数调优和最终预测。",
"expected_output": "完整的 PyCaret 分类工作流代码,包含 setup(含 normalize=True, remove_outliers=True, feature_selection=True 等参数)、compare_models、tune_model、ensemble_model、predict_model 等函数调用",
"files": []
},
{
"id": 2,
"prompt": "我有一个 CSV 文件 'house_price.csv',目标列是 'Price',请帮我用 PyCaret 搭建一个回归模型来预测房价。需要进行数据预处理(归一化、异常值处理、特征工程)和模型调优。",
"expected_output": "针对回归任务的 PyCaret 代码,包含回归模块的导入、setup 配置(含 normalize=True, remove_outliers=True, transformation=True 等参数)和回归模型相关函数",
"files": []
},
{
"id": 3,
"prompt": "使用 PyCaret 进行客户聚类分析,我有客户数据包含年龄、收入、消费分数等特征,请帮我完成整个聚类分析流程。",
"expected_output": "使用 pycaret.clustering 模块的完整代码,包括 create_model、assign_model、evaluate_model 等",
"files": []
},
{
"id": 4,
"prompt": "我有时序数据 'sales.csv',包含历史销售记录,请帮我用 PyCaret 预测未来12个月的销售量。",
"expected_output": "使用 pycaret.time_series 模块的代码,包含 setup(指定 fh 参数)、compare_models、create_model、predict_model 等",
"files": []
},
{
"id": 5,
"prompt": "帮我用 PyCaret 进行异常检测,数据集是信用卡交易记录,需要识别欺诈交易。",
"expected_output": "使用 pycaret.anomaly 模块,包含 iforest、lof 等异常检测算法的使用",
"files": []
},
{
"id": 6,
"prompt": "我有一组客户评论文本数据,请用 PyCaret 进行文本主题建模,提取主要主题。",
"expected_output": "使用 pycaret.nlp 模块,包含 setup、create_model(lda/nmf)、assign_model、plot_model 等",
"files": []
},
{
"id": 7,
"prompt": "我的分类数据集存在严重的类别不平衡问题,少数类占比只有5%,请帮我用 PyCaret 处理这个问题并建模。",
"expected_output": "在 setup 中使用 fix_imbalance=True, fix_imbalance_method='SMOTE' 参数,并展示如何评估不平衡数据",
"files": []
},
{
"id": 8,
"prompt": "请帮我用 PyCaret 比较逻辑回归、随机森林、XGBoost、CatBoost 在分类任务上的性能,并选出最佳模型。",
"expected_output": "使用 compare_models(include=['lr', 'rf', 'xgboost', 'catboost']) 进行模型比较",
"files": []
},
{
"id": 9,
"prompt": "我的数据集有较多缺失值和异常值,请帮我配置 PyCaret 的数据预处理参数进行清洗。",
"expected_output": "setup 中使用 numeric_imputation、categorical_imputation、remove_outliers、outliers_method 等参数",
"files": []
},
{
"id": 10,
"prompt": "请帮我用 PyCaret 进行特征选择,我有100多个特征,需要筛选出最重要的特征来建模。",
"expected_output": "setup 中使用 feature_selection=True、feature_selection_method、n_features_to_select 参数",
"files": []
},
{
"id": 11,
"prompt": "我的数据包含日期特征 'Date',请帮我用 PyCaret 自动提取日期相关特征。",
"expected_output": "setup 中使用 date_features 参数指定日期列,PyCaret 会自动提取年/月/日/星期等特征",
"files": []
},
{
"id": 12,
"prompt": "请帮我用 PyCaret 对数据进行归一化处理,有哪些归一化方法可选?",
"expected_output": "setup 中使用 normalize=True 和 normalize_method 参数,可选 zscore/minmax/maxabs/robust",
"files": []
},
{
"id": 13,
"prompt": "请帮我用 PyCaret 进行模型可解释性分析,查看哪些特征对预测结果影响最大。",
"expected_output": "使用 plot_model(model, plot='feature') 或 interpret_model(model) 进行特征重要性分析",
"files": []
},
{
"id": 14,
"prompt": "请帮我用 PyCaret 创建一个集成模型,结合多个基础模型的预测结果。",
"expected_output": "使用 ensemble_model、blend_models 或 stack_models 进行模型集成",
"files": []
},
{
"id": 15,
"prompt": "训练好的 PyCaret 模型如何保存和部署到生产环境?请给我一个完整的示例。",
"expected_output": "使用 save_model 保存模型,load_model 加载模型,deploy_model 部署到云端,或 create_app 创建 Streamlit 应用",
"files": []
},
{
"id": 16,
"prompt": "我需要用 PyCaret 进行购物篮分析,找出商品之间的关联规则。",
"expected_output": "使用 pycaret.arules 模块,包含 setup、create_model、assign_model 等",
"files": []
},
{
"id": 17,
"prompt": "请帮我用 PyCaret 查看模型评估指标,比如 AUC、准确率、召回率、F1分数等。",
"expected_output": "使用 get_metrics 获取指标,evaluate_model 或 plot_model 查看详细评估结果",
"files": []
},
{
"id": 18,
"prompt": "我的数据有类别型特征,比如城市、产品类别等,请帮我用 PyCaret 处理这些类别特征。",
"expected_output": "在 setup 中使用 categorical_features 参数指定类别特征,PyCaret 会自动进行编码",
"files": []
},
{
"id": 19,
"prompt": "请帮我用 PyCaret 进行自动化机器学习(AutoML),自动选择最佳模型和超参数。",
"expected_output": "使用 automl() 函数或结合 compare_models + tune_model + ensemble_model 的完整流程",
"files": []
},
{
"id": 20,
"prompt": "我有一个分类问题,需要使用 GroupKFold 进行交叉验证,因为数据有分组结构(同一用户多条记录)。",
"expected_output": "setup 中使用 fold_strategy='groupkfold' 和 fold_groups 参数指定分组列",
"files": []
},
{
"id": 21,
"prompt": "请帮我用 PyCaret 对回归模型进行超参数调优,优化 RMSE 指标。",
"expected_output": "使用 tune_model(model, optimize='RMSE') 进行调优",
"files": []
},
{
"id": 22,
"prompt": "我的时间序列数据有明显的季节性(周季节),请帮我配置 PyCaret 的季节性参数。",
"expected_output": "setup 中使用 seasonal_period 参数,如 seasonal_period=7 表示周季节性",
"files": []
},
{
"id": 23,
"prompt": "请帮我用 PyCaret 绘制分类模型的 ROC 曲线和混淆矩阵。",
"expected_output": "使用 plot_model(model, plot='auc') 和 plot_model(model, plot='confusion_matrix')",
"files": []
},
{
"id": 24,
"prompt": "我需要使用 PyCaret 生成一个交互式的模型评估仪表板。",
"expected_output": "使用 evaluate_model(model) 或 dashboard(model) 生成交互式仪表板",
"files": []
},
{
"id": 25,
"prompt": "请帮我用 PyCaret 进行情感分析,判断文本评论是正面还是负面。",
"expected_output": "使用 pycaret.nlp 或 pycaret.text 模块进行情感分析",
"files": []
},
{
"id": 26,
"prompt": "我需要对 PyCaret 回归模型的结果进行统计显著性检验,查看哪些特征对目标变量有显著影响。",
"expected_output": "使用 statsmodels 的 OLS 回归获取 P值和置信区间,或在 PyCaret 中使用 interpret_model 查看特征重要性",
"files": []
},
{
"id": 27,
"prompt": "请帮我用 statsmodels 进行假设检验,判断两组数据的均值是否有显著差异。",
"expected_output": "使用 scipy.stats 的 ttest_ind 进行 t 检验,或使用 statsmodels 的 ANOVA",
"files": []
},
{
"id": 28,
"prompt": "请帮我用 statsmodels 进行时间序列分析,建立 ARIMA 模型预测未来趋势。",
"expected_output": "使用 statsmodels.tsa.arima.model.ARIMA 或 SARIMAX 进行时间序列建模和预测",
"files": []
},
{
"id": 29,
"prompt": "我需要对回归模型进行统计诊断,包括残差自相关检验和异方差检验。",
"expected_output": "使用 statsmodels.stats.stattools.durbin_watson 检验自相关,使用 statsmodels.stats.diagnostic.het_breuschpagan 检验异方差",
"files": []
},
{
"id": 30,
"prompt": "请帮我用 statsmodels 的广义线性模型 GLM 进行二分类建模,需要获取系数和置信区间。",
"expected_output": "使用 statsmodels.GLM 设置 family=sm.families.Binomial() 进行 logistic 回归",
"files": []
}
]
}
AutoML Skill | 自动化机器学习技能
---
English
Overview
AutoML Skill is a powerful automated machine learning skill based on PyCaret, designed to help data scientists and developers quickly build end-to-end machine learning workflows with minimal code.
Features
- 🚀 Automated Model Selection - Automatically compare multiple models and select the best one
- 🎯 Automated Hyperparameter Tuning - Optimize model parameters using Optuna/Hyperopt
- ⚡ Automated Feature Engineering - Data preprocessing, transformation, and feature selection
- 🔄 Model Ensemble - Support for Bagging, Boosting, Stacking, Blending
- 📊 Model Interpretability - SHAP, Permutation Importance support
- ☁️ Production-Ready - Model deployment to AWS, GCP, Azure
- 📈 Statistical Enhancement - Confidence intervals, hypothesis testing, significance analysis (statsmodels)
Supported ML Tasks
| Module | Task Type | Description |
|---|---|---|
pycaret.classification | Classification | Binary & Multi-class classification |
pycaret.regression | Regression | Regression prediction |
pycaret.clustering | Clustering | Unsupervised clustering |
pycaret.anomaly | Anomaly Detection | Outlier detection |
pycaret.time_series | Time Series | Time series forecasting |
pycaret.nlp | NLP | Text classification, Topic modeling |
pycaret.arules | Association Rules | Market basket analysis |
Statistical Enhancement (statsmodels)
When you need statistical inference, hypothesis testing, or confidence intervals, use statsmodels alongside PyCaret:
# OLS Regression with statistical significance
import statsmodels.api as sm
X = sm.add_constant(X)
model = sm.OLS(y, X).fit()
print(model.summary()) # R², F-test, P-values, confidence intervals
# Hypothesis Testing
from scipy import stats
t_stat, p_value = stats.ttest_ind(group1, group2)
# ARIMA Time Series
from statsmodels.tsa.arima.model import ARIMA
arima_model = ARIMA(data, order=(1,1,1)).fit()Quick Start
完整的 AutoML 工作流程:
from pycaret.classification import *
import pandas as pd
# Step 1: Load Data
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
# Step 2: Data Exploration
print(f"Train: {train.shape}, Test: {test.shape}")
# Step 3-4: Preprocessing & Feature Engineering
clf = setup(
train,
target='target',
# Missing values
numeric_imputation='median',
categorical_imputation='mode',
# Outliers
remove_outliers=True,
# Class balance
fix_imbalance=True,
# Feature scaling
normalize=True,
normalize_method='zscore',
# Feature selection
feature_selection=True,
n_features_to_select=0.3,
session_id=42
)
# Step 5: Model Selection
best = compare_models(sort='AUC')
# Step 6-7: Training & Tuning
tuned = tune_model(best, optimize='AUC', n_iter=30)
# Step 8-9: Evaluation & Interpretation
evaluate_model(tuned)
interpret_model(tuned)
# Step 10: Ensemble (optional)
# ensemble = ensemble_model(tuned)
# Step 11: Final Prediction
final = finalize_model(tuned)
predictions = predict_model(final, data=test)
# Step 12: Save
save_model(final, 'best_model')Documentation Structure
automl-skill/
├── SKILL.md # Main skill file
├── evals/
│ └── evals.json # Test cases (30 examples)
└── references/ # Detailed documentation
├── classification.md # Classification module
├── regression.md # Regression module
├── time_series.md # Time series module
├── clustering.md # Clustering module
├── anomaly.md # Anomaly detection
├── nlp.md # NLP module
├── association_rules.md # Association rules
├── utilities.md # Utility functions
└── setup_parameters_deep_dive.md # Parameter guideWhen to Use This Skill
- Rapid prototyping and experiment iteration
- Feature engineering and data preprocessing
- Model selection and comparison
- Hyperparameter optimization
- Statistical inference and hypothesis testing
- Model deployment and production
---
中文
简介
AutoML Skill 是一个基于 PyCaret 的强大自动化机器学习技能,旨在帮助数据科学家和开发者用最少的代码快速构建端到端的机器学习工作流。
功能特点
- 🚀 自动化模型选择 - 自动比较多个模型并选择最佳模型
- 🎯 自动化超参数调优 - 使用 Optuna/Hyperopt 自动优化模型参数
- ⚡ 自动化特征工程 - 数据预处理、转换和特征选择
- 🔄 模型集成 - 支持 Bagging、Boosting、Stacking、Blending
- 📊 模型可解释性 - 支持 SHAP、Permutation Importance
- ☁️ 生产就绪 - 支持部署到 AWS、GCP、Azure
- 📈 统计推断增强 - 置信区间、假设检验、显著性分析 (statsmodels)
支持的任务类型
| 模块 | 任务类型 | 说明 |
|---|---|---|
pycaret.classification | 分类 | 二分类和多分类 |
pycaret.regression | 回归 | 回归预测 |
pycaret.clustering | 聚类 | 无监督聚类 |
pycaret.anomaly | 异常检测 | 离群点检测 |
pycaret.time_series | 时间序列 | 时间序列预测 |
pycaret.nlp | 自然语言处理 | 文本分类、主题建模 |
pycaret.arules | 关联规则 | 购物篮分析 |
统计推断增强 (statsmodels)
当需要统计推断、假设检验、置信区间时,可以使用 statsmodels 补充 PyCaret:
# OLS 回归(带统计显著性)
import statsmodels.api as sm
X = sm.add_constant(X)
model = sm.OLS(y, X).fit()
print(model.summary()) # R², F检验, P值, 置信区间
# 假设检验
from scipy import stats
t_stat, p_value = stats.ttest_ind(group1, group2)
# ARIMA 时间序列
from statsmodels.tsa.arima.model import ARIMA
arima_model = ARIMA(data, order=(1,1,1)).fit()快速开始
完整的 AutoML 工作流程:
from pycaret.classification import *
import pandas as pd
# Step 1: 加载数据
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
# Step 2: 数据探索
print(f"训练集: {train.shape}, 测试集: {test.shape}")
# Step 3-4: 数据预处理 + 特征工程
clf = setup(
train,
target='target',
# 缺失值处理
numeric_imputation='median',
categorical_imputation='mode',
# 异常值处理
remove_outliers=True,
# 类别平衡
fix_imbalance=True,
# 特征缩放
normalize=True,
normalize_method='zscore',
# 特征选择
feature_selection=True,
n_features_to_select=0.3,
session_id=42
)
# Step 5: 模型选择
best = compare_models(sort='AUC')
# Step 6-7: 训练与调优
tuned = tune_model(best, optimize='AUC', n_iter=30)
# Step 8-9: 评估与解释
evaluate_model(tuned)
interpret_model(tuned)
# Step 10: 集成(可选)
# ensemble = ensemble_model(tuned)
# Step 11: 最终预测
final = finalize_model(tuned)
predictions = predict_model(final, data=test)
# Step 12: 保存
save_model(final, 'best_model')文档结构
automl-skill/
├── SKILL.md # 主技能文件
├── evals/
│ └── evals.json # 测试用例 (30个示例)
└── references/ # 详细文档
├── classification.md # 分类模块
├── regression.md # 回归模块
├── time_series.md # 时间序列模块
├── clustering.md # 聚类模块
├── anomaly.md # 异常检测
├── nlp.md # NLP模块
├── association_rules.md # 关联规则
├── utilities.md # 工具函数
└── setup_parameters_deep_dive.md # 参数指南使用场景
- 快速原型开发和实验迭代
- 特征工程和数据预处理
- 模型选择和比较
- 超参数优化
- 统计推断和假设检验
- 模型部署和生产
相关链接
- PyCaret 官方文档: https://pycaret.gitbook.io/docs
- PyCaret API 文档: https://pycaret.readthedocs.io/
---
This skill is part of the automl-skill project. Future versions will integrate more AutoML libraries like AutoGluon, FLAML, etc.
PyCaret Anomaly 模块 | Anomaly Detection Module
异常检测任务的完整 API 参考文档。
setup() 函数
from pycaret.anomaly import setup
# 基础用法
ano = setup(data)
# 参数与 Clustering 模块基本相同
ano = setup(
data,
index=True,
numeric_features=None,
categorical_features=None,
ordinal_features=None,
date_features=None,
text_features=None,
ignore_features=None,
keep_features=None,
preprocess=True,
imputation_type='simple',
numeric_imputation='mean',
categorical_imputation='constant',
text_features_method='tf-idf',
max_encoding_ohe=-1,
encoding_method=None,
rare_to_value=None,
rare_value='rare',
polynomial_features=False,
polynomial_degree=2,
low_variance_threshold=None,
remove_multicollinearity=False,
multicollinearity_threshold=0.9,
bin_numeric_features=None,
remove_outliers=False,
outliers_method='iforest',
outliers_threshold=0.05,
transformation=False,
transformation_method='yeo-johnson',
normalize=False,
normalize_method='zscore',
pca=False,
pca_method='linear',
pca_components=None,
custom_pipeline=None,
custom_pipeline_position=-1,
n_jobs=-1,
use_gpu=False,
html=True,
session_id=None,
log_experiment=False,
experiment_name=None,
experiment_custom_tags=None,
log_plots=False,
log_profile=False,
log_data=False,
verbose=True,
memory=True,
profile=False,
profile_kwargs={}
)常用异常检测算法
'iforest' # Isolation Forest
'ee' # Elliptic Envelope
'lof' # Local Outlier Factor
'svm' # One-Class SVM
'pca' # PCA-based Outlier Detection
'kde' # Kernel Density Estimationcreate_model()
from pycaret.anomaly import create_model
# Isolation Forest
iforest = create_model('iforest')
# Elliptic Envelope
ee = create_model('ee')
# Local Outlier Factor
lof = create_model('lof')
# One-Class SVM
svm = create_model('svm')
# 带参数
iforest = create_model('iforest', contamination=0.1, random_state=42)tune_model()
from pycaret.anomaly import tune_model
# 调优
tuned = tune_model('iforest')assign_model()
from pycaret.anomaly import assign_model
# 分配异常标签
results = assign_model(model)
# 返回原始数据 + Cluster 列 (1=正常, -1=异常)plot_model() 图表类型
| 图表 | 说明 |
|---|---|
'tsne' | t-SNE 可视化 |
'umap' | UMAP 可视化 |
'cluster' | Cluster PCA Plot |
evaluate_model()
from pycaret.anomaly import evaluate_model
evaluate_model(model)predict_model()
from pycaret.anomaly import predict_model
# 预测新数据
predictions = predict_model(model, data=new_data)
# 返回 Label (1=正常, -1=异常) 和 Score完整工作流示例
from pycaret.anomaly import *
# 1. 加载数据
data = get_data('outlier')
# 2. 初始化
ano = setup(data, normalize=True)
# 3. 创建模型
iforest = create_model('iforest', contamination=0.05)
# 4. 调优
tuned = tune_model(iforest)
# 5. 分配标签
results = assign_model(tuned)
# 6. 可视化
plot_model(tuned, plot='tsne')
# 7. 评估
evaluate_model(tuned)
# 8. 预测新数据
predictions = predict_model(tuned, data=new_data)PyCaret Association Rules 模块 | Association Rules Module
关联规则挖掘任务的完整 API 参考文档。
setup() 函数
from pycaret.arules import setup
# 基础用法
arules = setup(data, transaction_id='transaction_id', item_features='item')
# 完整参数
arules = setup(
# ===== 必需参数 =====
data, # 数据框(必需)
transaction_id, # 交易ID列(必需)
item_features=None, # 商品特征列
# ===== 数据处理 =====
encoding_method=None, # 编码方法
freq_threshold=0.01, # 频繁项集阈值
# ===== 系统选项 =====
n_jobs=-1,
html=True,
session_id=None,
verbose=True,
profile=False
)create_model()
from pycaret.arules import create_model
# 创建关联规则模型
model = create_model()
# 完整参数
model = create_model(
metric='confidence', # 评估指标
threshold=0.5, # 阈值
min_support=0.001, # 最小支持度
max_length=10 # 最大项集长度
)评估指标
| 指标 | 说明 |
|---|---|
| support | 支持度 |
| confidence | 置信度 |
| lift | 提升度 |
assign_model()
from pycaret.arules import assign_model
# 获取关联规则
rules = assign_model(model)
# 返回关联规则表plot_model() 图表类型
| 图表 | 说明 |
|---|---|
'network' | 关联网络图 |
'matrix' | 关联矩阵图 |
'sunburst' | 旭日图 |
完整工作流示例
from pycaret.arules import *
# 1. 加载数据
data = get_data('market')
# 2. 初始化
arules = setup(data, transaction_id='Item', item_features='Amount')
# 3. 创建模型
model = create_model(
metric='confidence',
threshold=0.5,
min_support=0.01
)
# 4. 获取规则
rules = assign_model(model)
# 5. 可视化
plot_model(model, plot='network')
plot_model(model, plot='matrix')
# 6. 查看规则
print(rules.head(10))常用参数说明
- metric: 评估指标,可选 'support', 'confidence', 'lift'
- threshold: 阈值,过滤低于此值的规则
- min_support: 最小支持度
- max_length: 项集最大长度
示例数据格式
交易数据格式示例:
| transaction_id | item |
|---|---|
| 1 | Apple |
| 1 | Banana |
| 1 | Milk |
| 2 | Banana |
| 2 | Bread |
| 3 | Apple |
| 3 | Bread |
| 3 | Milk |
| 3 | Banana |
或使用 One-Hot 编码格式:
| transaction_id | Apple | Banana | Bread | Milk |
|---|---|---|---|---|
| 1 | 1 | 1 | 0 | 1 |
| 2 | 0 | 1 | 1 | 0 |
| 3 | 1 | 1 | 1 | 1 |
PyCaret Classification 模块 | Classification Module
分类任务的完整 API 参考文档。
setup() 函数
from pycaret.classification import setup
# 基础用法
clf = setup(data, target='target_column')
# 完整参数
clf = setup(
# ===== 必需参数 =====
data, # 数据框(必需)
target=-1, # 目标列索引/名称/序列
# ===== 数据划分 =====
train_size=0.7, # 训练集比例
test_data=None, # 外部测试集
data_split_shuffle=True, # 是否打乱
data_split_stratify=True, # 分层抽样
fold_strategy='stratifiedkfold', # 折策略: 'kfold', 'stratifiedkfold', 'groupkfold'
fold=10, # 交叉验证折数
fold_shuffle=False, # 折是否打乱
fold_groups=None, # 分组(用于 GroupKFold)
# ===== 索引处理 =====
index=True, # 索引处理: True/False/列名/位置
# ===== 特征类型指定 =====
numeric_features=None, # 指定数值特征
categorical_features=None, # 指定类别特征
ordinal_features=None, # 有序类别: {'col': ['low', 'medium', 'high']}
date_features=None, # 日期特征
text_features=None, # 文本特征
ignore_features=None, # 忽略的特征
keep_features=None, # 保留的特征
# ===== 数据预处理 =====
preprocess=True, # 是否预处理
imputation_type='simple', # 插补类型: 'simple', 'iterative', None
numeric_imputation='mean', # 数值型: 'mean', 'median', 'mode', 'knn'
categorical_imputation='mode', # 类别型: 'mode', 'constant'
iterative_imputation_iters=5, # 迭代插补次数
numeric_iterative_imputer='lightgbm', # 数值迭代插补器
categorical_iterative_imputer='lightgbm', # 类别迭代插补器
text_features_method='tf-idf', # 文本方法: 'tf-idf', 'bow'
max_encoding_ohe=25, # OHE 编码的最大类别数
encoding_method=None, # 编码方法(category_encoders)
rare_to_value=None, # 稀有类别阈值
rare_value='rare', # 稀有类别替换值
# ===== 特征工程 =====
polynomial_features=False, # 多项式特征
polynomial_degree=2, # 多项式阶数
low_variance_threshold=None, # 低方差阈值
group_features=None, # 分组特征
drop_groups=False, # 是否删除分组特征
remove_multicollinearity=False, # 移除多重共线性
multicollinearity_threshold=0.9, # 多重共线性阈值
bin_numeric_features=None, # 离散化数值特征
# ===== 离群值处理 =====
remove_outliers=False, # 是否移除离群值
outliers_method='iforest', # 方法: 'iforest', 'ee', 'lof'
outliers_threshold=0.05, # 离群值阈值
# ===== 类别平衡 =====
fix_imbalance=False, # 是否平衡类别
fix_imbalance_method='SMOTE', # 平衡方法: 'SMOTE', 'RandomUnderSampler'
# ===== 变换 =====
transformation=False, # 是否变换
transformation_method='yeo-johnson', # 变换方法
normalize=False, # 是否归一化
normalize_method='zscore', # 归一化方法: 'zscore', 'minmax', 'maxabs', 'robust'
# ===== 降维 =====
pca=False, # 是否PCA
pca_method='linear', # PCA方法: 'linear', 'kernel', 'incremental'
pca_components=None, # PCA主成分数
# ===== 特征选择 =====
feature_selection=False, # 是否特征选择
feature_selection_method='classic', # 方法: 'classic', 'univariate'
feature_selection_estimator='lightgbm', # 选择器
n_features_to_select=0.2, # 选择特征比例/数量
# ===== 自定义 Pipeline =====
custom_pipeline=None, # 自定义转换器
custom_pipeline_position=-1, # 位置
# ===== 引擎配置 =====
engine=None, # 引擎配置
# ===== 系统选项 =====
n_jobs=-1, # 并行任务数
use_gpu=False, # 是否使用GPU
html=True, # 是否显示HTML
session_id=None, # 随机种子
log_experiment=False, # 记录实验
experiment_name=None, # 实验名称
experiment_custom_tags=None, # 自定义标签
log_plots=False, # 自动记录图表
log_profile=False, # 记录数据Profile
log_data=False, # 记录数据
verbose=True, # 详细输出
memory=True, # 缓存
profile=False, # 生成报告
profile_kwargs={} # 报告参数
)常用模型缩写
# 线性模型
'lr' # Logistic Regression
'ridge' # Ridge Classifier
'lda' # Linear Discriminant Analysis
'qda' # Quadratic Discriminant Analysis
# 树模型
'dt' # Decision Tree
'rf' # Random Forest
'et' # Extra Trees
# Boosting
'gbc' # Gradient Boosting Classifier
'ada' # AdaBoost Classifier
'catboost' # CatBoost Classifier
'lightgbm' # LightGBM Classifier
'xgboost' # XGBoost Classifier
# 其他
'nb' # Naive Bayes
'svm' # Support Vector Machine
'rbfsvm' # RBF SVM
'knn' # K-Nearest Neighbors
'mlp' # Multi-Layer Perceptroncompare_models()
from pycaret.classification import compare_models
# 比较所有模型
best = compare_models()
# 指定模型
best = compare_models(include=['lr', 'dt', 'rf', 'xgboost'])
# 参数
best = compare_models(
fold=5,
round=4,
sort='Accuracy', # 排序指标
n_select=1,
turbo=True,
verbose=True
)create_model()
from pycaret.classification import create_model
# 创建模型
lr = create_model('lr')
rf = create_model('rf')
# 完整参数
model = create_model(
estimator='rf',
fold=5,
round=4,
verbose=True,
**kwargs
)tune_model()
from pycaret.classification import tune_model
# 调优模型
tuned = tune_model(model)
# 自定义网格
tuned = tune_model(
model,
custom_grid={'n_estimators': [100, 200], 'max_depth': [3, 5, 7]},
optimize='Accuracy',
n_iter=10
)ensemble_model()
from pycaret.classification import ensemble_model
# Bagging
bagged = ensemble_model(model, method='Bagging')
# Boosting
boosted = ensemble_model(model, method='Boosting')blend_models() & stack_models()
from pycaret.classification import blend_models, stack_models
# 融合
blended = blend_models(estimator_list=['lr', 'dt', 'rf'], method='soft')
# 堆叠
stacked = stack_models(
estimator_list=['lr', 'dt', 'rf'],
meta_model='lr'
)plot_model() 图表类型
| 图表 | 说明 |
|---|---|
'auc' | ROC AUC 曲线 |
'pr' | Precision-Recall 曲线 |
'confusion_matrix' | 混淆矩阵 |
'threshold' | 阈值分析 |
'learning_curve' | 学习曲线 |
'validation_curve' | 验证曲线 |
'manifold' | 流形学习 |
'feature' | 特征重要性 |
'feature_all' | 所有特征重要性 |
'classification_report' | 分类报告 |
'error' | 预测误差 |
'calibration_curve' | 校准曲线 |
'ks_statistic' | KS 统计量 |
'lift_curve' | Lift 曲线 |
'gain_curve' | Gain 曲线 |
evaluate_model()
from pycaret.classification import evaluate_model
evaluate_model(model)predict_model()
from pycaret.classification import predict_model
predictions = predict_model(model, data=new_data)
# 返回: Label, Score评估指标
| 指标 | 说明 |
|---|---|
| Accuracy | 准确率 |
| AUC | ROC AUC |
| Recall | 召回率 |
| Precision | 精确率 |
| F1 | F1 分数 |
| Kappa | Cohen's Kappa |
| MCC | Matthews Correlation Coefficient |
完整工作流示例
from pycaret.classification import *
# 1. 加载数据
data = get_data('breast_cancer')
# 2. 初始化
clf = setup(data, target='target', normalize=True)
# 3. 比较模型
best = compare_models()
# 4. 调优
tuned = tune_model(best)
# 5. 集成
ensemble = ensemble_model(tuned)
# 6. 评估
evaluate_model(ensemble)
# 7. 预测
predictions = predict_model(ensemble, data=test_data)
# 8. 保存
save_model(ensemble, 'best_model')PyCaret Clustering 模块 | Clustering Module
聚类任务的完整 API 参考文档。
setup() 函数
from pycaret.clustering import setup
# 基础用法(无 target 参数)
clu = setup(data)
# 完整参数
clu = setup(
# ===== 必需参数 =====
data, # 数据框(必需)
# ===== 索引处理 =====
index=True,
# ===== 特征类型指定 =====
numeric_features=None,
categorical_features=None,
ordinal_features=None,
date_features=None,
text_features=None,
ignore_features=None,
keep_features=None,
# ===== 数据预处理 =====
preprocess=True,
imputation_type='simple', # 聚类只支持 'simple'
numeric_imputation='mean',
categorical_imputation='constant', # 聚类默认 constant
text_features_method='tf-idf', # 文本方法
max_encoding_ohe=-1, # -1 表示全部用 OHE
encoding_method=None,
rare_to_value=None,
rare_value='rare',
# ===== 特征工程 =====
polynomial_features=False,
polynomial_degree=2,
low_variance_threshold=None,
remove_multicollinearity=False,
multicollinearity_threshold=0.9,
bin_numeric_features=None,
# ===== 离群值处理 =====
remove_outliers=False,
outliers_method='iforest',
outliers_threshold=0.05,
# ===== 变换 =====
transformation=False,
transformation_method='yeo-johnson',
normalize=False,
normalize_method='zscore',
# ===== 降维 =====
pca=False,
pca_method='linear',
pca_components=None,
# ===== 自定义 Pipeline =====
custom_pipeline=None,
custom_pipeline_position=-1,
# ===== 系统选项 =====
n_jobs=-1,
use_gpu=False,
html=True,
session_id=None,
log_experiment=False,
experiment_name=None,
experiment_custom_tags=None,
log_plots=False,
log_profile=False,
log_data=False,
verbose=True,
memory=True,
profile=False,
profile_kwargs={}
)常用聚类算法
'kmeans' # K-Means Clustering
'hclust' # Hierarchical Clustering
'sc' # Spectral Clustering
'meanshift' # Mean Shift Clustering
'ap' # Affinity Propagation
'birch' # BIRCH Clustering
'dbscan' # DBSCAN
'kproto' # K-Prototypes (for mixed data)create_model()
from pycaret.clustering import create_model
# K-Means
kmeans = create_model('kmeans', num_clusters=3)
# 层次聚类
hclust = create_model('hclust', num_clusters=3)
# DBSCAN
dbscan = create_model('dbscan', eps=0.5, min_samples=5)
# 完整参数
model = create_model(
'kmeans',
num_clusters=4,
round=4,
verbose=True
)tune_model()
from pycaret.clustering import tune_model
# 调优聚类模型
tuned = tune_model('kmeans')assign_model()
from pycaret.clustering import assign_model
# 分配聚类标签
results = assign_model(model)
# 返回原始数据 + Cluster 列plot_model() 图表类型
| 图表 | 说明 |
|---|---|
'cluster' | Cluster PCA Plot (2D) |
'tsne' | Cluster t-SNE (3D) |
'elbow' | Elbow Plot |
'silhouette' | Silhouette Plot |
'distance' | Distance Plot |
'distribution' | Distribution Plot |
evaluate_model()
from pycaret.clustering import evaluate_model
evaluate_model(model)predict_model()
from pycaret.clustering import predict_model
# 预测新数据
predictions = predict_model(model, data=new_data)评估指标
from pycaret.clustering import get_metrics
metrics = get_metrics()
# 可用指标: silhouette, calinski_harabasz, davies_bouldin, rand完整工作流示例
from pycaret.clustering import *
# 1. 加载数据
data = get_data('jewellery')
# 2. 初始化
clu = setup(data, normalize=True)
# 3. 创建模型
kmeans = create_model('kmeans', num_clusters=4)
# 4. 调优
tuned = tune_model(kmeans)
# 5. 分配标签
results = assign_model(tuned)
# 6. 可视化
plot_model(tuned, plot='elbow')
plot_model(tuned, plot='silhouette')
plot_model(tuned, plot='cluster')
# 7. 评估
evaluate_model(tuned)
# 8. 预测新数据
predictions = predict_model(tuned, data=new_data)PyCaret NLP 模块 | NLP Module
自然语言处理任务的完整 API 参考文档。
setup() 函数
from pycaret.nlp import setup
# 基础用法
nlp = setup(data, target='text_column')
# 完整参数
nlp = setup(
# ===== 必需参数 =====
data, # 数据框(必需)
target, # 文本列名(必需)
# ===== 特征指定 =====
numeric_features=None, # 数值特征
categorical_features=None, # 类别特征
ignore_features=None, # 忽略的特征
# ===== 数据预处理 =====
imputation_type='simple', # 插补类型
max_encoding_ohe=25, # OHE 编码数
encoding_method=None, # 编码方法
# ===== 文本处理 =====
text_features_method='tf-idf', # 文本特征方法: 'tf-idf', 'bow', 'embeddings'
text_aggregation='sum', # 聚合方式: 'sum', 'mean', 'median', 'max', 'min'
text_feature_extract=None, # 特征提取: None, 'tokenize'
# ===== 降维 =====
pca=False,
pca_method='linear',
pca_components=None,
# ===== 聚类配置 =====
clustering=False, # 是否进行聚类
cluster_method='kmeans', # 聚类方法
# ===== 主题模型 =====
topic_model=None, # 主题模型配置
topic_model_name='lda', # 模型名: 'lda', 'nmf', 'lsi', 'hdp'
num_topics='auto', # 主题数量
# ===== 系统选项 =====
n_jobs=-1,
html=True,
session_id=None,
log_experiment=False,
experiment_name=None,
verbose=True,
profile=False
)常用主题模型
'lda' # Latent Dirichlet Allocation
'nmf' # Non-Negative Matrix Factorization
'lsi' # Latent Semantic Indexing
'hdp' # Hierarchical Dirichlet Processcreate_model()
from pycaret.nlp import create_model
# 创建主题模型
lda = create_model('lda', num_topics=4)
# 带参数
lda = create_model('lda', num_topics=4, doc_topic_prior=0.1, topic_word_prior=0.01)
nmf = create_model('nmf', num_topics=4)tune_model()
from pycaret.nlp import tune_model
# 调优
tuned = tune_model(lda)assign_model()
from pycaret.nlp import assign_model
# 分配主题
results = assign_model(lda)
# 返回原始数据 + Topic 相关列plot_model() 图表类型
| 图表 | 说明 |
|---|---|
'wordcloud' | 词云 |
'frequency' | 词频图 |
'ngram' | N-gram 图 |
'sentiment' | 情感分布 |
'dimension' | 维度分布 |
'topic_distribution' | 主题分布 |
'topic_model' | 主题模型可视化 |
evaluate_model()
from pycaret.nlp import evaluate_model
evaluate_model(lda)predict_model()
from pycaret.nlp import predict_model
# 预测新文本
predictions = predict_model(lda, data=new_texts)完整工作流示例
from pycaret.nlp import *
# 1. 加载数据
data = get_data('kiva')
# 2. 初始化
nlp = setup(data, target='loan_theme')
# 3. 创建主题模型
lda = create_model('lda', num_topics=4)
# 4. 调优
tuned = tune_model(lda)
# 5. 分配主题
results = assign_model(tuned)
# 6. 可视化
plot_model(tuned, plot='wordcloud')
plot_model(tuned, plot='frequency')
plot_model(tuned, plot='topic_distribution')
# 7. 评估
evaluate_model(tuned)文本分类
# 使用 pycaret.text 进行文本分类
from pycaret.text import *
clf = setup(data, target='target_column')
best = compare_models()情感分析
# 情感分析
sentiment = create_model('sentiment')
results = assign_model(sentiment)PyCaret Regression 模块 | Regression Module
回归任务的完整 API 参考文档。
setup() 函数
from pycaret.regression import setup
# 基础用法
reg = setup(data, target='target_column')
# 完整参数(与 Classification 类似,但增加了 transform_target)
reg = setup(
# ===== 必需参数 =====
data, # 数据框(必需)
target=-1, # 目标列
# ===== 数据划分 =====
train_size=0.7,
test_data=None,
data_split_shuffle=True,
data_split_stratify=False, # 回归通常不用分层
fold_strategy='kfold', # 回归默认用 kfold
fold=10,
fold_shuffle=False,
fold_groups=None,
# ===== 索引处理 =====
index=True,
# ===== 特征类型指定 =====
numeric_features=None,
categorical_features=None,
ordinal_features=None,
date_features=None,
text_features=None,
ignore_features=None,
keep_features=None,
# ===== 数据预处理 =====
preprocess=True,
imputation_type='simple',
numeric_imputation='mean',
categorical_imputation='mode',
iterative_imputation_iters=5,
numeric_iterative_imputer='lightgbm',
categorical_iterative_imputer='lightgbm',
text_features_method='tf-idf',
max_encoding_ohe=25,
encoding_method=None,
rare_to_value=None,
rare_value='rare',
# ===== 特征工程 =====
polynomial_features=False,
polynomial_degree=2,
low_variance_threshold=None,
group_features=None,
drop_groups=False,
remove_multicollinearity=False,
multicollinearity_threshold=0.9,
bin_numeric_features=None,
# ===== 离群值处理 =====
remove_outliers=False,
outliers_method='iforest',
outliers_threshold=0.05,
# ===== 目标变换(回归特有)=====
transform_target=False, # 是否变换目标变量
transform_target_method='yeo-johnson', # 变换方法
# ===== 变换 =====
transformation=False,
transformation_method='yeo-johnson',
normalize=False,
normalize_method='zscore',
# ===== 降维 =====
pca=False,
pca_method='linear',
pca_components=None,
# ===== 特征选择 =====
feature_selection=False,
feature_selection_method='classic',
feature_selection_estimator='lightgbm',
n_features_to_select=0.2,
# ===== 自定义 Pipeline =====
custom_pipeline=None,
custom_pipeline_position=-1,
# ===== 引擎配置 =====
engine=None,
# ===== 系统选项 =====
n_jobs=-1,
use_gpu=False,
html=True,
session_id=None,
log_experiment=False,
experiment_name=None,
experiment_custom_tags=None,
log_plots=False,
log_profile=False,
log_data=False,
verbose=True,
memory=True,
profile=False,
profile_kwargs={}
)常用模型缩写
# 线性模型
'lr' # Linear Regression
'ridge' # Ridge Regression
'lasso' # Lasso Regression
'en' # Elastic Net
'lar' # Least Angle Regression
'br' # Bayesian Ridge
# 树模型
'dt' # Decision Tree Regressor
'rf' # Random Forest Regressor
'et' # Extra Trees Regressor
# Boosting
'gbr' # Gradient Boosting Regressor
'ada' # AdaBoost Regressor
'catboost' # CatBoost Regressor
'lightgbm' # LightGBM Regressor
'xgboost' # XGBoost Regressor
# 其他
'knn' # K-Nearest Neighbors Regressor
'mlp' # MLP Regressorcompare_models()
from pycaret.regression import compare_models
# 比较所有模型
best = compare_models()
# 指定模型
best = compare_models(include=['lr', 'rf', 'xgboost'])
# 参数
best = compare_models(
fold=5,
round=4,
sort='R2', # 排序指标: 'R2', 'RMSE', 'MSE', 'MAE'
n_select=1,
turbo=True
)create_model()
from pycaret.regression import create_model
# 创建模型
lr = create_model('lr')
rf = create_model('rf')tune_model()
from pycaret.regression import tune_model
# 调优模型
tuned = tune_model(model, optimize='RMSE')
tuned = tune_model(model, optimize='R2')plot_model() 图表类型
| 图表 | 说明 |
|---|---|
'residuals' | 残差图 |
'error' | 预测误差 |
'cooks' | Cook's Distance |
'rfe' | 递归特征消除 |
'learning_curve' | 学习曲线 |
'validation_curve' | 验证曲线 |
'manifold' | 流形学习 |
'feature' | 特征重要性 |
'feature_all' | 所有特征重要性 |
'parameter' | 模型参数 |
评估指标
| 指标 | 说明 |
|---|---|
| R2 | R² 决定系数 |
| RMSE | 均方根误差 |
| MSE | 均方误差 |
| MAE | 平均绝对误差 |
| MSLE | 均方对数误差 |
| MAPE | 平均绝对百分比误差 |
完整工作流示例
from pycaret.regression import *
# 1. 加载数据
data = get_data('boston')
# 2. 初始化
reg = setup(data, target='medv', normalize=True, remove_outliers=True)
# 3. 比较模型
best = compare_models()
# 4. 调优
tuned = tune_model(best, optimize='RMSE')
# 5. 集成
ensemble = ensemble_model(tuned)
# 6. 评估
evaluate_model(ensemble)
# 7. 预测
predictions = predict_model(ensemble, data=test_data)
# 8. 保存
save_model(ensemble, 'best_regression_model')PyCaret setup() 参数深度分析 | Deep Dive into PyCaret setup() Parameters
本文档详细解释 PyCaret setup() 函数中各个参数的不同取值对 AutoML 结果的影响,帮助用户根据实际场景做出最佳选择。
文档基于 PyCaret 3.0 官方 API 文档
---
1. 数据缺失值处理 | Imputation
imputation_type - 缺失值处理类型
| 值 | 说明 | 适用场景 | AutoML 影响 |
|---|---|---|---|
'simple' | 简单插补(默认) | 大多数场景 | 快速,适合数据缺失比例<30% |
'iterative' | 迭代插补(使用模型预测) | 缺失比例高、非随机缺失 | 更准确,但计算耗时 |
None | 不处理 | 数据已完整或有意保留 | 可能导致模型训练失败 |
numeric_imputation - 数值型缺失值填充
| 值 | 说明 | 适用场景 | AutoML 影响 |
|---|---|---|---|
'mean' | 均值填充(默认) | 数据近似正态分布 | 保持均值,可能放大异常值影响 |
'median' | 中位数填充 | 存在极端值/偏态分布 | 鲁棒性好,推荐金融/医疗数据 |
'mode' | 众数填充 | 离散数值或存在高频值 | 可能扭曲分布 |
'knn' | K近邻填充 | 特征间有相关性 | 更准确,但大数据集耗时 |
'drop' | 删除含缺失的行 | 缺失比例<5% | 丢失数据,不推荐 |
int/float | 指定固定值 | 业务有明确填充规则 | 需领域知识 |
实战建议:
# 金融风控 - 建议用中位数
setup(data, numeric_imputation='median')
# 推荐系统 - 可用 knn
setup(data, numeric_imputation='knn')categorical_imputation - 类别型缺失值填充
| 值 | 说明 | 适用场景 | AutoML 影响 |
|---|---|---|---|
'mode' | 众数填充(默认) | 大多数场景 | 简单有效 |
'constant' | 填充为 "Unknown" | 缺失有业务含义 | 聚类任务默认用此值 |
'drop' | 删除含缺失的行 | 缺失极少 | 可能丢失重要模式 |
---
2. 数据划分策略 | Data Splitting
fold_strategy - 交叉验证策略
| 值 | 说明 | 适用场景 | AutoML 影响 |
|---|---|---|---|
'kfold' | 标准K折 | 回归任务、平衡数据 | 标准baseline |
'stratifiedkfold' | 分层K折(默认,分类) | 分类任务、不平衡数据 | 保持类别比例,更可靠 |
'groupkfold' | 分组K折 | 存在分组结构(患者/用户) | 防止数据泄露 |
'timeseries' | 时间序列分割 | 时间序列预测 | 防止未来信息泄露 |
实战建议:
# 分类任务(默认)
setup(data, fold_strategy='stratifiedkfold')
# 回归任务
setup(data, fold_strategy='kfold')
# 纵向数据(同一患者多次就诊)
setup(data, fold_strategy='groupkfold', fold_groups='patient_id')data_split_stratify - 分层抽样
| 值 | 说明 | AutoML 影响 |
|---|---|---|
True | 按目标变量分层(默认,分类) | 训练/测试集类别比例一致 |
False | 随机划分(默认,回归) | 可能导致类别分布不一致 |
['col1', 'col2'] | 按指定列分层 | 多列组合分层 |
---
3. 特征工程 | Feature Engineering
normalize_method - 归一化方法
| 值 | 说明 | 公式 | 适用场景 | AutoML 影响 |
|---|---|---|---|---|
'zscore' | Z-Score标准化(默认) | z = (x - μ) / σ | 大多数场景,数据近似正态 | 标准方法,均值0方差1 |
'minmax' | 最小最大缩放 | x' = (x - min) / (max - min) | 数据有边界,神经网络 | 值映射到[0,1] |
'maxabs' | 最大绝对值缩放 | x' = x / max(\ | x\ | ) |
'robust' | 鲁棒缩放 | x' = (x - Q1) / (Q3 - Q1) | 存在 outliers | 使用四分位距,对异常值鲁棒 |
实战建议:
# 标准场景
setup(data, normalize=True, normalize_method='zscore')
# 有异常值的数据
setup(data, normalize=True, normalize_method='robust')
# 稀疏矩阵/文本TF-IDF
setup(data, normalize=True, normalize_method='maxabs')transformation_method - 变换方法
| 值 | 说明 | 适用场景 | AutoML 影响 |
|---|---|---|---|
'yeo-johnson' | Yeo-Johnson变换(默认) | 可处理负值和零值 | 使数据更接近正态分布 |
'quantile' | 分位数变换 | 需要均匀分布 | 将数据映射到均匀/正态分布 |
何时使用 transformation=True:
- 特征严重偏态(skewness > 1)
- 线性模型(LR, SVM)表现不佳
- 某些算法对正态性有要求
pca_method - PCA降维方法
| 值 | 说明 | 适用场景 | AutoML 影响 |
|---|---|---|---|
'linear' | 线性PCA(默认) | 大多数场景 | 快速,效果好 |
'kernel' | 核PCA | 非线性关系 | 保留非线性结构,但耗时 |
'incremental' | 增量PCA | 大数据集(>100k行) | 内存友好 |
pca_components - PCA保留成分数
| 值 | 说明 | AutoML 影响 |
|---|---|---|
None | 保留所有成分 | 不降维,仅转换 |
int | 保留n个主成分 | 指定数量 |
float (0-1) | 保留解释方差比例 | 如0.95保留95%方差 |
'mle' | MLE自动选择 | 智能选择,可能较好 |
---
4. 特征选择 | Feature Selection
feature_selection_method - 特征选择方法
| 值 | 说明 | 适用场景 | AutoML 影响 |
|---|---|---|---|
'classic' | SelectFromModel(默认) | 大多数场景 | 使用LightGBM计算重要性 |
'univariate' | SelectKBest | 快速筛选 | 独立评估每个特征 |
'sequential' | 序列前向/后向选择 | 精确筛选 | 耗时,特征多时不可用 |
feature_selection_estimator - 特征重要性评估器
| 值 | 说明 | 适用场景 | AutoML 影响 |
|---|---|---|---|
'lightgbm' | LightGBM(默认) | 分类/回归 | 快速,效果好 |
'rf' | Random Forest | 需要可解释性 | 稳定,但稍慢 |
| 自定义 | sklearn estimator | 特殊需求 | 灵活 |
n_features_to_select - 选择特征数量
| 值 | 说明 | AutoML 影响 |
|---|---|---|
float (0-1) | 保留比例,如0.2保留20% | 常用推荐值 |
int | 保留数量 | 精确控制 |
---
5. 离群值处理 | Outlier Handling
outliers_method - 离群值检测方法
| 值 | 全称 | 原理 | 适用场景 | AutoML 影响 |
|---|---|---|---|---|
'iforest' | Isolation Forest | 隔离异常点 | 大数据、任意分布 | 快速高效,默认推荐 |
'ee' | Elliptic Envelope | 假设多元正态 | 数据接近正态分布 | 需要足够样本 |
'lof' | Local Outlier Factor | 局部密度偏差 | 簇状分布数据 | 计算复杂度高 |
outliers_threshold - 离群值比例
| 值 | 说明 | AutoML 影响 |
|---|---|---|
0.05 | 默认,移除5% | 平衡数据保留与清洗 |
0.01 | 保守,仅移除1% | 保留更多数据 |
0.1 | 激进,移除10% | 清洗更彻底 |
实战建议:
# 标准场景
setup(data, remove_outliers=True, outliers_threshold=0.05)
# 金融风控(异常重要)
setup(data, remove_outliers=True, outliers_method='lof')
# 大数据
setup(data, remove_outliers=True, outliers_method='iforest')---
6. 类别平衡 | Class Imbalance
fix_imbalance_method - 平衡方法
| 值 | 全称 | 原理 | 适用场景 | AutoML 影响 |
|---|---|---|---|---|
'SMOTE' | Synthetic Minority Oversampling | 插值生成新样本 | 少数类样本>1000 | 默认推荐,效果好 |
'SMOTENC' | SMOTE for Nominal and Continuous | 混合数据 | 含类别特征 | 混合数据首选 |
'ADASYN' | Adaptive Synthetic | 自适应生成 | 严重不平衡 | 聚焦难点样本 |
'RandomUnderSampler' | 随机下采样 | 删除多数类 | 多数类样本不多 | 可能丢失信息 |
何时使用 fix_imbalance=True:
- 少数类占比 < 20%
- 类别比例 > 1:10
- 评估指标选择 AUC/F1 而非 Accuracy
---
7. 多重共线性处理 | Multicollinearity
remove_multicollinearity - 移除高相关特征
| 值 | 说明 | AutoML 影响 |
|---|---|---|
True | 启用 | 移除相关性>threshold的特征 |
False | 禁用(默认) | 保留所有特征 |
multicollinearity_threshold - 相关性阈值
| 值 | 说明 | AutoML 影响 |
|---|---|---|
0.9 | 默认 | 移除高度相关的特征 |
0.95 | 宽松 | 保留更多特征 |
0.8 | 严格 | 更激进的特征筛选 |
---
8. 稀有类别处理 | Rare Category Handling
rare_to_value - 稀有类别阈值
| 值 | 说明 | AutoML 影响 |
|---|---|---|
None | 不处理 | 保留原始类别 |
0.05 | 少于5%视为稀有 | 合并稀有类别 |
0.1 | 少于10%视为稀有 | 更激进的合并 |
rare_value - 稀有类别替换值
| 值 | 说明 | AutoML 影响 |
|---|---|---|
'rare' | 替换为"rare"字符串 | 默认 |
'unknown' | 替换为"unknown" | 更易理解 |
---
9. 特殊特征处理 | Special Feature Handling
bin_numeric_features - 离散化数值特征
将连续数值特征转换为类别特征,使用 KMeans 聚类确定分割点。
setup(data, bin_numeric_features=['age', 'income'])AutoML 影响:
- 优点:可捕捉非线性关系
- 缺点:可能丢失信息
group_features - 分组特征
setup(data, group_features={'address': ['city', 'state', 'zip']})生成统计特征:min, max, mean, std, median, mode
ordinal_features - 有序类别
setup(data, ordinal_features={
'education': ['high_school', 'bachelor', 'master', 'phd'],
'income': ['low', 'medium', 'high']
})保留类别间的顺序信息。
---
10. GPU 配置 | GPU Configuration
use_gpu 参数
| 值 | 说明 | 支持算法 |
|---|---|---|
False | CPU计算(默认) | 所有算法 |
True | 自动选择GPU | XGBoost, CatBoost, LightGBM, LogisticRegression, Ridge, RF, KNN, SVM |
'force' | 强制GPU | 仅GPU算法,否则报错 |
注意:GPU仅在数据>50,000行时启用。
---
11. 完整参数组合示例 | Complete Parameter Combinations
典型分类任务
# 标准二分类
clf = setup(
data,
target='target',
train_size=0.8,
fold_strategy='stratifiedkfold',
fold=5,
numeric_imputation='mean',
categorical_imputation='mode',
normalize=True,
normalize_method='zscore',
fix_imbalance=True,
fix_imbalance_method='SMOTE',
session_id=42
)金融风控任务
# 金融风控 - 保守策略
clf = setup(
data,
target='fraud',
numeric_imputation='median', # 中位数,对异常值鲁棒
categorical_imputation='constant', # 缺失有含义
normalize=True,
normalize_method='robust', # 鲁棒缩放
remove_outliers=True,
outliers_method='lof', # 局部密度检测
outliers_threshold=0.02, # 保守
fix_imbalance=True,
fix_imbalance_method='SMOTE',
remove_multicollinearity=True,
multicollinearity_threshold=0.8, # 严格
session_id=42
)高维数据(特征>100)
# 高维数据
clf = setup(
data,
target='target',
pca=True,
pca_method='linear',
pca_components=0.95, # 保留95%方差
feature_selection=True,
feature_selection_method='classic',
n_features_to_select=0.3, # 保留30%
session_id=42
)时间紧迫,快速建模
# 快速建模
clf = setup(
data,
target='target',
preprocess=True, # 默认预处理
normalize=True,
fold=3, # 减少折数
turbo=True, # compare_models用turbo
session_id=42
)---
参数选择决策树
数据有缺失值?
├─ 是 → imputation_type='simple'
│ ├─ 数值型 → numeric_imputation='median' (有异常值) / 'mean' (正常)
│ └─ 类别型 → categorical_imputation='mode'
└─ 否 → 继续
数据不平衡?
├─ 是 → fix_imbalance=True
│ └─ fix_imbalance_method='SMOTE' (默认)
└─ 否 → 继续
数据有异常值?
├─ 是 → remove_outliers=True
│ ├─ 大数据 → outliers_method='iforest'
│ └─ 簇状分布 → outliers_method='lof'
└─ 否 → 继续
特征太多(>100)?
├─ 是 → pca=True / feature_selection=True
└─ 否 → 继续
特征需要缩放?
├─ 是 → normalize=True
│ ├─ 有异常值 → normalize_method='robust'
│ ├─ 稀疏数据 → normalize_method='maxabs'
│ └─ 其他 → normalize_method='zscore'
└─ 否 → 继续---
参考来源
- PyCaret 官方文档: https://pycaret.readthedocs.io/
- PyCaret API Reference: https://pycaret.readthedocs.io/en/latest/api/classification.html
PyCaret Time Series 模块 | Time Series Module
时间序列预测的完整 API 参考文档。
setup() 函数
from pycaret.time_series import setup
# 基础用法(不需要 target 参数)
ts = setup(data, fh=12)
# 完整参数
ts = setup(
# ===== 必需参数 =====
data, # Series 或 DataFrame(必需)
# ===== 目标指定 =====
target=None, # 目标列名(DataFrame 时必需)
index=None, # 日期索引列名
# ===== 时间序列特有参数 =====
fh=1, # 预测步长: 整数/列表
seasonal_period=None, # 季节周期: 整数/列表/'auto'
sp_detection='auto', # 季节检测方法
max_sp_to_consider=60, # 最大季节周期
remove_harmonics=False, # 移除谐波
harmonic_order_method='harmonic_max', # 谐波阶数方法
num_sps_to_use=1, # 使用的季节周期数
seasonality_type='mul', # 季节类型: 'add', 'mul'
point_alpha=None, # 点预测置信度
coverage=0.9, # 预测区间覆盖率
enforce_exogenous=True, # 是否强制使用外生变量
# ===== 交叉验证 =====
fold_strategy='expanding', # 折策略: 'expanding', 'sliding'
fold=3, # 折数
hyperparameter_split='all', # 超参分割: 'all', 'train', 'test'
ignore_seasonality_test=False, # 忽略季节性检验
# ===== 特征指定 =====
ignore_features=None, # 忽略的特征
# ===== 目标变量处理 =====
numeric_imputation_target=None, # 目标插补: 'drift', 'linear', 'mean', 'median', 'bfill', 'ffill'
transform_target=None, # 目标变换: 'box-cox', 'log', 'sqrt', 'exp', 'cos'
scale_target=None, # 目标缩放: 'zscore', 'minmax'
fe_target_rr=None, # 目标特征工程
# ===== 外生变量处理 =====
numeric_imputation_exogenous=None, # 外生变量插补
transform_exogenous=None, # 外生变量变换
scale_exogenous=None, # 外生变量缩放
fe_exogenous=None, # 外生变量特征工程
# ===== 系统选项 =====
n_jobs=-1,
use_gpu=False,
custom_pipeline=None,
html=True,
session_id=None,
log_experiment=False,
experiment_name=None,
experiment_custom_tags=None,
log_plots=False,
log_profile=False,
log_data=False,
engine=None,
verbose=True,
profile=False,
profile_kwargs={},
fig_kwargs={}
)常用模型
# 统计模型
'arima' # ARIMA
'auto_arima' # Auto ARIMA
'ets' # Exponential Smoothing
'theta' # Theta Method
'naive' # Naive Forecaster
'snaive' # Seasonal Naive
'grand_means' # Grand Means
'polytrend' # Polynomial Trend
# 机器学习模型
'exp_smooth' # Exponential Smoothing
'bulima' # Basic Unobserved Components
'lr' # Linear Regression
'ridge' # Ridge Regression
'lasso' # Lasso Regressioncompare_models()
from pycaret.time_series import compare_models
# 比较所有模型
best = compare_models()
# 指定模型
best = compare_models(include=['arima', 'ets', 'theta'])
# 参数
best = compare_models(
fold=3,
sort='SMAPE', # 排序指标: 'SMAPE', 'MAE', 'RMSE', 'MSE'
n_select=1
)create_model()
from pycaret.time_series import create_model
# 创建模型
arima = create_model('arima')
ets = create_model('ets')
# 带参数
arima = create_model('arima', seasonal_order=(1,1,1,12))tune_model()
from pycaret.time_series import tune_model
# 调优
tuned = tune_model(arima)plot_model() 图表类型
| 图表 | 说明 |
|---|---|
'ts' | 时间序列图 |
'tsacf' | ACF 图 |
'tspacf' | PACF 图 |
'decomp' | 分解图 |
'diagnostics' | 诊断图 |
'cv' | 交叉验证图 |
'forecast' | 预测图 |
'residuals' | 残差图 |
check_stats()
from pycaret.time_series import check_stats
# 平稳性检验
stats = check_stats()评估指标
| 指标 | 说明 |
|---|---|
| SMAPE | 对称平均绝对百分比误差 |
| MAE | 平均绝对误差 |
| RMSE | 均方根误差 |
| MSE | 均方误差 |
| R2 | R² 决定系数 |
完整工作流示例
from pycaret.time_series import *
# 1. 加载数据
data = get_data('airline')
# 2. 初始化
ts = setup(data, fh=12, seasonal_period=12)
# 3. 比较模型
best = compare_models()
# 4. 创建模型
model = create_model('arima')
# 5. 调优
tuned = tune_model(model)
# 6. 评估
evaluate_model(tuned)
# 7. 预测
predictions = predict_model(tuned, fh=24)
# 8. 保存
save_model(tuned, 'ts_model')预测参数
# 使用训练好的模型进行预测
predictions = predict_model(model, fh=24)
predictions = predict_model(model, horizon=24, step=1)PyCaret 通用工具函数 | Utility Functions
所有 PyCaret 模块通用的辅助函数和工具。
数据加载
get_data()
from pycaret.classification import get_data
# 列出所有可用数据集
all_datasets = get_data('index')
# 加载数据集
data = get_data('breast_cancer')
data = get_data('iris')
data = get_data('boston')
data = get_data('juice')
data = get_data('bank')
data = get_data('credit')配置管理
get_config()
from pycaret.classification import get_config
# 获取各种配置
X_train = get_config('X_train')
X_test = get_config('X_test')
y_train = get_config('y_train')
y_test = get_config('y_test')
pipeline = get_config('pipeline')
target = get_config('target_param')
# 所有可用配置
# 'X', 'X_train', 'X_test', 'y', 'y_train', 'y_test'
# 'X_train_transformed', 'X_test_transformed'
# 'target_param', 'pipeline', 'data', 'seed'
# 'n_jobs_param', 'html_param', 'master_pipeline'set_config()
from pycaret.classification import set_config
# 修改配置
set_config('seed', 123)
set_config('n_jobs_param', -1)
set_config('html_param', False)模型管理
models()
from pycaret.classification import models
# 获取所有可用模型
all_models = models()
# 只返回模型ID
model_ids = models()['ID'].tolist()get_metrics()
from pycaret.classification import get_metrics
# 获取所有指标
metrics = get_metrics()add_metric() / remove_metric()
from pycaret.classification import add_metric, remove_metric
# 添加自定义指标
add_metric(
name='my_metric',
score_func=my_score_function,
greater_is_better=True
)
# 删除指标
remove_metric('my_metric')日志与结果
pull()
from pycaret.classification import pull
# 获取评估结果
results = pull()get_logs()
from pycaret.classification import get_logs
# 获取实验日志
logs = get_logs()工具函数
pycaret.utils
from pycaret.utils import check_metric
from pycaret.utils import enable_colab, disable_colab
from pycaret.utils import version
# 检查指标
accuracy = check_metric(y_true, y_pred, 'Accuracy')
# Colab 优化
enable_colab()
disable_colab()
# 版本
print(version())check_fold()
from pycaret.classification import check_fold
fold_params = check_fold()模型部署
save_model()
from pycaret.classification import save_model
# 保存模型
save_model(model, 'my_model')
save_model(model, 'my_model', model_format='pickle')load_model()
from pycaret.classification import load_model
# 加载模型
loaded_model = load_model('my_model')deploy_model()
from pycaret.classification import deploy_model
# AWS
deploy_model(model, 'my_model', platform='aws',
authentication={'bucket_name': 'my-bucket'})
# GCP
deploy_model(model, 'my_model', platform='gcp',
authentication={'project': 'my-project', 'bucket': 'my-bucket'})
# Azure
deploy_model(model, 'my_model', platform='azure',
authentication={'storage_account': 'myaccount', 'container': 'mycontainer'})应用生成
create_app()
from pycaret.classification import create_app
# 创建 Streamlit 应用
app = create_app(model)create_api()
from pycaret.classification import create_api
# 创建 FastAPI
api = create_api(model, api_name='predict')create_docker()
from pycaret.classification import create_docker
# 创建 Docker 文件
docker_file = create_docker('my_model')完整 API 速查表
| 函数 | 功能 |
|---|---|
setup() | 初始化环境 |
get_data() | 加载数据集 |
models() | 获取可用模型 |
compare_models() | 比较模型 |
create_model() | 创建模型 |
tune_model() | 调优模型 |
ensemble_model() | 集成模型 |
blend_models() | 融合模型 |
stack_models() | 堆叠模型 |
automl() | 自动 ML |
predict_model() | 预测 |
evaluate_model() | 评估 |
plot_model() | 绘图 |
interpret_model() | 解释 |
finalize_model() | 最终训练 |
save_model() | 保存 |
load_model() | 加载 |
deploy_model() | 部署 |
get_config() | 获取配置 |
set_config() | 设置配置 |
pull() | 获取结果 |
get_logs() | 获取日志 |
get_metrics() | 获取指标 |
add_metric() | 添加指标 |
calibrate_model() | 校准模型 |
optimize_threshold() | 优化阈值 |
dashboard() | 仪表板 |
create_app() | 创建应用 |
create_api() | 创建 API |
create_docker() | 创建 Docker |