首页 > 其他分享 >机器学习 - toad库

机器学习 - toad库

时间:2024-05-26 09:30:31浏览次数:11  
标签:plot 机器 toad utils 学习 ax 默认值 data

toad 是一个Python库,用于数据预处理和特征工程,特别是在金融风控和信用评分建模中应用广泛。
以下是 toad 库中主要函数的详细说明,包括它们的参数和作用:

数据转换与预处理

1. toad.transformer.WOETransformer

作用:将分类变量转换为WOE(Weight of Evidence)值,以便更好地用于模型训练。
参数

  • exclude: list, 默认值为空列表。需要排除在外的列。
  • min_samples: int, 默认值为0。每个分箱中的最小样本数。
  • n_bins: int, 默认值为10。每个变量的分箱数量。
  • woe: dict, 默认值为None。预定义的WOE字典。
woe = toad.transformer.WOETransformer()
data_woe = woe.fit_transform(data, target='default')
2. toad.transformer.Fillna

作用:填补缺失值。
参数

  • value: dict or scalar, 默认值为None。填补缺失值的策略或具体值。
fillna = toad.transformer.Fillna(value=0)
data_filled = fillna.fit_transform(data)
3. toad.transformer.TargetEncoder

作用:目标编码器,用于将分类变量编码为目标变量的平均值。
参数

  • cols: list, 默认值为空列表。需要编码的列。
  • target: str。目标列的名称。
  • min_samples: int, 默认值为1。每个类别的最小样本数。
target_encoder = toad.transformer.TargetEncoder(cols=['categorical_col'], target='default')
data_encoded = target_encoder.fit_transform(data)
4. toad.transformer.StandardScaler

作用:标准化数据。
参数

  • cols: list, 默认值为空列表。需要标准化的列。
  • with_mean: bool, 默认值为True。是否将数据均值归零。
  • with_std: bool, 默认值为True。是否将数据方差归一。
scaler = toad.transformer.StandardScaler(cols=['age', 'income'])
data_scaled = scaler.fit_transform(data)
5. toad.transformer.LabelEncoder

作用:标签编码器,用于将分类变量编码为整数。
参数

  • cols: list, 默认值为空列表。需要编码的列。
label_encoder = toad.transformer.LabelEncoder(cols=['categorical_col'])
data_encoded = label_encoder.fit_transform(data)
6. toad.utils.to_categorical

作用:将变量转换为分类变量。
参数

  • df: DataFrame。输入的数据集。
  • cols: list。需要转换的列。
data = toad.utils.to_categorical(data, cols=['age'])
7. toad.utils.fillna

作用:填补缺失值。
参数

  • df: DataFrame。输入的数据集。
  • value: dict or scalar, 默认值为None。填补缺失值的策略或具体值。
data_filled = toad.utils.fillna(data, value=0)
8. toad.utils.to_numeric

作用:将变量转换为数值类型。
参数

  • df: DataFrame。输入的数据集。
  • cols: list。需要转换的列。
numeric_data = toad.utils.to_numeric(data, cols=['age', 'income'])
9. toad.utils.to_categorical

作用:将变量转换为分类变量。
参数

  • df: DataFrame。输入的数据集。
  • cols: list。需要转换的列。
data = toad.utils.to_categorical(data, cols=['age'])
10. toad.utils.fillna

作用:填补缺失值。
参数

  • df: DataFrame。输入的数据集。
  • value: dict or scalar, 默认值为None。填补缺失值的策略或具体值。
data_filled = toad.utils.fillna(data, value=0)

分箱与合并

1. toad.transformer.Combiner

作用:将连续变量进行分箱处理。
参数

  • method: str, 默认值为’quantile’。分箱方法(例如,‘quantile’, ‘step’, ‘kmeans’)。
  • min_samples: int, 默认值为0。每个分箱中的最小样本数。
  • n_bins: int, 默认值为10。每个变量的分箱数量。
combiner = toad.transformer.Combiner()
combiner.fit(data, y='default')
data_binned = combiner.transform(data)
2. toad.transformer.Combine

作用:将两个变量进行合并。
参数

  • df: DataFrame。输入的数据集。
  • cols: list。需要合并的列。
  • name: str。新合并列的名称。
  • func: function。用于合并的函数,例如 summean 等。
