Hikaru's notes

A collection of notes and resources

View the Project on GitHub HikaruMizoe/notes

2.2 モデルをトレーニングおよび改良する

タスクステートメント

モデルをトレーニングおよび改良する

対象知識

トレーニングプロセスの要素

エポック(Epoch)

ステップ(Step)/イテレーション

バッチサイズ(Batch Size)

モデルトレーニング時間を短縮する方法

早期停止(Early Stopping)

early_stopping = {
    "Type": "Auto",
    "MaxRuntimeInSeconds": 86400
}

分散トレーニング(Distributed Training)

モデルサイズに影響する要因

モデルのパフォーマンスを向上させる方法

正則化手法の利点

ドロップアウト(Dropout)

重み減衰(Weight Decay)

L1/L2 正則化

ハイパーパラメータのチューニング手法

ベイズ最適化(Bayesian Optimization)

モデルのハイパーパラメータとそれらがモデルパフォーマンスに及ぼす影響

ツリーベースのモデル

ニューラルネットワーク

SageMaker の外部で構築されたモデルを SageMaker に取り入れる方法

対象スキル

1. SageMaker の組み込みアルゴリズムと一般的な ML ライブラリを使用して ML モデルを開発する

XGBoost の例

import sagemaker
from sagemaker import image_uris

container = image_uris.retrieve('xgboost', region, '1.7-1')

xgb = sagemaker.estimator.Estimator(
    container,
    role=role,
    instance_count=1,
    instance_type='ml.m5.xlarge',
    output_path=output_path
)

2. SageMaker スクリプトモードを使用してモデルをトレーニングする

TensorFlow の例

from sagemaker.tensorflow import TensorFlow

tf_estimator = TensorFlow(
    entry_point='train.py',
    role=role,
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    framework_version='2.12',
    py_version='py310',
    hyperparameters={
        'epochs': 10,
        'batch_size': 32
    }
)

tf_estimator.fit({'training': s3_train_data})

PyTorch の例

from sagemaker.pytorch import PyTorch

pytorch_estimator = PyTorch(
    entry_point='train.py',
    role=role,
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    framework_version='2.0',
    py_version='py310'
)

3. カスタムデータセットを使用して事前トレーニングされたモデルをファインチューニングする

from sagemaker.jumpstart.estimator import JumpStartEstimator

# 事前トレーニング済みモデルでファインチューニング
model_id = 'huggingface-text-classification-bert-base-uncased'

estimator = JumpStartEstimator(
    model_id=model_id,
    environment={'accept_eula': 'true'}
)

# カスタムデータでファインチューニング
estimator.fit({'training': s3_train_data})

4. ハイパーパラメータチューニングを実行する(SageMaker AMT)

from sagemaker.tuner import HyperparameterTuner, IntegerParameter, ContinuousParameter

hyperparameter_ranges = {
    'max_depth': IntegerParameter(3, 10),
    'eta': ContinuousParameter(0.01, 0.5),
    'min_child_weight': IntegerParameter(1, 10),
    'subsample': ContinuousParameter(0.5, 1.0),
    'num_round': IntegerParameter(50, 200)
}

tuner = HyperparameterTuner(
    estimator=xgb_estimator,
    objective_metric_name='validation:auc',
    hyperparameter_ranges=hyperparameter_ranges,
    max_jobs=20,
    max_parallel_jobs=3,
    strategy='Bayesian'
)

tuner.fit({'train': s3_train_data, 'validation': s3_val_data})

5. 自動ハイパーパラメータ最適化機能を導入する

# SageMaker Autopilot を使用
from sagemaker.automl.automl import AutoML

automl = AutoML(
    role=role,
    target_attribute_name='target',
    max_candidates=100,
    mode='ENSEMBLING'
)

automl.fit(s3_input_data, job_name='automl-job')

6. モデルのオーバーフィット、アンダーフィット、壊滅的忘却を防止する

オーバーフィット対策

アンダーフィット対策

壊滅的忘却対策(継続学習)

7. 複数のトレーニングモデルを組み合わせてパフォーマンスを向上させる

アンサンブル手法

from sklearn.ensemble import VotingClassifier

# 複数モデルの投票
ensemble = VotingClassifier(
    estimators=[
        ('xgb', xgb_model),
        ('rf', rf_model),
        ('lr', lr_model)
    ],
    voting='soft'
)

スタッキング

from sklearn.ensemble import StackingClassifier

stacking = StackingClassifier(
    estimators=[
        ('xgb', xgb_model),
        ('rf', rf_model)
    ],
    final_estimator=LogisticRegression()
)

8. モデルサイズを縮小する

データ型の変更

# Float32 → Float16 (半精度)
model.half()

プルーニング(枝刈り)

import torch.nn.utils.prune as prune

# 重みの50%をプルーニング
prune.l1_unstructured(module, name='weight', amount=0.5)

圧縮

9. モデルバージョンを管理する(SageMaker Model Registry)

from sagemaker.model import Model
from sagemaker.model_metrics import ModelMetrics, MetricsSource

# モデルメトリクスの定義
model_metrics = ModelMetrics(
    model_statistics=MetricsSource(
        s3_uri=f's3://{bucket}/metrics.json',
        content_type='application/json'
    )
)

# モデルパッケージグループの作成
model_package_group_name = 'customer-churn-models'

# モデルの登録
model_package = model.register(
    content_types=['text/csv'],
    response_types=['text/csv'],
    inference_instances=['ml.m5.large'],
    transform_instances=['ml.m5.large'],
    model_package_group_name=model_package_group_name,
    approval_status='PendingManualApproval',
    model_metrics=model_metrics
)

分散トレーニングの種類

データ並列化

from sagemaker.tensorflow import TensorFlow

tf_estimator = TensorFlow(
    entry_point='train.py',
    role=role,
    instance_count=4,  # 複数インスタンス
    instance_type='ml.p3.8xlarge',
    framework_version='2.12',
    distribution={
        'smdistributed': {
            'dataparallel': {
                'enabled': True
            }
        }
    }
)

モデル並列化

distribution={
    'smdistributed': {
        'modelparallel': {
            'enabled': True,
            'parameters': {
                'partitions': 2,
                'microbatches': 4
            }
        }
    }
}

重要なポイント

ハイパーパラメータチューニングのベストプラクティス

  1. 最も影響力のあるパラメータを優先
  2. 適切な範囲を設定
  3. 並列ジョブ数を調整(予算とのバランス)
  4. ベイズ最適化を活用
  5. 早期停止を使用

正則化の選択

関連リンク