Day23 机器学习流水线(管道/pipeline)

发布于:2025-09-02 ⋅ 阅读:(22) ⋅ 点赞:(0)

以后只作为问题笔记

1.导入库,包括Pipeline 和相关预处理工具

2.分离xy,划分数据集

3.定义预处理:(构建小转换器)

   构建处理有序特征的 Pipeline: 先填充缺失值,再进行标签编码

   构建处理标称特征的 Pipeline: 先填充缺失值,再进行独热编码

   构建处理连续特征的 Pipeline: 先填充缺失值,再进行标准化

4.构建 ColumnTransformer---将不同的预处理应用于不同的列子集,构造一个完备的列转化器(小的组成大转换器)

5.构建完整管道,将预处理器和模型串联起来

6.使用 Pipeline 进行训练和评估

【数据挖掘】sklearn中超级方便的pipeline机制!_哔哩哔哩_bilibili

在构建完完整的pipeline后,调用其的规则语法:

当构建完完整的 Pipeline后,调用它的核心语法遵循 “估计器(Estimator)” 的通用规则,主要通过 fit()transform()fit_transform() 三个方法完成数据处理,对于包含模型的管道,还可以用 predict() 等方法进行预测。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import time # 导入 time 库
import warnings
warnings.filterwarnings("ignore")
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False # 防止负号显示问题

# 导入 Pipeline 和相关预处理工具
from sklearn.pipeline import Pipeline #  用于创建机器学习工作流
from sklearn.compose import ColumnTransformer # 用于将不同的预处理应用于不同的列,之前是对datafame的某一列手动处理,如果在pipeline中直接用standardScaler等函数就会对所有列处理,所以要用到这个工具
from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder, StandardScaler # 用于数据预处理
from sklearn.impute import SimpleImputer # 用于处理缺失值

# 机器学习相关库
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
from sklearn.model_selection import train_test_split # 只导入 train_test_split


# --- 加载原始数据 ---
data = pd.read_csv('data.csv')
y = data['Credit Default']
X = data.drop(['Credit Default'], axis=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)


# --- 定义不同列的类型和它们对应的预处理步骤 (这些将被放入 Pipeline 的 ColumnTransformer 中) --- 这些定义是基于原始数据 X 的列类型来确定的
object_cols = X.select_dtypes(include=['object']).columns.tolist()

ordinal_features = ['Home Ownership', 'Years in current job', 'Term']
ordinal_categories = [
    ['Own Home', 'Rent', 'Have Mortgage', 'Home Mortgage'], # Home Ownership 的顺序 (对应1, 2, 3, 4)
    ['< 1 year', '1 year', '2 years', '3 years', '4 years', '5 years', '6 years', '7 years', '8 years', '9 years', '10+ years'], # Years in current job 的顺序 (对应1-11)
    ['Short Term', 'Long Term'] # Term 的顺序 (对应0, 1)
]
ordinal_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')), # 用众数填充分类特征的缺失值
    ('encoder', OrdinalEncoder(categories=ordinal_categories, handle_unknown='use_encoded_value', unknown_value=-1))
])


# 分类特征 
nominal_features = ['Purpose'] # 使用原始列名
nominal_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')), # 用众数填充分类特征的缺失值
    ('onehot', OneHotEncoder(handle_unknown='ignore', sparse_output=False)) # sparse_output=False 使输出为密集数组
])

# 连续特征 ,从X的列中排除掉分类特征,得到连续特征列表
continuous_features = X.columns.difference(object_cols).tolist() # 原始X中非object类型的列
continuous_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')), # 用众数填充缺失值 (复现你的原始逻辑)
    ('scaler', StandardScaler()) # 标准化,一个好的实践
])

# --- 构建 ColumnTransformer --- 将不同的预处理应用于不同的列子集,构造一个完备的转化器
preprocessor = ColumnTransformer(
    transformers=[
        ('ordinal', ordinal_transformer, ordinal_features),
        ('nominal', nominal_transformer, nominal_features),
        ('continuous', continuous_transformer, continuous_features)
    ],
    remainder='passthrough' # 保留没有在transformers中指定的列(如果存在的话),或者 'drop' 丢弃
)

# --- 构建完整的 Pipeline ---
pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor), # 第一步:应用所有的预处理 (ColumnTransformer)
    ('classifier', RandomForestClassifier(random_state=42)) # 第二步:随机森林分类器
])

# --- 1. 使用 Pipeline 在划分好的训练集和测试集上评估 ---
pipeline.fit(X_train, y_train)
pipeline_pred = pipeline.predict(X_test)

print(classification_report(y_test, pipeline_pred))
print(confusion_matrix(y_test, pipeline_pred))

管道工程中pipeline类接收的是一个包含多个小元组的 列表 作为输入

可以这样理解这个结构:

1. 列表 []: 定义了步骤执行的先后顺序。Pipeline 会按照列表中的顺序依次处理数据。之所以用列表,是未来可以对这个列表进行修改。

2. 元组 (): 用于将每个步骤的名称和处理对象捆绑在一起。名称用于在后续访问或设置参数时引用该步骤,而对象则是实际执行数据转换或模型训练的工具。固定了操作名+操作

不用字典因为字典是无序的。


网站公告

今日签到

点亮在社区的每一天
去签到