combine = toad.transformer.Combine(cols=['col1', 'col2'], name='combined_col', func='sum')
data_combined = combine.fit_transform(data)
3. toad.transformer.Split

作用:将一个变量进行拆分。
参数

  • df: DataFrame。输入的数据集。
  • col: str。需要拆分的列。
  • sep: str。分隔符。
  • names: list。拆分后新列的名称。
split = toad.transformer.Split(col='combined_col', sep='_', names=['col1', 'col2'])
data_split = split.fit_transform(data)
4. toad.transformer.Bin

作用:对变量进行分箱。
参数

  • df: DataFrame。输入的数据集。
  • col: str。需要分箱的列。
  • n_bins: int, 默认值为10。分箱数量。
  • method: str, 默认值为’quantile’。分箱方法(例如,‘quantile’, ‘step’, ‘kmeans’)。
bin = toad.transformer.Bin(col='age', n_bins=5, method='quantile')
data_binned = bin.fit_transform(data)
5. toad.transformer.Combiner

作用:将连续变量进行分箱处理。
参数

  • method: str, 默认值为’quantile’。分箱方法(例如,‘quantile’, ‘step’, ‘kmeans’)。
  • min_samples: int, 默认值为0。每个分箱中的最小样本数。
  • n_bins: int, 默认值为10。每个变量的分箱数量。
combiner = toad.transformer.Combiner()
combiner.fit(data, y='default')
data_binned = combiner.transform(data)

特征选择

1. toad.selection.select

作用:特征选择工具,用于自动选择重要特征。
参数

  • target: str。目标列的名称。
  • empty: float, 默认值为0.9。缺失值比例的阈值。
  • iv: float, 默认值为0.02。信息值的阈值。
  • corr: float, 默认值为0.7。相关系数的阈值。
selected = toad.selection.select(data, target='default', empty=0.9, iv=0.02, corr=0.7)
2. toad.selection.stepwise

作用:逐步回归特征选择。
参数

  • X: DataFrame。特征矩阵。
  • y: Series。目标变量。
  • direction: str, 默认值为’both’。选择方向,可以是 ‘forward’、‘backward’ 或 ‘both’。
selected_features = toad.selection.stepwise(X, y, direction='both')
3. toad.selection.high_iv

作用:选择高信息值(IV)的特征。
参数

  • df: DataFrame。输入的数据集。
  • target: str。目标列的名称。
  • threshold: float, 默认值为0.02。IV值的阈值。
high_iv_features = toad.selection.high_iv(data, target='default', threshold=0.02)

模型评估

1. toad.metrics.ks

作用:计算KS(Kolmogorov-Smirnov)值。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
ks_value = toad.metrics.ks(y_true, y_pred)
2. toad.metrics.roc_auc_score

作用:计算AUC(Area Under Curve)。
参数

  • y_true: array-like。真实标签。
  • y_score: array-like。预测得分。
auc_score = toad.metrics.roc_auc_score(y_true, y_score)
3. toad.metrics.confusion_matrix

作用:计算混淆矩阵。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
conf_matrix = toad.metrics.confusion_matrix(y_true, y_pred)
4. toad.metrics.precision_score

作用:计算精确率。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
precision = toad.metrics.precision_score(y_true, y_pred)
5. toad.metrics.recall_score

作用:计算召回率。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
recall = toad.metrics.recall_score(y_true, y_pred)
6. toad.metrics.f1_score

作用:计算F1得分。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
f1 = toad.metrics.f1_score(y_true, y_pred)
7. toad.metrics.ks_bucket

**

作用**:计算KS分箱的KS值。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
  • n_bins: int, 默认值为10。分箱数量。
ks_buckets = toad.metrics.ks_bucket(y_true, y_pred, n_bins=10)

数据检测与处理

1. toad.utils.detect_categorical

作用:检测数据中的分类变量。
参数

  • df: DataFrame。输入的数据集。
  • exclude: list, 默认值为空列表。需要排除在外的列。
categorical_vars = toad.utils.detect_categorical(data)
2. toad.utils.drop_na

