1. 规范的文件命名

文件命名应遵循一致性原则,便于识别和搜索:

  • 使用小写字母,单词间用下划线分隔(snake_case)
  • 明确表达文件功能,避免模糊命名
  • 脚本文件以.py为扩展名,配置文件使用.yaml或.json

示例:

data_preprocessor.py      # 数据预处理脚本
model_trainer.py          # 模型训练脚本
hyperparameters.yaml      # 超参数配置文件
2. 规范的文件夹管理

推荐的 ML 项目目录结构:

project_name/
├── config/               # 配置文件目录
│   ├── model_config.yaml
│   └── data_config.yaml
├── data/                 # 数据目录
│   ├── raw/              # 原始数据
│   ├── processed/        # 处理后的数据
│   └── external/         # 外部数据
├── docs/                 # 文档目录
├── models/               # 模型文件目录
│   ├── trained/
│   └── saved/
├── notebooks/            # Jupyter笔记本
├── src/                  # 源代码目录
│   ├── __init__.py
│   ├── data/             # 数据处理模块
│   ├── models/           # 模型定义模块
│   ├── training/         # 训练相关模块
│   └── utils/            # 工具函数模块
├── tests/                # 测试代码
├── .gitignore
├── requirements.txt
└── README.md

3. 机器学习项目的拆分
将 ML 项目按功能拆分为独立模块,实现高内聚低耦合:

数据模块(data)
数据加载(loaders)
数据预处理(preprocessing)
特征工程(feature_engineering)
模型模块(models)
模型定义(definitions)
模型构建(builders)
模型评估(evaluation)
训练模块(training)
训练循环(train_loop)
优化器配置(optimizers)
学习率调度(lr_schedulers)
工具模块(utils)
日志工具(logging)
可视化工具(visualization)
通用函数(general_functions)
配置模块(config)
参数管理(parameter_management)
路径管理(path_management)


4. 编码格式和类型注解
遵循 PEP 8 编码规范,并使用类型注解提高代码可读性和可维护性:
 

from typing import List, Tuple, Optional, Dict
import pandas as pd
import numpy as np

def preprocess_data(
    df: pd.DataFrame,
    categorical_features: List[str],
    numerical_features: List[str],
    target_column: str
) -> Tuple[pd.DataFrame, pd.Series]:
    """
    预处理数据,区分特征和目标变量
    
    Args:
        df: 原始数据DataFrame
        categorical_features: 分类特征列名列表
        numerical_features: 数值特征列名列表
        target_column: 目标变量列名
        
    Returns:
        预处理后的特征DataFrame和目标变量Series
    """
    # 分离特征和目标变量
    X = df[categorical_features + numerical_features].copy()
    y = df[target_column].copy()
    
    return X, y

-------------------------------------------------------------------------------------------------------------------------------

下面是制作通用的pipeline

# 关键步骤
- 明确业务目标
- 定义成功指标(业务指标 + 技术指标)
- 确定问题类型(分类/回归/聚类等)
- 评估项目可行性

数据收集

class DataCollector:
    def __init__(self):
        self.data_sources = []
    
    def add_data_source(self, source_type, path_or_connection):
        """添加数据源:数据库、API、文件等"""
        pass
    
    def merge_data_sources(self):
        """整合多源数据"""
        pass
    
    def initial_data_check(self):
        """初步数据检查"""
        print(f"数据集形状: {self.data.shape}")
        print(f"缺失值情况:\n{self.data.isnull().sum()}")

数据探索与分析

class DataAnalyzer:
    def __init__(self, data):
        self.data = data
    
    def basic_statistics(self):
        """基础统计分析"""
        return {
            'describe': self.data.describe(),
            'info': self.data.info(),
            'dtypes': self.data.dtypes
        }
    
    def visualize_distributions(self):
        """分布可视化"""
        # 数值特征分布
        # 类别特征分布
        # 目标变量分析
        pass
    
    def correlation_analysis(self):
        """相关性分析"""
        pass

数据预处理

