关于 ml-model-training
面向机器学习实践者的模型训练技能,涵盖 scikit-learn、PyTorch 和 TensorFlow/Keras。内容从数据准备延伸到模型评估,并说明如何避免常见训练错误。
主要功能
- 01数据准备与特征工程
- 02scikit-learn 和 PyTorch 示例
- 03TensorFlow/Keras 参考模式
- 04分类与回归指标
- 05防止数据泄漏和过拟合
适用场景
- 01规划模型训练流程
- 02评估分类或回归模型
- 03避免数据泄漏与过拟合
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill ml-model-training安装后在 Claude Code 中输入/ml-model-training确认已加载。
附带文件references/pytorch-training.mdreferences/tensorflow-keras.md
详细介绍
ML 模型训练
使用恰当的数据处理与评估方法训练机器学习模型。
训练工作流
- 数据准备 → 2. 特征工程 → 3. 模型选择 → 4. 训练 → 5. 评估
数据准备
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
# Load and clean data
df = pd.read_csv('data.csv')
df = df.dropna()
# Encode categorical variables
le = LabelEncoder()
df['category'] = le.fit_transform(df['category'])
# Split data (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)
# Scale features
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()
评估指标
| 任务 | 指标 |
|---|---|
| 分类 | Accuracy、Precision、Recall、F1、AUC-ROC |
| 回归 | MSE、RMSE、MAE、R² |
完整框架示例
-
PyTorch:请参阅 references/pytorch-training.md,了解完整训练流程,其中包括:
- 使用 BatchNorm 和 Dropout 的自定义模型类
- 带早停机制的训练/验证循环
- 学习率调度
- 模型检查点
- 包含分类报告的完整评估
-
TensorFlow/Keras:请参阅 references/tensorflow-keras.md,了解以下内容:
- Sequential 模型架构
- 回调(EarlyStopping、ReduceLROnPlateau、ModelCheckpoint、TensorBoard)
- 训练历史可视化
- 用于移动端部署的 TFLite 转换
- 自定义训练循环
最佳实践
建议:
- 使用交叉验证进行稳健评估
- 使用 MLflow 跟踪实验
- 定期保存模型检查点
- 监控过拟合
- 记录超参数
- 使用 70/15/15 的训练/验证/测试集划分
不建议:
- 在没有验证集的情况下训练
- 忽略类别不平衡
- 跳过特征缩放
- 使用测试集调整超参数
- 忘记设置随机种子
已知问题防范
1. 数据泄漏
问题:在划分数据前进行缩放或转换,会导致测试集信息泄漏到训练过程中。
解决方案:始终先划分数据,再仅使用训练数据拟合转换器:
# ✅ Correct: Fit on train, transform train/val/test
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val) # Only transform
X_test = scaler.transform(X_test) # Only transform
# ❌ Wrong: Fitting on all data
X_all = scaler.fit_transform(X) # Leaks test info!
2. 忽略类别不平衡
问题:在不平衡数据集(例如,95% 为 A 类、5% 为 B 类)上训练,会导致模型只预测多数类。
解决方案:使用类别权重或重采样:
from sklearn.utils.class_weight import compute_class_weight
# Compute class weights
class_weights = compute_class_weight('balanced', classes=np.unique(y_train), y=y_train)
model = RandomForestClassifier(class_weight='balanced')
# Or use SMOTE for oversampling minority class
from imblearn.over_sampling import SMOTE
smote = SMOTE()
X_resampled, y_resampled = smote.fit_resample(X_train, y_train)
3. 未使用正则化导致过拟合
问题:复杂模型会记住训练数据,在验证集/测试集上的表现较差。
解决方案:添加正则化技术:
# Dropout in PyTorch
nn.Dropout(0.3)
# L2 regularization in scikit-learn
RandomForestClassifier(max_depth=10, min_samples_split=20)
# Early stopping in 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
# ✅ Correct: Tune on train+val, evaluate on test
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) # Cross-validation on training set
best_model = grid_search.best_estimator_
# Final evaluation on held-out test set
final_score = best_model.score(X_test, y_test)
何时加载参考资料
在以下情况下加载参考文件:
- PyTorch 实现细节:加载
references/pytorch-training.md,查看包含早停机制、学习率调度和检查点的完整训练循环 - TensorFlow/Keras 模式:加载
references/tensorflow-keras.md,了解回调的用法、自定义训练循环,以及使用 TFLite 进行移动端部署
评论
支持 Markdown