RailWise KB已发布
AI模型训练与调优工具
RailWise AI模型训练与调优工具提供完整的机器学习模型生命周期管理,包括数据准备、特征工程、模型训练、超参数调优、模型评估和部署上线。支持变形预测、异常检测、图像识别等多种监测场景的模型开发。
ai-guide
AI模型训练与调优工具
Section titled “AI模型训练与调优工具”AI模型训练与调优工具是 RailWise 提供的机器学习模型全生命周期管理平台,面向数据科学家、AI工程师和高级监测工程师。工具提供从数据准备、特征工程、模型训练、超参数调优到模型部署的完整工作流,支持变形预测、异常检测、图像识别等多种监测场景的模型开发。
| 场景 | 说明 | 模型类型 |
|---|---|---|
| 变形预测 | 基于历史数据预测未来变形 | 时间序列模型 |
| 异常检测 | 检测测量数据中的异常模式 | 分类/自编码器 |
| 预警判定 | 自动判定预警等级 | 分类模型 |
| 图像识别 | 裂缝识别、位移标识别 | 计算机视觉模型 |
| 数据补全 | 缺失数据插值 | 生成模型 |
| 趋势分类 | 变形趋势类型识别 | 分类模型 |
| 设备故障预测 | 预测设备故障 | 生存分析 |
| 施工风险预测 | 预测施工风险等级 | 集成学习 |
| 项目 | 版本 |
|---|---|
| AI模型训练与调优工具 | 1.5.0 |
| Python | 3.11+ |
| PyTorch | 2.2+ |
| Scikit-learn | 1.4+ |
| Optuna | 3.5+ |
| MLflow | 2.12+ |
| 功能模块 | 说明 | 技术实现 |
|---|---|---|
| 数据准备 | 数据清洗、标注、划分 | Pandas + 自定义工具 |
| 特征工程 | 特征提取、选择、转换 | Scikit-learn + 自定义 |
| 模型训练 | 多种模型训练 | PyTorch + Scikit-learn |
| 超参数调优 | 自动超参数搜索 | Optuna + Ray Tune |
| 模型评估 | 多维度模型评估 | 自定义评估指标 |
| 模型管理 | 模型版本管理 | MLflow |
| 模型部署 | 模型导出与部署 | ONNX + Triton |
| 实验跟踪 | 实验记录与对比 | MLflow Tracking |
| 自动机器学习 | 自动化模型选择 | AutoML |
支持的模型类型
Section titled “支持的模型类型”| 模型类型 | 算法 | 适用场景 |
|---|---|---|
| 时间序列预测 | ARIMA, Prophet, LSTM, N-BEATS | 变形预测 |
| 异常检测 | Isolation Forest, Autoencoder, VAE | 异常检测 |
| 分类 | Random Forest, XGBoost, LightGBM | 预警判定 |
| 回归 | Linear Regression, SVR, MLP | 数值预测 |
| 计算机视觉 | ResNet, YOLO, U-Net | 图像识别 |
| 生成模型 | GAN, Diffusion | 数据增强 |
| 集成学习 | Stacking, Blending | 综合预测 |
┌─────────────────────────────────────────────────────────────────────┐│ AI模型训练与调优工具架构 │├─────────────────────────────────────────────────────────────────────┤│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ││ │ 数据层 │ │ 实验管理 │ │ 模型仓库 │ ││ │ - 原始数据 │ │ - MLflow │ │ - 版本管理 │ ││ │ - 特征存储 │ │ - 实验跟踪 │ │ - 模型注册 │ ││ │ - 标注数据 │ │ - 参数记录 │ │ - 模型部署 │ ││ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ ││ │ │ │ ││ └──────────────────┼──────────────────┘ ││ ▼ ││ ┌──────────────────────────────┐ ││ │ 训练引擎 │ ││ │ 数据加载 → 训练 → 评估 → 保存 │ ││ └──────────────┬───────────────┘ ││ │ ││ ┌───────────────────┼───────────────────┐ ││ ▼ ▼ ▼ ││ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ││ │ 传统机器学习 │ │ 深度学习 │ │ 自动机器学习 │ ││ │ - Scikit-learn│ │ - PyTorch │ │ - AutoML │ ││ │ - XGBoost │ │ - Transformers│ │ - NAS │ ││ │ - LightGBM │ │ - ONNX │ │ - 自动特征工程│ ││ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ ││ │ │ │ ││ └──────────────────┼──────────────────┘ ││ ▼ ││ ┌──────────────────────────────┐ ││ │ 超参数优化 │ ││ │ Optuna / Ray Tune / Hyperopt │ ││ └──────────────────────────────┘ │└─────────────────────────────────────────────────────────────────────┘| 项目 | 最低要求 | 推荐配置 |
|---|---|---|
| Python | 3.11 | 3.12 |
| 内存 | 16 GB | 64 GB |
| 磁盘 | 50 GB | 500 GB |
| GPU | 可选 | NVIDIA CUDA 12+,显存8GB+ |
| 操作系统 | Ubuntu 22.04 | Ubuntu 22.04 / CentOS 8 |
# 创建虚拟环境python -m venv railwise-mlsource railwise-ml/bin/activate
# 安装基础包pip install railwise-ml
# 安装完整版(包含深度学习)pip install "railwise-ml[deep-learning]"
# 安装GPU版本pip install "railwise-ml[gpu]"
# 验证安装python -c "import railwise_ml; print(railwise_ml.__version__)"# 核心依赖pip install numpy pandas scikit-learn
# 深度学习pip install torch torchvision torchaudio
# 梯度提升pip install xgboost lightgbm catboost
# 超参数优化pip install optuna ray[tune]
# 实验跟踪pip install mlflow
# 模型部署pip install onnx onnxruntime tritonclient
# 可视化pip install matplotlib seaborn tensorboard初始化训练环境
Section titled “初始化训练环境”from railwise_ml import ModelTrainerfrom railwise_ml.config import TrainingConfig
# 配置训练环境config = TrainingConfig( project_name="deformation_prediction", experiment_name="lstm_v2", tracking_uri="http://mlflow.railwise.cn:5000", device="cuda", # 或 "cpu" random_seed=42)
# 创建训练器trainer = ModelTrainer(config)from railwise_ml.data import DataLoader
# 加载数据data_loader = DataLoader( source="tsm", # 或 "file", "database" api_key="rw_tsm_xxxxxxxx", base_url="https://tsm.railwise.cn")
# 获取项目数据data = data_loader.load_project_data( project_id="proj_rw_2026_001", point_ids=["P1", "P2", "P3"], date_range=("2024-01-01", "2026-07-08"), features=["settlement", "rate", "acceleration", "temperature", "rainfall"])
# 数据预处理processed_data = data_loader.preprocess( data=data, missing_strategy="interpolate", outlier_strategy="winsorize", normalization="standard", sequence_length=24 # 时间序列长度)
# 划分数据集train_data, val_data, test_data = data_loader.split( data=processed_data, train_ratio=0.7, val_ratio=0.15, test_ratio=0.15, shuffle=False # 时间序列不随机打乱)from railwise_ml.features import FeatureEngineer
# 创建特征工程器fe = FeatureEngineer()
# 自动特征工程auto_features = fe.auto_engineer( data=train_data, target="settlement", max_features=50, methods=["statistical", "temporal", "interaction"])
# 手动特征工程fe.add_feature("rolling_mean_7d", lambda df: df["settlement"].rolling(7).mean())fe.add_feature("rolling_std_7d", lambda df: df["settlement"].rolling(7).std())fe.add_feature("rate_of_change", lambda df: df["settlement"].diff())fe.add_feature("acceleration", lambda df: df["settlement"].diff().diff())
# 特征选择selected_features = fe.select_features( method="mutual_info", # 或 "correlation", "lasso", "rf_importance" k=20 # 选择前20个特征)
print(f"选择特征: {selected_features}")from railwise_ml.models import LSTMModel, TrainingPipeline
# 定义模型model = LSTMModel( input_size=len(selected_features), hidden_size=128, num_layers=2, output_size=1, # 预测1个时间步 dropout=0.2)
# 训练配置training_config = { "epochs": 100, "batch_size": 32, "learning_rate": 0.001, "optimizer": "adam", "scheduler": "reduce_on_plateau", "early_stopping_patience": 10, "loss_function": "mse"}
# 训练管道pipeline = TrainingPipeline( model=model, config=training_config, trainer=trainer)
# 训练history = pipeline.train( train_data=train_data, val_data=val_data, callbacks=["tensorboard", "checkpoint", "early_stopping"])
# 查看训练历史print(f"最佳验证损失: {history.best_val_loss:.4f}")print(f"最佳epoch: {history.best_epoch}")from railwise_ml.tuning import HyperparameterTuner
# 定义超参数搜索空间def objective(trial): # 模型参数 hidden_size = trial.suggest_int("hidden_size", 64, 256) num_layers = trial.suggest_int("num_layers", 1, 4) dropout = trial.suggest_float("dropout", 0.1, 0.5)
# 训练参数 learning_rate = trial.suggest_float("learning_rate", 1e-5, 1e-2, log=True) batch_size = trial.suggest_categorical("batch_size", [16, 32, 64])
# 创建模型并训练 model = LSTMModel( input_size=len(selected_features), hidden_size=hidden_size, num_layers=num_layers, dropout=dropout )
pipeline = TrainingPipeline( model=model, config={ "epochs": 50, "batch_size": batch_size, "learning_rate": learning_rate } )
history = pipeline.train(train_data, val_data) return history.best_val_loss
# 创建调优器tuner = HyperparameterTuner( study_name="lstm_optimization", direction="minimize", n_trials=100, pruner="median" # 早停策略)
# 执行调优best_params = tuner.optimize(objective)
print(f"最优超参数: {best_params}")from railwise_ml.evaluation import ModelEvaluator
# 创建评估器evaluator = ModelEvaluator(metrics=["mse", "mae", "rmse", "mape", "r2"])
# 评估模型results = evaluator.evaluate( model=model, test_data=test_data, visualize=True)
print("=== 模型评估结果 ===")print(f"MSE: {results.mse:.4f}")print(f"MAE: {results.mae:.4f}")print(f"RMSE: {results.rmse:.4f}")print(f"MAPE: {results.mape:.2f}%")print(f"R²: {results.r2:.4f}")
# 可视化评估结果evaluator.plot_predictions( actual=test_data.y, predicted=results.predictions, output="./evaluation/predictions.png")
evaluator.plot_residuals( residuals=results.residuals, output="./evaluation/residuals.png")模型保存与加载
Section titled “模型保存与加载”# 保存模型trainer.save_model( model=model, path="./models/lstm_v2.pth", metadata={ "version": "2.0", "features": selected_features, "metrics": results.to_dict(), "training_config": training_config })
# 加载模型loaded_model = trainer.load_model("./models/lstm_v2.pth")
# 导出为ONNXtrainer.export_onnx( model=model, path="./models/lstm_v2.onnx", input_shape=(1, 24, len(selected_features)) # (batch, seq_len, features))模型类型详解
Section titled “模型类型详解”1. 变形预测模型
Section titled “1. 变形预测模型”LSTM模型
Section titled “LSTM模型”from railwise_ml.models import LSTMModel
model = LSTMModel( input_size=10, # 输入特征数 hidden_size=128, # 隐藏层大小 num_layers=2, # LSTM层数 output_size=1, # 输出大小(预测1步) dropout=0.2, # Dropout率 bidirectional=True # 双向LSTM)适用场景: 中长期变形预测 优点: 能捕捉长期依赖 缺点: 训练较慢,需要较多数据
N-BEATS模型
Section titled “N-BEATS模型”from railwise_ml.models import NBEATSModel
model = NBEATSModel( input_size=24, # 输入序列长度 output_size=12, # 预测序列长度 hidden_size=128, n_stacks=3, # 堆叠数 n_blocks=3, # 每堆叠块数 n_layers=4 # 每块层数)适用场景: 多步预测 优点: 可解释性强,纯深度学习 缺点: 需要大量数据
Prophet模型
Section titled “Prophet模型”from railwise_ml.models import ProphetModel
model = ProphetModel( yearly_seasonality=True, weekly_seasonality=True, daily_seasonality=False, changepoint_prior_scale=0.05)适用场景: 有明确周期性的数据 优点: 可解释性强,无需调参 缺点: 对复杂模式效果有限
2. 异常检测模型
Section titled “2. 异常检测模型”from railwise_ml.models import AutoencoderModel
model = AutoencoderModel( input_size=10, encoder_layers=[64, 32, 16], decoder_layers=[16, 32, 64], activation="relu")适用场景: 无监督异常检测 优点: 无需标注数据 缺点: 对复杂异常模式效果有限
变分自编码器(VAE)
Section titled “变分自编码器(VAE)”from railwise_ml.models import VAEModel
model = VAEModel( input_size=10, latent_dim=8, encoder_layers=[64, 32], decoder_layers=[32, 64])适用场景: 生成式异常检测 优点: 能生成正常数据分布 缺点: 训练不稳定
3. 分类模型
Section titled “3. 分类模型”XGBoost
Section titled “XGBoost”from railwise_ml.models import XGBoostModel
model = XGBoostModel( n_estimators=100, max_depth=6, learning_rate=0.1, subsample=0.8, colsample_bytree=0.8)适用场景: 预警等级分类 优点: 训练快,效果好 缺点: 对时序数据不敏感
from railwise_ml.models import RandomForestModel
model = RandomForestModel( n_estimators=100, max_depth=10, min_samples_split=5)适用场景: 特征重要性分析 优点: 可解释性强 缺点: 可能过拟合
标准训练工作流
Section titled “标准训练工作流”from railwise_ml.workflow import TrainingWorkflow
# 定义工作流workflow = TrainingWorkflow( name="deformation_prediction_workflow", steps=[ { "name": "data_loading", "type": "data_loader", "config": { "source": "tsm", "project_id": "proj_rw_2026_001" } }, { "name": "preprocessing", "type": "preprocessor", "config": { "missing_strategy": "interpolate", "outlier_strategy": "winsorize" } }, { "name": "feature_engineering", "type": "feature_engineer", "config": { "methods": ["statistical", "temporal"], "max_features": 50 } }, { "name": "model_training", "type": "trainer", "config": { "model_type": "lstm", "epochs": 100, "batch_size": 32 } }, { "name": "evaluation", "type": "evaluator", "config": { "metrics": ["mse", "mae", "rmse", "mape"] } }, { "name": "model_registration", "type": "model_registry", "config": { "model_name": "deformation_lstm", "tags": ["production", "v2.0"] } } ])
# 执行工作流result = workflow.run()
print(f"工作流状态: {result.status}")print(f"模型版本: {result.model_version}")print(f"评估指标: {result.metrics}")自动机器学习(AutoML)
Section titled “自动机器学习(AutoML)”from railwise_ml.automl import AutoMLTrainer
# 创建AutoML训练器automl = AutoMLTrainer( task="regression", # 或 "classification", "forecasting" time_budget=3600, # 1小时预算 max_models=10, # 最多训练10个模型 ensemble=True # 启用集成)
# 自动训练leaderboard = automl.fit( train_data=train_data, val_data=val_data, test_data=test_data, target="settlement")
# 查看排行榜print("=== AutoML 排行榜 ===")for i, model in enumerate(leaderboard): print(f"{i+1}. {model.name}: {model.metric:.4f}")
# 获取最佳模型best_model = automl.get_best_model()print(f"最佳模型: {best_model.name}")from railwise_ml.tuning import GridSearchTuner
# 定义参数网格param_grid = { "hidden_size": [64, 128, 256], "num_layers": [1, 2, 3], "dropout": [0.1, 0.2, 0.3], "learning_rate": [0.001, 0.0001]}
# 创建网格搜索调优器tuner = GridSearchTuner( model_class=LSTMModel, param_grid=param_grid, scoring="neg_mean_squared_error", cv=3)
# 执行搜索best_params = tuner.fit(train_data, val_data)print(f"最优参数: {best_params}")from railwise_ml.tuning import BayesianOptimizer
# 定义搜索空间search_space = { "hidden_size": (64, 256), "num_layers": (1, 4), "dropout": (0.1, 0.5), "learning_rate": (1e-5, 1e-2), "batch_size": [16, 32, 64]}
# 创建贝叶斯优化器optimizer = BayesianOptimizer( model_class=LSTMModel, search_space=search_space, n_iterations=50, acquisition_function="ei" # Expected Improvement)
# 优化best_params = optimizer.optimize(train_data, val_data)print(f"最优参数: {best_params}")from railwise_ml.callbacks import EarlyStopping
early_stopping = EarlyStopping( monitor="val_loss", patience=10, min_delta=0.001, mode="min", restore_best_weights=True)
# 在训练中使用history = pipeline.train( train_data=train_data, val_data=val_data, callbacks=[early_stopping])模型评估与部署
Section titled “模型评估与部署”from railwise_ml.evaluation import cross_validate, plot_learning_curves
# 交叉验证cv_results = cross_validate( model=model, data=data, cv=5, metrics=["mse", "mae", "rmse"])
print(f"交叉验证 RMSE: {cv_results['rmse_mean']:.4f} ± {cv_results['rmse_std']:.4f}")
# 学习曲线plot_learning_curves( history=history, output="./evaluation/learning_curves.png")from railwise_ml.registry import ModelRegistry
# 创建模型注册表registry = ModelRegistry( tracking_uri="http://mlflow.railwise.cn:5000")
# 注册模型model_version = registry.register_model( model_name="deformation_lstm", model_path="./models/lstm_v2.pth", metrics={ "mse": results.mse, "mae": results.mae, "rmse": results.rmse, "mape": results.mape }, params=best_params, tags={ "stage": "production", "project": "proj_rw_2026_001", "version": "2.0" })
print(f"模型版本: {model_version}")from railwise_ml.deployment import ModelDeployer
# 创建部署器deployer = ModelDeployer( deployment_target="triton", # 或 "onnx", "torchserve" server_url="http://triton.railwise.cn:8000")
# 部署模型deployer.deploy( model_name="deformation_lstm", model_version=model_version, model_path="./models/lstm_v2.onnx", config={ "max_batch_size": 32, "instance_group": [{"count": 2, "kind": "GPU"}] })
# 测试部署test_input = torch.randn(1, 24, 10) # (batch, seq, features)prediction = deployer.predict( model_name="deformation_lstm", input=test_input)print(f"预测结果: {prediction}")与RAILWISE-TSM集成
Section titled “与RAILWISE-TSM集成”从TSM获取训练数据
Section titled “从TSM获取训练数据”from railwise_tsm import TSMClientfrom railwise_ml.data import TSMDataAdapter
# 创建TSM客户端tsm = TSMClient( base_url="https://tsm.railwise.cn", api_key="rw_tsm_xxxxxxxx")
# 创建数据适配器adapter = TSMDataAdapter(tsm_client=tsm)
# 获取训练数据training_data = adapter.get_training_data( project_ids=["proj_rw_2026_001", "proj_rw_2026_002"], point_types=["settlement", "displacement"], date_range=("2024-01-01", "2026-07-08"), include_environmental=True # 包含环境数据)
# 自动标注(基于预警记录)labeled_data = adapter.auto_label( data=training_data, label_type="alert_level" # 或 "anomaly", "trend")模型自动更新
Section titled “模型自动更新”from railwise_ml.pipeline import AutoRetrainingPipeline
# 创建自动重训练管道auto_retrain = AutoRetrainingPipeline( model_name="deformation_lstm", trigger_conditions={ "data_drift": 0.1, # 数据漂移阈值 "performance_degrade": 0.05, # 性能下降阈值 "schedule": "0 0 * * 0" # 每周日重训练 }, data_source=adapter)
# 启动自动重训练auto_retrain.start()1. 数据准备
Section titled “1. 数据准备”- 确保数据质量,处理缺失值和异常值
- 时间序列数据保持时间顺序
- 训练/验证/测试集按时间划分
- 特征工程前进行探索性数据分析
2. 模型选择
Section titled “2. 模型选择”| 场景 | 推荐模型 | 数据量要求 |
|---|---|---|
| 短期预测(1-3天) | ARIMA / Prophet | >100条 |
| 中期预测(3-14天) | LSTM / N-BEATS | >1000条 |
| 长期预测(>14天) | Ensemble | >5000条 |
| 异常检测 | Isolation Forest / Autoencoder | >500条 |
| 预警分类 | XGBoost / LightGBM | >1000条 |
| 图像识别 | ResNet / YOLO | >1000张 |
3. 防止过拟合
Section titled “3. 防止过拟合”# 使用正则化model = LSTMModel( input_size=10, hidden_size=128, dropout=0.3, # Dropout正则化 weight_decay=0.01 # L2正则化)
# 使用数据增强augmented_data = data_loader.augment( methods=["jitter", "scaling", "time_warp"], factor=2 # 数据量翻倍)
# 早停early_stopping = EarlyStopping(patience=10)4. 模型监控
Section titled “4. 模型监控”from railwise_ml.monitoring import ModelMonitor
monitor = ModelMonitor( model_name="deformation_lstm", metrics=["mse", "mae", "data_drift"])
# 监控模型性能monitor.check_performance( recent_data=last_week_data, threshold=0.1 # 性能下降10%报警)
# 监控数据漂移monitor.check_data_drift( reference_data=training_data, current_data=recent_data, threshold=0.05)限制与注意事项
Section titled “限制与注意事项”| 限制项 | 说明 |
|---|---|
| 数据量 | 深度学习模型需要至少1000条数据 |
| 训练时间 | 复杂模型可能需要数小时 |
| GPU资源 | 深度学习模型需要GPU加速 |
| 模型解释 | 深度学习模型可解释性较差 |
| 模型更新 | 建议每月评估模型性能 |
| 数据隐私 | 训练数据需脱敏处理 |
注意: 模型预测结果需结合工程经验判断,不能完全依赖模型输出。
Q1: 训练数据不足怎么办?
Section titled “Q1: 训练数据不足怎么办?”- 使用数据增强技术
- 迁移学习(使用预训练模型)
- 使用 simpler 模型(如ARIMA)
- 收集更多历史数据
# 数据增强augmented_data = data_loader.augment( methods=["jitter", "scaling", "time_warp", "magnitude_warp"], factor=5)Q2: 模型训练过慢?
Section titled “Q2: 模型训练过慢?”- 使用GPU加速
- 减小模型规模
- 使用更小的batch size
- 使用混合精度训练
# 混合精度训练from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
for batch in dataloader: with autocast(): output = model(batch) loss = criterion(output, target)
scaler.scale(loss).backward() scaler.step(optimizer) scaler.update()Q3: 模型效果不佳?
Section titled “Q3: 模型效果不佳?”- 检查数据质量
- 尝试不同的特征工程
- 调整模型架构
- 使用集成学习
Q4: 如何解释模型预测?
Section titled “Q4: 如何解释模型预测?”from railwise_ml.explainability import SHAPExplainer
# 使用SHAP解释模型explainer = SHAPExplainer(model)shap_values = explainer.explain(test_data)
# 可视化特征重要性explainer.plot_feature_importance( shap_values=shap_values, features=selected_features, output="./explanation/feature_importance.png")
# 解释单个预测explainer.explain_prediction( input_data=test_data[0], output="./explanation/prediction_explanation.png")| 版本 | 日期 | 变更内容 |
|---|---|---|
| 1.5.0 | 2026-07-08 | 新增N-BEATS模型;支持AutoML;优化超参数调优 |
| 1.0.0 | 2026-03-20 | 初始版本发布;支持LSTM、XGBoost、Prophet |
技术支持: 如有疑问,请联系 RailWise 技术支持团队
- 邮箱:support@railwise.cn
- 电话:0574-XXXXXXXX
- 文档反馈:GitHub Issues