class DataPreprocessor:
    def __init__(self):
        self.scalers = {}
        self.encoders = {}
        self.imputers = {}
    
    def handle_missing_values(self, strategy='auto'):
        """处理缺失值"""
        strategies = {
            'mean': SimpleImputer(strategy='mean'),
            'median': SimpleImputer(strategy='median'),
            'most_frequent': SimpleImputer(strategy='most_frequent'),
            'knn': KNNImputer()
        }
    
    def encode_categorical(self, method='onehot'):
        """编码分类变量"""
        encoders = {
            'onehot': OneHotEncoder(),
            'label': LabelEncoder(),
            'target': TargetEncoder()
        }
    
    def feature_scaling(self, method='standard'):
        """特征缩放"""
        scalers = {
            'standard': StandardScaler(),
            'minmax': MinMaxScaler(),
            'robust': RobustScaler()
        }
    
    def create_pipeline(self):
        """创建预处理管道"""
        return Pipeline([
            ('imputer', SimpleImputer(strategy='median')),
            ('scaler', StandardScaler()),
            ('encoder', OneHotEncoder(handle_unknown='ignore'))
        ]) class DataPreprocessor:
    def __init__(self):
        self.scalers = {}
        self.encoders = {}
        self.imputers = {}
    
    def handle_missing_values(self, strategy='auto'):
        """处理缺失值"""
        strategies = {
            'mean': SimpleImputer(strategy='mean'),
            'median': SimpleImputer(strategy='median'),
            'most_frequent': SimpleImputer(strategy='most_frequent'),
            'knn': KNNImputer()
        }
    
    def encode_categorical(self, method='onehot'):
        """编码分类变量"""
        encoders = {
            'onehot': OneHotEncoder(),
            'label': LabelEncoder(),
            'target': TargetEncoder()
        }
    
    def feature_scaling(self, method='standard'):
        """特征缩放"""
        scalers = {
            'standard': StandardScaler(),
            'minmax': MinMaxScaler(),
            'robust': RobustScaler()
        }
    
    def create_pipeline(self):
        """创建预处理管道"""
        return Pipeline([
            ('imputer', SimpleImputer(strategy='median')),
            ('scaler', StandardScaler()),
            ('encoder', OneHotEncoder(handle_unknown='ignore'))
        ])

特征工程

class FeatureEngineer:
    def __init__(self):
        self.feature_selector = None
    
    def create_features(self, data):
        """创建新特征"""
        # 多项式特征
        # 交互特征
        # 时间特征
        # 文本特征
        pass
    
    def select_features(self, method='mutual_info'):
        """特征选择"""
        selectors = {
            'variance': VarianceThreshold(),
            'mutual_info': SelectKBest(mutual_info_classif, k=50),
            'rf_importance': SelectFromModel(RandomForestClassifier()),
            'pca': PCA(n_components=0.95)
        }

模型训练

class ModelTrainer:
    def __init__(self):
        self.models = {}
        self.best_model = None
    
    def initialize_models(self, problem_type):
        """初始化模型池"""
        if problem_type == 'classification':
            self.models = {
                'logistic': LogisticRegression(),
                'random_forest': RandomForestClassifier(),
                'xgboost': XGBClassifier(),
                'svm': SVC(),
                'lightgbm': LGBMClassifier()
            }
        elif problem_type == 'regression':
            self.models = {
                'linear': LinearRegression(),
                'random_forest': RandomForestRegressor(),
                'xgboost': XGBRegressor(),
                'lightgbm': LGBMRegressor()
            }
    
    def train_models(self, X_train, y_train):
        """训练多个模型"""
        trained_models = {}
        for name, model in self.models.items():
            model.fit(X_train, y_train)
            trained_models[name] = model
        return trained_models
    
    def hyperparameter_tuning(self, model, param_grid, cv=5):
        """超参数调优"""
        grid_search = GridSearchCV(
            model, param_grid, cv=cv, scoring='accuracy', n_jobs=-1
        )
        return grid_search

模型评估

