Machine Learning
Description
机器学习全流程:问题定义、数据准备、特征工程、模型选择、训练调参、评估验证、模型部署。
Trigger
machine learning, ML, 机器学习, 模型训练, 深度学习, DL, 特征工程, model training, 调参
Content
ML 项目流程
[问题定义] → [数据收集] → [特征工程] → [模型选择] → [训练调参]
↓
[部署监控] ← [A/B 测试] ← [模型评估] ← [交叉验证] ←──────┘
问题类型与算法选择
| 问题 | 算法 | 库 | |------|------|-----| | 二分类 | LogisticRegression, XGBoost, LightGBM | sklearn, xgboost | | 多分类 | RandomForest, CatBoost, LightGBM | sklearn, catboost | | 回归 | LinearRegression, XGBoostRegressor, GradientBoosting | sklearn, xgboost | | 时间序列 | Prophet, ARIMA, LSTM | prophet, statsmodels | | 聚类 | KMeans, DBSCAN, HDBSCAN | sklearn | | 推荐 | Collaborative Filtering, Matrix Factorization | implicit, lightfm | | NLP | BERT, GPT fine-tuning | transformers | | 异常检测 | IsolationForest, Autoencoder | sklearn, pytorch |
数据准备
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
# Train/Val/Test Split
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)
# 特征缩放
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_val_scaled = scaler.transform(X_val)
X_test_scaled = scaler.transform(X_test)
# 处理不平衡数据
from imblearn.over_sampling import SMOTE
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X_train, y_train)
特征工程
# 数值特征
df["log_amount"] = np.log1p(df["amount"])
df["amount_per_day"] = df["amount"] / df["days_active"]
df["engagement_ratio"] = df["clicks"] / df["impressions"].clip(1)
# 分类特征编码
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
encoder = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
categorical_encoded = encoder.fit_transform(df[["country", "device"]])
# 时间特征
df["day_of_week"] = df["date"].dt.dayofweek
df["hour"] = df["timestamp"].dt.hour
df["is_weekend"] = df["day_of_week"].isin([5, 6]).astype(int)
# 特征选择
from sklearn.feature_selection import mutual_info_classif
mi_scores = mutual_info_classif(X_train, y_train)
important_features = X_train.columns[mi_scores > threshold]
模型训练与评估
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import classification_report, roc_auc_score, confusion_matrix
from sklearn.model_selection import cross_val_score, GridSearchCV
# 交叉验证
model = GradientBoostingClassifier(random_state=42)
scores = cross_val_score(model, X_train_scaled, y_train, cv=5, scoring="roc_auc")
print(f"CV AUC: {scores.mean():.4f} +- {scores.std():.4f}")
# 超参数调优
param_grid = {
"n_estimators": [100, 200],
"max_depth": [3, 5, 7],
"learning_rate": [0.01, 0.1, 0.2],
}
grid = GridSearchCV(
GradientBoostingClassifier(random_state=42),
param_grid, cv=5, scoring="roc_auc", n_jobs=-1
)
grid.fit(X_train_scaled, y_train)
print(f"Best params: {grid.best_params_}")
# 评估
y_pred = grid.predict(X_val_scaled)
y_proba = grid.predict_proba(X_val_scaled)[:, 1]
print(classification_report(y_val, y_pred))
print(f"ROC AUC: {roc_auc_score(y_val, y_proba):.4f}")
模型解释
# 特征重要性
importances = pd.DataFrame({
"feature": X_train.columns,
"importance": grid.best_estimator_.feature_importances_
}).sort_values("importance", ascending=False)
# SHAP 分析
import shap
explainer = shap.Explainer(grid.best_estimator_)
shap_values = explainer(X_val_scaled)
shap.summary_plot(shap_values, X_val_scaled)
检查清单
- [ ] 数据无泄漏 (train 和 test 的数据重叠)
- [ ] 特征缩放只 fit 在 train 上
- [ ] 交叉验证使用分层 (stratified) 拆分
- [ ] 分类问题检查类不平衡
- [ ] 过拟合检查 (train vs val 指标差距)
- [ ] 特征重要性已验证
- [ ] 模型可解释性符合业务需求
- [ ] 推理延迟满足生产要求
Version
1.0.0

Scan to join WeChat group