作用:删除包含缺失值的行或列。
参数

  • df: DataFrame。输入的数据集。
  • axis: int, 默认值为0。0表示删除行,1表示删除列。
  • how: str, 默认值为’any’。'any’表示只要有缺失值就删除,'all’表示全部缺失才删除。
clean_data = toad.utils.drop_na(data, axis=0, how='any')
3. toad.utils.clip

作用:裁剪数据。
参数

  • df: DataFrame。输入的数据集。
  • lower: float, 默认值为None。下限。
  • upper: float, 默认值为None。上限。
clipped_data = toad.utils.clip(data, lower=0, upper=100)
4. toad.utils.combine

作用:合并两个数据框。
参数

  • df1: DataFrame。第一个数据框。
  • df2: DataFrame。第二个数据框。
  • on: str or list。合并的键。
combined_data = toad.utils.combine(df1, df2, on='key_col')
5. toad.utils.drop_na

作用:删除包含缺失值的行或列。
参数

  • df: DataFrame。输入的数据集。
  • axis: int, 默认值为0。0表示删除行,1表示删除列。
  • how: str, 默认值为’any’。'any’表示只要有缺失值就删除,'all’表示全部缺失才删除。
clean_data = toad.utils.drop_na(data, axis=0, how='any')
6. toad.utils.clip

作用:裁剪数据。
参数

  • df: DataFrame。输入的数据集。
  • lower: float, 默认值为None。下限。
  • upper: float, 默认值为None。上限。
clipped_data = toad.utils.clip(data, lower=0, upper=100)
7. toad.utils.combine

作用:合并两个数据框。
参数

  • df1: DataFrame。第一个数据框。
  • df2: DataFrame。第二个数据框。
  • on: str or list。合并的键。
combined_data = toad.utils.combine(df1, df2, on='key_col')

数据可视化

1. toad.plot.ks_plot

作用:绘制KS曲线。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
  • ax: matplotlib Axes, 默认值为None。如果提供,则绘制在此轴上。
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
toad.plot.ks_plot(y_true, y_pred, ax=ax)
plt.show()
2. toad.plot.roc_plot

作用:绘制ROC曲线。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
  • ax: matplotlib Axes, 默认值为None。如果提供,则绘制在此轴上。
fig, ax = plt.subplots()
toad.plot.roc_plot(y_true, y_pred, ax=ax)
plt.show()
3. toad.plot.pr_plot

作用:绘制PR(Precision-Recall)曲线。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
  • ax: matplotlib Axes, 默认值为None。如果提供,则绘制在此轴上。
fig, ax = plt.subplots()
toad.plot.pr_plot(y_true, y_pred, ax=ax)
plt.show()
4. toad.plot.iv_plot

作用:绘制信息值(IV)曲线。
参数

  • iv: DataFrame。包含IV值的数据框。
  • threshold: float, 默认值为0。用于绘制阈值线。
  • ax: matplotlib Axes, 默认值为None。如果提供,则绘制在此轴上。
iv = toad.IV(data, target='default')
fig, ax = plt.subplots()
toad.plot.iv_plot(iv, threshold=0.02, ax=ax)
plt.show()
5. toad.plot.ks_plot

作用:绘制KS曲线。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
  • ax: matplotlib Axes, 默认值为None。如果提供,则绘制在此轴上。
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
toad.plot.ks_plot(y_true, y_pred, ax=ax)
plt.show()
6. toad.plot.roc_plot

作用:绘制ROC曲线。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
  • ax: matplotlib Axes, 默认值为None。如果提供,则绘制在此轴上。
fig, ax = plt.subplots()
toad.plot.roc_plot(y_true, y_pred, ax=ax)
plt.show()
7. toad.plot.pr_plot

作用:绘制PR(Precision-Recall)曲线。
参数

  • y_true: array-like。真实标签。
  • y_pred: array-like。预测标签。
  • ax: matplotlib Axes, 默认值为None。如果提供,则绘制在此轴上。
fig, ax = plt.subplots()
toad.plot.pr_plot(y_true, y_pred, ax=ax)
plt.show()
8. toad.plot.iv_plot

作用:绘制信息值(IV)曲线。
参数

  • iv: DataFrame。包含IV值的数据框。
  • threshold: float, 默认值为0。用于绘制阈值线。
  • ax: matplotlib Axes, 默认值为None。如果提供,则绘制在此轴上。