class ModelEvaluator:
    def __init__(self):
        self.metrics = {}
    
    def calculate_metrics(self, y_true, y_pred, problem_type):
        """计算评估指标"""
        if problem_type == 'classification':
            return {
                'accuracy': accuracy_score(y_true, y_pred),
                'precision': precision_score(y_true, y_pred, average='weighted'),
                'recall': recall_score(y_true, y_pred, average='weighted'),
                'f1': f1_score(y_true, y_pred, average='weighted'),
                'roc_auc': roc_auc_score(y_true, y_pred)
            }
        elif problem_type == 'regression':
            return {
                'mse': mean_squared_error(y_true, y_pred),
                'rmse': np.sqrt(mean_squared_error(y_true, y_pred)),
                'mae': mean_absolute_error(y_true, y_pred),
                'r2': r2_score(y_true, y_pred)
            }
    
    def cross_validate(self, model, X, y, cv=5):
        """交叉验证"""
        return cross_val_score(model, X, y, cv=cv, scoring='accuracy')
    
    def plot_confusion_matrix(self, y_true, y_pred):
        """绘制混淆矩阵"""
        pass
    
    def plot_learning_curve(self, model, X, y):
        """绘制学习曲线"""
        pass

模型部署监控

class ModelDeployer:
    def __init__(self):
        self.pipeline = None
    
    def create_serving_pipeline(self, preprocessor, model):
        """创建服务管道"""
        self.pipeline = Pipeline([
            ('preprocessor', preprocessor),
            ('model', model)
        ])
        return self.pipeline
    
    def save_pipeline(self, filepath):
        """保存管道"""
        joblib.dump(self.pipeline, filepath)
    
    def load_pipeline(self, filepath):
        """加载管道"""
        self.pipeline = joblib.load(filepath)
        return self.pipeline
    
    def monitor_performance(self, X_new, y_new):
        """监控模型性能"""
        # 数据漂移检测
        # 概念漂移检测
        # 性能衰减监控
        pass

完整pipeline整合

class MLPipeline:
    def __init__(self, problem_type, target_column):
        self.problem_type = problem_type
        self.target_column = target_column
        self.collector = DataCollector()
        self.analyzer = None
        self.preprocessor = DataPreprocessor()
        self.feature_engineer = FeatureEngineer()
        self.trainer = ModelTrainer()
        self.evaluator = ModelEvaluator()
        self.deployer = ModelDeployer()
        
    def run_full_pipeline(self, data_paths):
        """运行完整pipeline"""
        print("🚀 开始机器学习Pipeline...")
        
        # 1. 数据收集
        print("1. 数据收集中...")
        data = self.collector.load_data(data_paths)
        
        # 2. EDA
        print("2. 数据探索分析中...")
        self.analyzer = DataAnalyzer(data)
        self.analyzer.full_analysis()
        
        # 3. 数据预处理
        print("3. 数据预处理中...")
        X_processed = self.preprocessor.full_preprocess(data)
        
        # 4. 特征工程
        print("4. 特征工程中...")
        X_features = self.feature_engineer.create_and_select_features(X_processed)
        
        # 5. 模型训练
        print("5. 模型训练中...")
        self.trainer.initialize_models(self.problem_type)
        trained_models = self.trainer.train_models(X_features, data[self.target_column])
        
        # 6. 模型评估
        print("6. 模型评估中...")
        best_model = self.evaluator.select_best_model(trained_models, X_features, data[self.target_column])
        
        # 7. 部署准备
        print("7. 部署准备中...")
        serving_pipeline = self.deployer.create_serving_pipeline(
            self.preprocessor.get_pipeline(), best_model
        )
        
        print("✅ Pipeline 完成!")
        return serving_pipeline

# 使用示例
if __name__ == "__main__":
    # 初始化pipeline
    pipeline = MLPipeline(problem_type='classification', target_column='target')
    
    # 运行完整流程
    model_pipeline = pipeline.run_full_pipeline(['data/train.csv', 'data/test.csv'])
    
    # 保存模型
    pipeline.deployer.save_pipeline('models/final_pipeline.pkl')

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