我来为你提供一个详细的PyCaret教学案例,通过一个完整的信用卡欺诈检测项目来讲解PyCaret的核心功能。
PyCaret 完整教学案例:信用卡欺诈检测
1. 环境准备和数据加载
# 安装PyCaret(首次使用)
# !pip install pycaret[full]
import pandas as pd
import numpy as np
from pycaret.classification import *
import warnings
warnings.filterwarnings('ignore')
# 加载数据集
# 这里使用一个模拟的信用卡交易数据集
# 实际生产中替换为你的数据源
data = pd.read_csv('https://raw.githubusercontent.com/pycaret/pycaret/master/datasets/credit.csv')
# 查看数据基本信息
print("数据集形状:", data.shape)
print("\n数据集前5行:")
print(data.head())
print("\n数据类型:")
print(data.dtypes)
print("\n目标变量分布:")
print(data['default'].value_counts())
2. 数据探索和预处理
# 检查缺失值
print("缺失值统计:")
print(data.isnull().sum())
# 检查数据不平衡情况
print("\n类别分布:")
print(data['default'].value_counts(normalize=True))
# 基础统计信息
print("\n数值特征统计:")
print(data.describe())
3. PyCaret环境初始化(最重要的步骤)
# setup函数是PyCaret的核心,它会自动完成大量预处理工作
clf1 = setup(
data=data, # 数据集
target='default', # 目标变量(要预测的列)
# 数据划分参数
train_size=0.8, # 80%用于训练
# 数据类型声明(PyCaret会自动推断,但明确声明更好)
numeric_features=['LIMIT_BAL', 'AGE', 'BILL_AMT1', 'BILL_AMT2',
'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6',
'PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4',
'PAY_AMT5', 'PAY_AMT6'],
categorical_features=['SEX', 'EDUCATION', 'MARRIAGE', 'PAY_0',
'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6'],
# 数据预处理参数
imputation_type='simple', # 缺失值填充策略:simple/iterative
numeric_imputation='mean', # 数值型缺失值用均值填充
categorical_imputation='mode', # 分类型缺失值用众数填充
# 特征工程参数
normalize=True, # 标准化数值特征
normalize_method='zscore', # 标准化方法:zscore/minmax/maxabs/robust
transformation=False, # 是否进行数据变换
handle_unknown_categorical=True, # 自动处理未知类别
remove_multicollinearity=True, # 移除多重共线性
multicollinearity_threshold=0.9, # 相关性阈值
# 类别不平衡处理
fix_imbalance=True, # 自动处理类别不平衡
fix_imbalance_method='smote', # 平衡方法:smote/adasyn等
# 特征选择
feature_selection=True, # 是否进行特征选择
feature_selection_threshold=0.8, # 特征重要性阈值
remove_outliers=False, # 是否移除异常值
# 验证策略
fold_strategy='stratifiedkfold', # 交叉验证策略
fold=5, # 5折交叉验证
# 其他参数
session_id=123, # 随机种子,确保结果可重现
log_experiment=False, # 是否记录实验日志
experiment_name='credit_fraud', # 实验名称
silent=True, # 静默模式
verbose=False # 是否显示详细信息
)
4. 模型比较和选择
# 比较多个模型的性能
# include参数指定要比较的模型,不指定则比较所有可用模型
best_model = compare_models(
include=['lr', 'rf', 'gbc', 'xgboost', 'lightgbm', 'dt', 'nb', 'svm'],
fold=5, # 交叉验证折数
round=4, # 结果保留小数位数
cross_validation=True, # 是否使用交叉验证
sort='Accuracy', # 排序指标
n_select=3, # 返回前3个最佳模型
budget_time=0.5, # 时间预算(分钟)
errors='ignore', # 错误处理方式
fit_kwargs=None, # 传递给fit方法的额外参数
groups=None, # 分组交叉验证
experiment_custom_tags=None # 自定义标签
)
# 查看最佳模型
print("最佳模型:", best_model)
5. 创建和训练单个模型
# 创建特定模型(以随机森林为例)
rf = create_model(
'rf', # 模型简称
fold=5, # 交叉验证折数
round=4, # 结果保留小数位数
cross_validation=True, # 使用交叉验证
fit_kwargs=None, # 额外的fit参数
groups=None, # 分组信息
probability_threshold=None, # 概率阈值
experiment_custom_tags=None # 自定义标签
)
# 查看模型详细信息
print("模型参数:")
print(rf.get_params())
6. 模型调优
# 超参数调优
tuned_rf = tune_model(
rf, # 要调优的模型
fold=5, # 交叉验证折数
round=4, # 结果保留小数位数
n_iter=10, # 搜索迭代次数
optimize='Accuracy', # 优化指标:Accuracy/AUC/Recall/Precision/F1/Kappa/MCC
custom_grid=None, # 自定义参数网格
choose_better=True, # 自动选择更好的模型
return_tuner=False, # 是否返回调优器对象
verbose=True, # 显示进度
tuner_verbose=True, # 调优器详细信息
early_stopping=False, # 早停策略
early_stopping_max_iters=10 # 早停最大迭代次数
)
# 查看调优后的参数
print("\n调优后的参数:")
print(tuned_rf.get_params())
7. 模型集成
# 创建集成模型(提高性能)
# Bagging集成
bagged_model = ensemble_model(
tuned_rf,
method='Bagging', # 集成方法:Bagging/Boosting
fold=5, # 交叉验证折数
n_estimators=10, # 基学习器数量
round=4, # 结果保留小数位数
choose_better=True, # 自动选择更好的模型
optimize='Accuracy', # 优化指标
fit_kwargs=None, # 额外的fit参数
groups=None, # 分组信息
verbose=False # 是否显示详细信息
)
# 混合模型(Blending)
# 首先创建多个基础模型
lr = create_model('lr')
dt = create_model('dt')
nb = create_model('nb')
# 创建混合模型
blended_model = blend_models(
estimator_list=[tuned_rf, lr, dt, nb], # 模型列表
fold=5, # 交叉验证折数
round=4, # 结果保留小数位数
choose_better=True, # 自动选择更好的模型
optimize='Accuracy', # 优化指标
method='soft', # 投票方式:soft/hard
weights=None, # 模型权重
fit_kwargs=None, # 额外的fit参数
groups=None, # 分组信息
verbose=True # 显示详细信息
)
8. 模型评估和可视化
# 评估模型性能
evaluate_model(tuned_rf)
# 生成各种可视化图表
# 混淆矩阵
plot_model(tuned_rf, plot='confusion_matrix', save=True)
# ROC曲线
plot_model(tuned_rf, plot='auc', save=True)
# 精确率-召回率曲线
plot_model(tuned_rf, plot='pr', save=True)
# 特征重要性
plot_model(tuned_rf, plot='feature', save=True)
# 学习曲线
plot_model(tuned_rf, plot='learning', save=True)
# 验证曲线
plot_model(tuned_rf, plot='vc', save=True)
# 决策边界(仅适用于2D数据)
# plot_model(tuned_rf, plot='boundary', save=True)
# 所有可用的图表类型
available_plots = ['auc', 'pr', 'confusion_matrix', 'error', 'class_report',
'boundary', 'rfe', 'learning', 'manifold', 'calibration',
'vc', 'dimension', 'feature', 'feature_all', 'parameter',
'lift', 'gain', 'tree']
9. 模型解释
# SHAP值解释(需要安装shap库)
interpret_model(tuned_rf, plot='summary') # SHAP摘要图
interpret_model(tuned_rf, plot='correlation') # 相关性图
interpret_model(tuned_rf, plot='reason', observation=0) # 单个样本解释
# 生成模型报告
# 创建完整的模型分析报告
from pycaret.utils import check_metric
metrics = check_metric(tuned_rf, metric='Accuracy')
print(f"模型准确率: {metrics}")
10. 预测和生产部署
# 在测试集上进行预测
predictions = predict_model(
tuned_rf, # 训练好的模型
data=None, # 默认使用测试集
probability_threshold=0.5, # 分类阈值
encoded_labels=True, # 是否编码标签
raw_score=False, # 是否返回原始分数
round=4, # 结果保留小数位数
verbose=True # 显示详细信息
)
# 查看预测结果
print(predictions.head())
# 最终化模型(在全部数据上重新训练)
final_model = finalize_model(tuned_rf)
# 保存模型
save_model(
final_model, # 要保存的模型
'credit_fraud_detector', # 模型名称(自动添加.pkl后缀)
model_only=False, # 是否只保存模型(False会保存完整pipeline)
verbose=True, # 显示详细信息
authentication=None # 云存储认证信息
)
# 加载模型
loaded_model = load_model(
'credit_fraud_detector', # 模型文件名
platform=None, # 云平台:aws/gcp/azure
authentication=None, # 认证信息
verbose=True # 显示详细信息
)
# 在新数据上进行预测
new_data = pd.DataFrame({
'LIMIT_BAL': [20000],
'SEX': [2],
'EDUCATION': [2],
'MARRIAGE': [1],
'AGE': [24],
'PAY_0': [2],
'PAY_2': [2],
'PAY_3': [-1],
'PAY_4': [-1],
'PAY_5': [-2],
'PAY_6': [-2],
'BILL_AMT1': [3913],
'BILL_AMT2': [3102],
'BILL_AMT3': [689],
'BILL_AMT4': [0],
'BILL_AMT5': [0],
'BILL_AMT6': [0],
'PAY_AMT1': [0],
'PAY_AMT2': [689],
'PAY_AMT3': [0],
'PAY_AMT4': [0],
'PAY_AMT5': [0],
'PAY_AMT6': [0]
})
prediction = predict_model(loaded_model, data=new_data)
print("\n预测结果:")
print(prediction[['prediction_label', 'prediction_score']])
11. 生产环境API部署
# 创建API(使用FastAPI)
create_api(final_model, 'credit_api')
# 创建Docker容器
create_docker('credit_api')
# 部署到云平台
# deploy_model(
# final_model,
# model_name='credit_fraud_detector',
# platform='aws', # 平台:aws/gcp/azure
# authentication={'bucket': 'my-bucket'}
# )
12. 批量预测(生产环境常用)
# 准备批量数据
batch_data = data.sample(100).drop('default', axis=1)
# 批量预测
batch_predictions = predict_model(
loaded_model,
data=batch_data,
raw_score=True # 同时返回概率分数
)
# 保存预测结果
batch_predictions.to_csv('predictions.csv', index=False)
print("