iv = toad.IV(data, target='default')
fig, ax = plt.subplots()
toad.plot.iv_plot(iv, threshold=0.02, ax=ax)
plt.show()

辅助函数

1. toad.utils.categorical

作用:获取数据集中所有分类变量的列名。
参数

  • df: DataFrame。输入的数据集。
categorical_columns = toad.utils.categorical(data)
2. toad.utils.continuous

作用:获取数据集中所有连续变量的列名。
参数

  • df: DataFrame。输入的数据集。
continuous_columns = toad.utils.continuous(data)
3. toad.utils.categorical

作用:获取数据集中所有分类变量的列名。
参数

  • df: DataFrame。输入的数据集。
categorical_columns = toad.utils.categorical(data)
4. toad.utils.continuous

作用:获取数据集中所有连续变量的列名。
参数

  • df: DataFrame。输入的数据集。
continuous_columns = toad.utils.continuous(data)

示例:信用评分模型

以下是一个使用 toad 库进行信用评分模型构建的完整示例,展示了从数据预处理、特征工程到模型训练和评估的全过程。

假设我们有一个信用评分的数据集,包含用户的基本信息、信用历史和是否违约的标记。我们将使用 toad 库来处理数据并构建一个逻辑回归模型。

步骤 1:导入必要的库
import pandas as pd
import toad
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, accuracy_score

# 示例数据集
data = pd.DataFrame({
    'age': [25, 45, 35, 50, 23, 34, 56, 28, 30, 40],
    'income': [50000, 100000, 75000, 120000, 30000, 60000, 110000, 50000, 54000, 90000],
    'loan_amount': [20000, 30000, 25000, 50000, 10000, 15000, 40000, 20000, 22000, 35000],
    'credit_score': [600, 700, 650, 750, 580, 620, 720, 640, 630, 710],
    'default': [0, 1, 0, 1, 0, 0, 1, 0, 0, 1]
})
步骤 2:数据预处理
  1. 填补缺失值
  2. 分箱处理
  3. 计算信息值并选择特征
# 填补缺失值
data = toad.utils.fillna(data, value=0)

# 分箱处理
combiner = toad.transformer.Combiner()
combiner.fit(data, y='default')
data_binned = combiner.transform(data)

# 计算信息值(IV)并选择特征
iv = toad.IV(data_binned, target='default')
selected_features = toad.selection.select(data_binned, target='default', iv=0.02)

print('Selected features:\n', selected_features)
步骤 3:WOE转换
# 使用WOETransformer进行WOE转换
woe = toad.transformer.WOETransformer()
data_woe = woe.fit_transform(selected_features, target='default')
步骤 4:分割数据集
# 分割数据集为训练集和测试集
X = data_woe.drop(columns=['default'])
y = data_woe['default']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
步骤 5:训练模型
# 训练逻辑回归模型
model = LogisticRegression()
model.fit(X_train, y_train)
步骤 6:模型评估
# 预测测试集
y_pred = model.predict(X_test)
y_pred_proba = model.predict_proba(X_test)[:, 1]

# 计算AUC和准确率
auc = roc_auc_score(y_test, y_pred_proba)
accuracy = accuracy_score(y_test, y_pred)

print(f'AUC: {auc:.2f}')
print(f'Accuracy: {accuracy:.2f}')
步骤 7:绘制KS曲线和ROC曲线
import matplotlib.pyplot as plt

# 绘制KS曲线
fig, ax = plt.subplots()
toad.plot.ks_plot(y_test, y_pred_proba, ax=ax)
plt.show()

# 绘制ROC曲线
fig, ax = plt.subplots()
toad.plot.roc_plot(y_test, y_pred_proba, ax=ax)
plt.show()

通过上述步骤,我们使用 toad 库完成了一个完整的信用评分模型的构建过程,包括数据预处理、特征工程、模型训练和评估。

更多问题咨询

Cos机器人

标签:plot,机器,toad,utils,学习,ax,默认值,data
From: https://blog.csdn.net/weixin_47552266/article/details/139150909

