使用 GitHub Actions 进行模型训练

面向机器学习的 CI/CD

Ravi Bhadauria

Machine Learning Engineer

数据集:澳大利亚天气预测

  • 二分类
    • 预测明日是否降雨
  • 5 个分类特征
    • Location
    • WindGustDir
    • WindDir9am
    • WindDir3pm
    • RainToday
  • 17 个数值特征
    • MinTemp
    • MaxTemp
    • Rainfall
    • Evaporation
    • ...
    • WindGustSpeed
    • Cloud3pm
    • Temp9am
    • RISK_MM
1 https://www.kaggle.com/datasets/rever3nd/weather-data
面向机器学习的 CI/CD

建模流程

  • 数据预处理
    • 将分类特征转为数值
    • 填充特征缺失值
    • 特征缩放
  • 随机森林分类器
    • max_depth = 2, n_estimators = 50
  • 测试集上的标准指标
    • 性能图表
      • 混淆矩阵图
面向机器学习的 CI/CD

数据准备:目标编码

def target_encode_categorical_features(
    df: pd.DataFrame, categorical_columns: List[str], target_column: str
) -> pd.DataFrame:
    encoded_data = df.copy()

    # Iterate through categorical columns
    for col in categorical_columns:
        # Calculate mean target value for each category
        encoding_map = df.groupby(col)[target_column].mean().to_dict()

        # Apply target encoding
        encoded_data[col] = encoded_data[col].map(encoding_map)

    return encoded_data
1 https://maxhalford.github.io/blog/target-encoding/
面向机器学习的 CI/CD

缺失值填充与缩放

def impute_and_scale_data(df_features: pd.DataFrame) -> pd.DataFrame:
    # Impute data with mean strategy
    imputer = SimpleImputer(strategy="mean")
    X_preprocessed = imputer.fit_transform(df_features.values)

    # Scale and fit with zero mean and unit variance
    scaler = StandardScaler()
    X_preprocessed = scaler.fit_transform(X_preprocessed)

    return pd.DataFrame(X_preprocessed, columns=df_features.columns)
面向机器学习的 CI/CD

训练

  • 训练/测试拆分
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
  data.drop(TARGET_COLUMN), data[TARGET_COLUMN], random_state=1993)
  • 随机森林分类器
from sklearn.ensemble import RandomForestClassifier

clf = RandomForestClassifier(
  max_depth=2, n_estimators=50, random_state=1993)
clf.fit(X_train, y_train)
面向机器学习的 CI/CD

评估指标

from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score

# Calculate predictions
y_pred = model.predict(X_test)

# Calculate accuracy accuracy = accuracy_score(y_test, y_pred)
# Calculate precision precision = precision_score(y_test, y_pred)
# Calculate recall recall = recall_score(y_test, y_pred)
# Calculate f1 score f1 = f1_score(y_test, y_pred)
1 https://scikit-learn.org/stable/modules/model_evaluation.html#classification-metrics
面向机器学习的 CI/CD

可视化图表

from sklearn.metrics import ConfusionMatrixDisplay
ConfusionMatrixDisplay.from_estimator(model, X_test, y_test,cmap=plt.cm.Blues)

在测试集上计算的混淆矩阵图

面向机器学习的 CI/CD

GitHub Actions 工作流

模型训练持续集成工作流示意图

  • 持续机器学习(CML)
    • 面向机器学习的 CI/CD 工具
    • 集成 GitHub Actions
      • 供应训练机器
      • 执行训练与评估
      • 比较实验
      • 监控数据集
      • 可视化报告
1 https://cml.dev/ 2 https://martinfowler.com/bliki/FeatureBranch.html
面向机器学习的 CI/CD

CML 命令

# Enable setup-cml action to be used later
- uses: iterative/setup-cml@v1
- name: Train model
  run: |
    # Your ML workflow goes here
    pip install -r requirements.txt
    python3 train.py
1 https://www.markdownguide.org/basic-syntax/#images
面向机器学习的 CI/CD

CML 命令

- name: Write CML report
  run: |
    # Add results and plots to markdown
    cat results.txt >> report.md
    echo "![training graph](./graph.png)" >> report.md

# Create comment from markdown report cml comment create report.md
env: REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
面向机器学习的 CI/CD

输出

拉取请求页面的截图,展示由 CML 生成的评论

面向机器学习的 CI/CD

¡Vamos a practicar!

面向机器学习的 CI/CD

Preparing Video For Download...