| name | automl-skill |
| description | AutoML 自动化机器学习技能 | Automated Machine Learning Skill. 基于 PyCaret 进行低代码机器学习建模,支持分类、回归、聚类、异常检测、时间序列预测、自然语言处理和关联规则挖掘等任务。 未来将集成更多 AutoML 库(如 AutoGluon、FLAML 等)。 当用户需要快速构建机器学习模型、自动化模型选择、超参数调优、模型集成、特征工程或进行 AutoML 实验时使用此技能。 适用于数据科学家、公民数据科学家、机器学习工程师和希望快速原型开发的人员。 触发关键词:AutoML、机器学习自动化、PyCaret、分类模型、回归模型、聚类、异常检测、时间序列、文本分类、模型调优、模型比较、特征选择、统计检验、显著性检验、A/B测试。 Trigger keywords in English: AutoML, automated machine learning, PyCaret, classification, regression, clustering, anomaly detection, time series forecasting, NLP, text mining, model tuning, model comparison, feature engineering, statistical test, significance testing, A/B testing.
|
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
X = sm.add_constant(X)
model = sm.OLS(y, X).fit()
print(model.summary())
广义线性模型 (GLM)
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_stat, p_value = stats.ttest_ind(group1, group2)
chi2, p_value, dof, expected = stats.chi2_contingency(contingency_table)
f_stat, p_value = stats.f_oneway(*groups)
时间序列分析
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.statespace.sarimax import SARIMAX
arima_model = ARIMA(train_data, order=(1,1,1)).fit()
forecast = arima_model.forecast(steps=12)
sarimax_model = SARIMAX(data, order=(1,1,1), seasonal_order=(1,1,1,12)).fit()
统计诊断
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)
混合效应模型 (随机效应)
from statsmodels.regression.mixed_linear_model import MixedLM
mixed_model = MixedLM(y, X, groups=group_var).fit()
PyCaret + statsmodels 组合使用
from pycaret.classification import *
clf = setup(data, target='target')
best = compare_models()
tuned = tune_model(best)
import statsmodels.api as sm
X_with_const = sm.add_constant(X_test)
sm_model = sm.Logit(y_test, X_with_const).fit(disp=0)
print(sm_model.summary())
支持的机器学习任务 | 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')
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',
categorical_imputation='mode',
remove_outliers=True,
outliers_method='iforest',
outliers_threshold=0.05,
fix_imbalance=True,
fix_imbalance_method='SMOTE',
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',
transformation=True,
transformation_method='yeo-johnson',
feature_selection=True,
feature_selection_method='classic',
n_features_to_select=0.2,
pca=True,
pca_method='linear',
pca_components=0.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',
choose_better=True,
n_iter=50
)
Step 8: 模型评估 | Model Evaluation
evaluate_model(tuned_model)
plot_model(tuned_model, plot='auc')
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
interpret_model(tuned_model)
interpret_model(tuned_model, plot='correlation')
interpret_model(tuned_model, plot='reason', observation=0)
Step 10: 模型集成 | Model Ensemble
bagged = ensemble_model(tuned_model, method='Bagging')
boosted = ensemble_model(tuned_model, method='Boosting')
blended = blend_models(
estimator_list=['lr', 'dt', 'rf', 'xgboost'],
method='soft',
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
save_model(final_model, 'my_model')
save_experiment('my_experiment')
loaded_model = load_model('my_model')
deploy_model(
final_model,
platform='aws',
authentication={
'bucket': 'my-bucket'
}
)
create_app(final_model, app_path='app.py')
create_api(final_model, api_name='predict', api_file='predict.py')
create_docker('my_model', docker_path='Dockerfile')
AutoML 完整流程示例 | Complete AutoML Pipeline Example
from pycaret.classification import *
import pandas as pd
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
print(f"训练集: {train.shape}, 测试集: {test.shape}")
print(f"缺失值:\n{train.isnull().sum()}")
print(f"目标分布:\n{train['target'].value_counts()}")
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
)
best = compare_models(sort='AUC')
tuned = tune_model(best, optimize='AUC', n_iter=30)
evaluate_model(tuned)
interpret_model(tuned)
final = finalize_model(tuned)
predictions = predict_model(final, data=test)
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
代码模板 | 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
- 数据预处理: 使用
normalize=True, remove_outliers=True 等参数
- 模型选择: 用
compare_models(turbo=True) 快速验证
- 超参数调优: 根据时间预算设置
n_iter
- 模型集成: 复杂任务使用
ensemble_model 或 stack_models
- 生产部署: 使用
finalize_model() 在全量数据上训练