相关文章

  • 关于对于Java中Entity以及VO,以及DTO中Request对象序列化的学习
    关于Serializable的探讨前提引入是由于软件测试上有同学提到说,什么该字段在程序刚运行时,导致jvm激增,所以吸引了我的注意回顾代码MybatisPlusGenerator自动生成的entity中就经常带有这个,而且我在开发代码的时候VO,以及DTO常常是直接复制对应的entity,所以也保不齐我对应......
  • 【python】requests库学习
    一、GET请求1、当使用requests.get(url)方法发送GET请求时,它会向指定的URL发送一个HTTPGET请求,并返回一个包含服务器响应的Response对象。例如:​url="https://api.example.com/data"response=requests.get(url)2、添加URL参数:可以通过将参数作为字典传递给params参数......
  • 视差背景,GODOT游戏引擎学习笔记(五)
    背景图片资源今天周六玩了一天,现在晚上来更新一下帖子。前面几节我们学习了创建一个人物精灵节点使其移动。这节我们来学习创建背景。会用到三个图片文件。我已经上传到csdn了,链接如下:https://download.csdn.net/download/weixin_66990397/89356894?spm=1001.2014.3001.5501......
  • 开坑开坑,GODOT游戏引擎学习笔记(一)
    前言         本人重度游戏玩家,计科专业学生,玩了许多游戏已经逐渐电子羊尾,于是打算学习几个游戏引擎,一个方面是爱好,另一方面也是多掌握点技术。先打算从2D游戏开始学,目前引擎确定为GODOT,一个开源且适合新手的引擎。后续学习unity和虚幻等引擎也会继续更新,同时也会开......
  • Mybatis学习(史上超详细)
    1、Mybatis简介:1.1、MyBatis历史MyBatis最初是Apache的一个开源项目iBatis,2010年6月这个项目由ApacheSoftwareFoundation迁移到了GoogleCode。随着开发团队转投GoogleCode旗下,iBatis3.x正式更名为MyBatis。代码于2013年11月迁移到Github。iBatis一词来源于“internet”......
  • 产品经理如何学习大模型?——从“小白”到“大牛”的奇幻旅程
    引言在这个由数据驱动的时代,产品经理们面临着一个全新的挑战——大模型。想象一下,你是一名产品经理,站在一个由代码和算法构成的神秘岛屿前,准备开始一场探索之旅。这场旅程不仅需要勇气,还需要智慧和耐心。那么,如何从一个对大模型一无所知的“小白”成长为一个精通此道的“大......
  • git 入门学习(持续学习ing)
    目录为什么要学习使用Git?什么是Git?Git的下载和安装1.进入Git官网,并跳转到Windows版本下载界面2.下载64位Windows操作系统(也可以根据自己电脑实际信息进行选择)3.下载完成后,双击下载程序,一直点击下一步即可完成安装(一路回车法)4.安装完成后,在桌面空白处点击右键,会发现多了两个菜......
  • C++初阶学习第九弹——探索STL奥秘(四)——vector的深层挖掘和模拟实现
    string(上):C++初阶学习第六弹——探索STL奥秘(一)——标准库中的string类-CSDN博客string(下):C++初阶学习第七弹——探索STL奥秘(二)——string的模拟实现-CSDN博客vector(上):C++初阶学习第八弹——探索STL奥秘(三)——深入刨析vector的使用-CSDN博客前言:在前面我们已经学习了string的......
  • TypeScript 学习笔记(十一):TypeScript 与微服务架构的结合应用
    TypeScript学习笔记(十一):TypeScript与微服务架构的结合应用1.引言在前几篇学习笔记中,我们探讨了TypeScript的基础知识、前后端框架的结合应用、测试与调试技巧、数据库以及GraphQL的结合应用。本篇将重点介绍TypeScript与微服务架构的结合应用,包括如何使用TypeSc......
  • TypeScript 学习笔记(十二):TypeScript 与 DevOps 的结合应用
    TypeScript学习笔记(十二):TypeScript与DevOps的结合应用1.引言在前几篇学习笔记中,我们探讨了TypeScript的基础知识、前后端框架的结合应用、测试与调试技巧、数据库、GraphQL以及微服务架构的结合应用。本篇将重点介绍TypeScript与DevOps的结合应用,包括如何在D......