机器学习模型训练 ml-model-training

这个技能用于使用scikit-learn、PyTorch和TensorFlow等工具训练机器学习模型,涵盖数据准备、特征工程、模型选择、训练和评估全流程,适用于分类、回归、神经网络等任务,并包括超参数调优和解决过拟合、欠拟合等常见问题,关键词包括机器学习、模型训练、数据预处理、特征工程、深度学习。

机器学习 0 次安装 0 次浏览 更新于 3/7/2026

name: 机器学习模型训练 description: 使用scikit-learn、PyTorch、TensorFlow训练机器学习模型。适用于分类/回归、神经网络、超参数调优,或遇到过拟合、欠拟合、收敛问题时。 keywords: 机器学习, 模型训练, PyTorch, TensorFlow, scikit-learn, 神经网络, 深度学习, 分类, 回归, 超参数调优, 交叉验证, 模型评估, 数据预处理, 特征工程 license: MIT

机器学习模型训练

使用正确的数据处理和评估训练机器学习模型。

训练工作流程

  1. 数据准备 → 2. 特征工程 → 3. 模型选择 → 4. 训练 → 5. 评估

数据准备

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder

# 加载和清洗数据
df = pd.read_csv('data.csv')
df = df.dropna()

# 编码分类变量
le = LabelEncoder()
df['category'] = le.fit_transform(df['category'])

# 分割数据 (70/15/15)
X = df.drop('target', axis=1)
y = df['target']
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5)

# 缩放特征
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
X_test = scaler.transform(X_test)

Scikit-learn 训练

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score

model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

y_pred = model.predict(X_val)
print(classification_report(y_val, y_pred))

PyTorch 训练

import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self, input_dim):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(input_dim, 64),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(64, 32),
            nn.ReLU(),
            nn.Linear(32, 1),
            nn.Sigmoid()
        )

    def forward(self, x):
        return self.layers(x)

model = Model(X_train.shape[1])
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = nn.BCELoss()

for epoch in range(100):
    model.train()
    optimizer.zero_grad()
    output = model(X_train_tensor)
    loss = criterion(output, y_train_tensor)
    loss.backward()
    optimizer.step()

评估指标

任务 指标
分类 准确率, 精确率, 召回率, F1分数, AUC-ROC
回归 MSE, RMSE, MAE, R²

完整框架示例

  • PyTorch: 参见 references/pytorch-training.md 以获取完整训练流程,包括:

    • 带有BatchNorm和Dropout的自定义模型类
    • 带有早停的训练/验证循环
    • 学习率调度
    • 模型检查点保存
    • 完整的评估与分类报告
  • TensorFlow/Keras: 参见 references/tensorflow-keras.md 以获取:

    • 序列模型架构
    • 回调(EarlyStopping, ReduceLROnPlateau, ModelCheckpoint, TensorBoard)
    • 训练历史可视化
    • TFLite转换用于移动部署
    • 自定义训练循环

最佳实践

做:

  • 使用交叉验证进行鲁棒评估
  • 使用MLflow跟踪实验
  • 定期保存模型检查点
  • 监控过拟合
  • 记录超参数
  • 使用70/15/15的训练/验证/测试分割

不做:

  • 没有验证集进行训练
  • 忽略类别不平衡
  • 跳过特征缩放
  • 使用测试集进行超参数调优
  • 忘记设置随机种子

已知问题预防

1. 数据泄露

问题: 在分割数据之前缩放或转换数据,导致测试集信息泄露到训练中。

解决方案: 总是先分割数据,然后只在训练数据上拟合转换器:

# ✅ 正确:在训练集上拟合,在训练/验证/测试集上转换
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)  # 仅转换
X_test = scaler.transform(X_test)  # 仅转换

# ❌ 错误:在所有数据上拟合
X_all = scaler.fit_transform(X)  # 泄露测试信息!

2. 忽略类别不平衡

问题: 在类别不平衡的数据集上训练(例如,95%类别A,5%类别B)导致模型只预测多数类。

解决方案: 使用类别权重或重采样:

from sklearn.utils.class_weight import compute_class_weight

# 计算类别权重
class_weights = compute_class_weight('balanced', classes=np.unique(y_train), y=y_train)
model = RandomForestClassifier(class_weight='balanced')

# 或使用SMOTE对少数类进行过采样
from imblearn.over_sampling import SMOTE
smote = SMOTE()
X_resampled, y_resampled = smote.fit_resample(X_train, y_train)

3. 由于无正则化导致的过拟合

问题: 复杂模型记忆训练数据,在验证/测试集上表现差。

解决方案: 添加正则化技术:

# PyTorch中的Dropout
nn.Dropout(0.3)

# scikit-learn中的L2正则化
RandomForestClassifier(max_depth=10, min_samples_split=20)

# Keras中的早停
from tensorflow.keras.callbacks import EarlyStopping
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
model.fit(X_train, y_train, validation_data=(X_val, y_val), callbacks=[early_stop])

4. 未设置随机种子

问题: 结果在不同运行中不可复现,使调试和比较不可能。

解决方案: 设置所有随机种子:

import random
import numpy as np
import torch

random.seed(42)
np.random.seed(42)
torch.manual_seed(42)
if torch.cuda.is_available():
    torch.cuda.manual_seed_all(42)

5. 使用测试集进行超参数调优

问题: 在测试集上优化超参数导致对测试数据的过拟合。

解决方案: 使用验证集进行调优,测试集仅用于最终评估:

from sklearn.model_selection import GridSearchCV

# ✅ 正确:在训练+验证集上调优,在测试集上评估
param_grid = {'n_estimators': [50, 100, 200], 'max_depth': [5, 10, 15]}
grid_search = GridSearchCV(RandomForestClassifier(), param_grid, cv=5)
grid_search.fit(X_train, y_train)  # 在训练集上进行交叉验证
best_model = grid_search.best_estimator_

# 在保留的测试集上进行最终评估
final_score = best_model.score(X_test, y_test)

何时加载参考文件

在需要时加载参考文件:

  • PyTorch 实现细节: 加载 references/pytorch-training.md 以获取带有早停、学习率调度和检查点的完整训练循环
  • TensorFlow/Keras 模式: 加载 references/tensorflow-keras.md 以获取回调使用、自定义训练循环和TFLite移动部署