機械学習プロジェクトのライフサイクル

機械学習プロジェクトは家を建てるようなもので、設計図から施工、検収までの完全なプロセスが必要であり、すべての段階が極めて重要で、どれ一つ欠けてもいけません。

機械学習プロセスの6つの中核段階:

  1. 問題定義:解決すべき問題を明確にする
  2. データ収集:関連データを取得する
  3. データ準備:データのクリーニングと前処理
  4. モデル訓練:アルゴリズムを選択しモデルを訓練する
  5. モデル評価:モデルの性能を評価する
  6. モデル展開:モデルを実運用に投入する


第1段階:問題定義

ビジネス問題を明確にする

問題定義は機械学習プロジェクトで最も重要な出発点です、ナビを使う前に目的地を明確にする必要があるのと同じです。

重要な質問

どのような問題を解決するのか?

  • 分類問題:メールがスパムかどうかを判定する
  • 回帰問題:住宅価格を予測する
  • クラスタリング問題:顧客をセグメント化する
  • 異常検知:クレジットカード不正を発見する

なぜこの問題が重要なのか?

  • ビジネス価値:効率向上、コスト削減、収益増加
  • ユーザー価値:体験の改善、パーソナライズされたサービスの提供

成功の基準は何か?

  • 定量的指標:精度が90%以上に達すること
  • ビジネス指標:コンバージョン率が20%向上

問題定義の例

実例

# 問題定義の例:ECレコメンドシステム
class ProblemDefinition:
    def __init__(self):
        # ビジネス問題
        self.business_problem = "ユーザーの購入コンバージョン率が低く、レコメンドの精度を高める必要がある"
       
        # 技術問題
        self.technical_problem = "ユーザーの行動に基づいて、ユーザーが購入する可能性のある商品を予測する"
       
        # 問題タイプ
        self.problem_type = "レコメンドシステム(分類+ランキング)"
       
        # 成功基準
        self.success_criteria = {
            "クリック率の向上": "15%",
            "コンバージョン率の向上": "10%",
            "レコメンド精度": "80%"
        }
       
        # 制約条件
        self.constraints = {
            "応答時間": "< 100ms",
            "データプライバシー": "GDPR要件への準拠",
            "計算リソース": "既存のサーバー構成"
        }
   
    def define_features_and_labels(self):
        """特徴とラベルを定義"""
        features = {
            "ユーザー特徴": ["年齢", "性別", "購入履歴", "閲覧行動"],
            "商品特徴": ["カテゴリ", "価格", "評価", に庫],
            "コンテキスト特徴": ["時間", "デバイス", "地理位置情報"]
        }
       
        labels = {
            "主要ラベル": "クリックしたかどうか",
            "副次ラベル": "購入したかどうか",
            "補助ラベル": "滞在時間"
        }
       
        return features, labels
   
    def print_definition(self):
        """問題定義を出力"""
        print("=" * 50)
        print("機械学習問題の定義")
        print("=" * 50)
        print(f"ビジネス問題:{self.business_problem}")
        print(f"技術問題:{self.technical_problem}")
        print(f"問題タイプ:{self.problem_type}")
        print("\n成功基準:")
        for metric, target in self.success_criteria.items():
            print(f"  {metric}:{target}")
        print("\n制約条件:")
        for constraint, limit in self.constraints.items():
            print(f"  {constraint}:{limit}")
       
        features, labels = self.define_features_and_labels()
        print("\n特徴定義:")
        for category, items in features.items():
            print(f"  {category}:{', '.join(items)}")
        print("\nラベル定義:")
        for label_type, label_name in labels.items():
            print(f"  {label_type}:{label_name}")

# 使用例
problem = ProblemDefinition()
problem.print_definition()

出力内容:

==================================================
机器学习问题定义
==================================================
业务问题:用户购买转化率低,需要提高推荐精准度
技术问题:基于用户行为预测用户可能购买的商品
问题类型:推荐系统(分类+排序)

成功标准:
  点击率提升:15%
  转化率提升:10%
  推荐准确率:80%

约束条件:
  响应时间:< 100ms
  数据隐私:符合 GDPR 要求
  计算资源:现有服务器配置

特征定义:
  用户特征:年龄, 性别, 购买历史, 浏览行为
  商品特征:类别, 价格, 评分, 库存
  上下文特征:时间, 设备, 地理位置

标签定义:
  主要标签:是否点击
  次要标签:是否购买
  辅助标签:停留时间

第2段階:データ収集

データソース

データは機械学習の燃料です、適切なデータがなければ、どんなに優れたアルゴリズムも機能しません。

一般的なデータソース

  1. 内部データ:会社の業務データ、ユーザー行動データ
  2. 外部データ:公開データセット、第三者データサービス
  3. Webクローラー:Webページデータ、ソーシャルメディアデータ
  4. センサーデータ:IoTデバイス、監視システム

データ収集の例

実例

# データ収集の例:複数のデータソースをシミュレーション
import pandas as pd
import numpy as np
from datetime import datetime, timedelta

class DataCollector:
    def __init__(self):
        self.collected_data = {}
   
    def collect_user_data(self, n_users=1000):
        """ユーザーデータを収集"""
        np.random.seed(42)
       
        user_data = {
            'user_id': range(1, n_users + 1),
            'age': np.random.randint(18, 65, n_users),
            'gender': np.random.choice(['男性', '女性'], n_users),
            'city': np.random.choice(['北京', '上海', '広州', '深セン'], n_users),
            'registration_date': [
                datetime.now() - timedelta(days=np.random.randint(1, 365))
                for _ in range(n_users)
            ]
        }
       
        self.collected_data['users'] = pd.DataFrame(user_data)
        print(f"{len(user_data['user_id'])} 件のユーザーデータを収集しました")
        return self.collected_data['users']
   
    def collect_behavior_data(self, n_behaviors=5000):
        """ユーザー行動データを収集"""
        np.random.seed(42)
       
        user_ids = np.random.choice(range(1, 1001), n_behaviors)
        product_ids = np.random.choice(range(1, 501), n_behaviors)
       
        behavior_data = {
            'behavior_id': range(1, n_behaviors + 1),
            'user_id': user_ids,
            'product_id': product_ids,
            'behavior_type': np.random.choice(
                ['閲覧', 'クリック', 'カートに追加', '購入'], n_behaviors,
                p=[0.4, 0.3, 0.2, 0.1]
            ),
            'timestamp': [
                datetime.now() - timedelta(minutes=np.random.randint(1, 10080))
                for _ in range(n_behaviors)
            ],
            'duration': np.random.exponential(30, n_behaviors)  # 滞在時間(秒)
        }
       
        self.collected_data['behaviors'] = pd.DataFrame(behavior_data)
        print(f"{len(behavior_data['behavior_id'])} 件の行動データを収集しました")
        return self.collected_data['behaviors']
   
    def collect_product_data(self, n_products=500):
        """商品データを収集"""
        np.random.seed(42)
       
        categories = ['電子製品', '衣類', '食品', '家庭用品', '書籍']
        product_data = {
            'product_id': range(1, n_products + 1),
            'category': np.random.choice(categories, n_products),
            'price': np.random.uniform(10, 1000, n_products),
            'rating': np.random.uniform(3.0, 5.0, n_products),
            'stock': np.random.randint(0, 1000, n_products)
        }
       
        self.collected_data['products'] = pd.DataFrame(product_data)
        print(f"{len(product_data['product_id'])} 件の商品データを収集しました")
        return self.collected_data['products']
   
    def get_data_summary(self):
        """データ概要を取得"""
        print("\nデータ収集概要:")
        for name, df in self.collected_data.items():
            print(f"\n{name} データセット:")
            print(f" 形状:{df.shape}")
            print(f" 列名:{list(df.columns)}")
            print(f" 欠損値:{df.isnull().sum().sum()}")
            print(f" サンプルデータ:")
            print(df.head(2))

# 使用例
collector = DataCollector()
collector.collect_user_data()
collector.collect_behavior_data()
collector.collect_product_data()
collector.get_data_summary()

第3段階:データ準備

データ準備の重要性

データ準備は機械学習プロジェクトの60〜80%の時間を占めます、料理前の下準備と同じくらい重要です。

データ準備の主なタスク

  1. データクリーニング:欠損値、異常値、重複値の処理
  2. 特徴エンジニアリング:新しい特徴の作成、重要な特徴の選択
  3. データ変換:標準化、正規化、エンコーディング
  4. データ分割:トレーニングセット、検証セット、テストセット

データ準備の例

実例

# データ準備の例
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.model_selection import train_test_split

class DataPreparer:
    def __init__(self, data):
        self.data = data.copy()
        self.processed_data = None
   
    def clean_data(self):
        """データクリーニング"""
        print("データクリーニングを開始...")
       
        # 1. 欠損値の処理
        print(f"処理前の欠損値の数:{self.data.isnull().sum().sum()}")
       
        # 数値列は平均値で補完
        numeric_columns = self.data.select_dtypes(include=[np.number]).columns
        for col in numeric_columns:
            if self.data[col].isnull().sum() > 0:
                self.data[col].fillna(self.data[col].mean(), inplace=True)
       
        # カテゴリ列は最頻値で補完
        categorical_columns = self.data.select_dtypes(include=['object']).columns
        for col in categorical_columns:
            if self.data[col].isnull().sum() > 0:
                mode_val = self.data[col].mode()[0]
                self.data[col].fillna(mode_val, inplace=True)
       
        print(f"処理後の欠損値の数:{self.data.isnull().sum().sum()}")
       
        # 2. 重複値の処理
        duplicates_before = self.data.duplicated().sum()
        self.data.drop_duplicates(inplace=True)
        duplicates_after = self.data.duplicated().sum()
        print(f"重複値の削除:{duplicates_before - duplicates_after} 件")
       
        # 3. 異常値の処理(簡単な方法:IQRを使用)
        for col in numeric_columns:
            Q1 = self.data[col].quantile(0.25)
            Q3 = self.data[col].quantile(0.75)
            IQR = Q3 - Q1
            lower_bound = Q1 - 1.5 * IQR
            upper_bound = Q3 + 1.5 * IQR
           
            outliers = ((self.data[col] < lower_bound) |
                       (self.data[col] > upper_bound)).sum()
            if outliers > 0:
                # 境界値で異常値を置換
                self.data[col] = self.data[col].clip(lower_bound, upper_bound)
                print(f"{col} 列の {outliers} 個の異常値を処理")
       
        return self.data
   
    def feature_engineering(self):
        """特徴エンジニアリング"""
        print("\n特徴エンジニアリングを開始...")
       
        # 1. 新しい特徴の作成(例)
        if 'price' in self.data.columns and 'rating' in self.data.columns:
            # コストパフォーマンス特徴を作成
            self.data['price_per_rating'] = self.data['price'] / self.data['rating']
            print("新しい特徴を作成:price_per_rating")
       
        # 2. 特徴選択(簡単な例:低分散特徴の削除)
        numeric_columns = self.data.select_dtypes(include=[np.number]).columns
        low_variance_features = []
       
        for col in numeric_columns:
            if self.data[col].var() < 0.01:  # 分散閾値
                low_variance_features.append(col)
       
        if low_variance_features:
            self.data.drop(columns=low_variance_features, inplace=True)
            print(f"低分散特徴の削除:{low_variance_features}")
       
        return self.data
   
    def transform_data(self):
        """データ変換"""
        print("\nデータ変換を開始...")
       
        # 1. カテゴリ変数のエンコード
        categorical_columns = self.data.select_dtypes(include=['object']).columns
        label_encoders = {}
       
        for col in categorical_columns:
            le = LabelEncoder()
            self.data[col] = le.fit_transform(self.data[col])
            label_encoders[col] = le
            print(f"カテゴリ変数のエンコード:{col}")
       
        # 2. 数値変数の標準化
        numeric_columns = self.data.select_dtypes(include=[np.number]).columns
        scaler = StandardScaler()
       
        if len(numeric_columns) > 0:
            self.data[numeric_columns] = scaler.fit_transform(self.data[numeric_columns])
            print(f"数値変数の標準化:{list(numeric_columns)}")
       
        return self.data, label_encoders, scaler
   
    def split_data(self, target_column, test_size=0.2, val_size=0.2):
        """データ分割"""
        print(f"\nデータ分割を開始(テストセット比率:{test_size}、検証セット比率:{val_size})...")
       
        X = self.data.drop(columns=[target_column])
        y = self.data[target_column]
       
        # まずテストセットを分離する
        X_temp, X_test, y_temp, y_test = train_test_split(
            X, y, test_size=test_size, random_state=42
        )
       
        # 次に残りのデータから検証セットを分離する
        val_size_adjusted = val_size / (1 - test_size)
        X_train, X_val, y_train, y_val = train_test_split(
            X_temp, y_temp, test_size=val_size_adjusted, random_state=42
        )
       
        print(f"トレーニングセットのサイズ:{X_train.shape)
        print(f"検証セットのサイズ:{X_val.shape)
        print(f"テストセットのサイズ:{X_test.shape)
       
        return {
            'X_train': X_train, 'y_train': y_train,
            'X_val': X_val, 'y_val': y_val,
            'X_test': X_test, 'y_test': y_test
        }
   
    def prepare_pipeline(self, target_column):
        """完全なデータ準備パイプライン"""
        print("=" * 50)
        print("データ準備パイプライン")
        print("=" * 50)
       
        # 1. データクリーニング
        self.clean_data()
       
        # 2. 特徴量エンジニアリング
        self.feature_engineering()
       
        # 3. データ変換
        processed_data, encoders, scaler = self.transform_data()
       
        # 4. データ分割
        splits = self.split_data(target_column)
       
        self.processed_data = processed_data
        return splits, encoders, scaler

# サンプルデータを作成してデータ準備をデモする
np.random.seed(42)
sample_data = pd.DataFrame({
    'age': np.random.randint(18, 65, 1000),
    'income': np.random.normal(50000, 15000, 1000),
    'gender': np.random.choice(['男', '女'], 1000),
    'city': np.random.choice(['北京', '上海', '広州'], 1000),
    'target': np.random.choice([0, 1], 1000)
})

# 欠損値と外れ値をいくつか追加
sample_data.loc[np.random.choice(1000, 50), 'income'] = np.nan
sample_data.loc[np.random.choice(1000, 20), 'age'] = np.random.randint(100, 150)

preparer = DataPreparer(sample_data)
splits, encoders, scaler = preparer.prepare_pipeline('target')
hr>

第4段階:モデル訓練

モデル選択戦略

適切なモデルを選択することは成功の鍵です、まるで仕事に適した道具を選ぶのと同じです。

モデル選択の考慮事項

  1. 問題タイプ:分類、回帰、クラスタリングなど
  2. データの特徴:データ量、特徴量の数、データタイプ
  3. パフォーマンス要件:精度、速度、解釈可能性
  4. リソース制約:計算リソース、時間制限

モデル訓練の例

実例

# モデルトレーニングの例
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.svm import SVC, SVR
from sklearn.metrics import accuracy_score, mean_squared_error, classification_report

class ModelTrainer:
    def __init__(self):
        self.models = {}
        self.trained_models = {}
   
    def register_model(self, name, model, problem_type):
        """モデルの登録"""
        self.models[name] = {
            'model': model,
            'problem_type': problem_type
        }
        print(f"モデルの登録:{name}({problem_type})")
   
    def train_single_model(self, name, X_train, y_train):
        """単一モデルのトレーニング"""
        if name not in self.models:
            raise ValueError(f"モデル {name} は未登録です")
       
        model_info = self.models[name]
        model = model_info['model']
       
        print(f"\nモデルのトレーニング:{name}")
        model.fit(X_train, y_train)
       
        self.trained_models[name] = model
        print(f"モデル {name} のトレーニングが完了しました")
       
        return model
   
    def train_all_models(self, X_train, y_train):
        """登録済みの全モデルをトレーニング"""
        print("\n全モデルのトレーニングを開始...")
       
        for name in self.models.keys():
            try:
                self.train_single_model(name, X_train, y_train)
            except Exception as e:
                print(f"モデル {name} のトレーニング中にエラーが発生しました:{e}")
       
        return self.trained_models
   
    def evaluate_models(self, X_test, y_test):
        """トレーニング済みの全モデルを評価"""
        print("\nモデル評価結果:")
        print("-" * 50)
       
        results = {}
       
        for name, model in self.trained_models.items():
            problem_type = self.models[name]['problem_type']
           
            # 予測
            y_pred = model.predict(X_test)
           
            # 問題タイプに応じて評価指標を選択
            if problem_type == 'classification':
                accuracy = accuracy_score(y_test, y_pred)
                results[name] = {'accuracy': accuracy}
                print(f"{name}: 正解率 = {accuracy:.4f}")
               
                # 詳細レポート
                print(classification_report(y_test, y_pred))
               
            elif problem_type == 'regression':
                mse = mean_squared_error(y_test, y_pred)
                rmse = np.sqrt(mse)
                results[name] = {'mse': mse, 'rmse': rmse}
                print(f"{name}: MSE = {mse:.4f}, RMSE = {rmse:.4f}")
           
            print("-" * 50)
       
        return results
   
    def get_best_model(self, results, metric='accuracy'):
        """最良モデルの取得"""
        if not results:
            return None
       
        best_model_name = max(results.keys(), key=lambda x: results[x].get(metric, 0))
        best_score = results[best_model_name][metric]
       
        print(f"\n最良モデル:{best_model_name}({metric} = {best_score:.4f})")
       
        return best_model_name, self.trained_models[best_model_name]

# 使用例
trainer = ModelTrainer()

# 異なるタイプのモデルを登録
trainer.register_model('ロジスティック回帰', LogisticRegression(random_state=42), 'classification')
trainer.register_model('ランダムフォレスト', RandomForestClassifier(n_estimators=100, random_state=42), 'classification')
trainer.register_model('サポートベクターマシン', SVC(random_state=42), 'classification')

# トレーニングデータを作成
X_train = splits['X_train']
y_train = splits['y_train']
X_test = splits['X_test']
y_test = splits['y_test']

# 全モデルをトレーニング
trained_models = trainer.train_all_models(X_train, y_train)

# モデルを評価
results = trainer.evaluate_models(X_test, y_test)

# 最良モデルを取得
best_name, best_model = trainer.get_best_model(results)

第5段階:モデル評価

評価指標の選択

適切な評価指標を選ぶことは、適切な物差しを選ぶようなものです、異なる指標は異なるシナリオに適しています。

一般的な評価指標

分類問題:

  • 正解率(Accuracy):正しく予測した割合
  • 適合率(Precision):陽性と予測されたサンプルのうち実際に陽性である割合
  • 再現率(Recall):実際に陽性のサンプルのうち正しく陽性と予測された割合
  • F1スコア:適合率と再現率の調和平均

回帰問題:

  • 平均二乗誤差(MSE):予測値と実際の値の差の二乗の平均
  • 平均二乗誤差の平方根(RMSE):MSE の平方根
  • 平均絶対誤差(MAE):予測値と実際の値の差の絶対値の平均
  • R²スコア:モデルが説明する分散の割合

モデル評価の例

実例

# モデル評価の例
import matplotlib.pyplot as plt
from sklearn.metrics import (
    accuracy_score, precision_score, recall_score, f1_score,
    confusion_matrix, roc_curve, auc
)

class ModelEvaluator:
    def __init__(self):
        self.evaluation_results = {}
   
    def evaluate_classification(self, y_true, y_pred, y_prob=None, model_name="Model"):
        """分類モデルの評価"""
        results = {}
       
        # 基本指標
        results['accuracy'] = accuracy_score(y_true, y_pred)
        results['precision'] = precision_score(y_true, y_pred, average='weighted')
        results['recall'] = recall_score(y_true, y_pred, average='weighted')
        results['f1'] = f1_score(y_true, y_pred, average='weighted')
       
        print(f"\n{model_name} 分類評価結果:")
        print(f"正解率:{results['accuracy']:.4f}")
        print(f"適合率:{results['precision']:.4f}")
        print(f"再現率:{results['recall']:.4f}")
        print(f"F1スコア:{results['f1']:.4f}")
       
        # 混同行列
        cm = confusion_matrix(y_true, y_pred)
        print(f"\n混同行列:")
        print(cm)
       
        # ROC曲線(確率予測がある場合)
        if y_prob is not None and len(np.unique(y_true)) == 2:
            fpr, tpr, thresholds = roc_curve(y_true, y_prob[:, 1])
            roc_auc = auc(fpr, tpr)
            results['roc_auc'] = roc_auc
           
            # ROC曲線をプロット
            plt.figure(figsize=(8, 6))
            plt.plot(fpr, tpr, color='darkorange', lw=2,
                    label=f'ROC曲線 (AUC = {roc_auc:.2f})')
            plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
            plt.xlim([0.0, 1.0])
            plt.ylim([0.0, 1.05])
            plt.xlabel('偽陽性率')
            plt.ylabel('真陽性率')
            plt.title(f'{model_name} ROC曲線')
            plt.legend(loc="lower right")
            plt.grid(True)
            plt.show()
       
        self.evaluation_results[model_name] = results
        return results
   
    def evaluate_regression(self, y_true, y_pred, model_name="Model"):
        """回帰モデルの評価"""
        results = {}
       
        # 基本指標
        mse = np.mean((y_true - y_pred) ** 2)
        rmse = np.sqrt(mse)
        mae = np.mean(np.abs(y_true - y_pred))
       
        # R²スコア
        ss_res = np.sum((y_true - y_pred) ** 2)
        ss_tot = np.sum((y_true - np.mean(y_true)) ** 2)
        r2 = 1 - (ss_res / ss_tot)
       
        results['mse'] = mse
        results['rmse'] = rmse
        results['mae'] = mae
        results['r2'] = r2
       
        print(f"\n{model_name} 回帰評価結果:")
        print(f"平均二乗誤差 (MSE):{mse:.4f}")
        print(f"平均二乗誤差の平方根 (RMSE):{rmse:.4f}")
        print(f"平均絶対誤差 (MAE):{mae:.4f}")
        print(f"R²スコア:{r2:.4f}")
       
        # 予測値と実際の値をプロット
        plt.figure(figsize=(8, 6))
        plt.scatter(y_true, y_pred, alpha=0.6)
        plt.plot([y_true.min(), y_true.max()], [y_true.min(), y_true.max()],
                'r--', lw=2)
        plt.xlabel('実際の値')
        plt.ylabel('予測値')
        plt.title(f'{model_name} 予測 vs 実際の値')
        plt.grid(True)
        plt.show()
       
        self.evaluation_results[model_name] = results
        return results
   
    def compare_models(self):
        """評価済みの全モデルを比較"""
        if not self.evaluation_results:
            print("比較できるモデル評価結果がありません")
            return
       
        print("\nモデル比較:")
        print("-" * 50)
       
        # 比較テーブルを作成
        comparison_data = []
        for model_name, results in self.evaluation_results.items():
            row = [model_name]
            for metric, value in results.items():
                row.append(f"{value:.4f}")
            comparison_data.append(row)
       
        # テーブルを表示
        headers = ["モデル名"] + list(self.evaluation_results.values())[0].keys()
        print("\t".join(headers))
        for row in comparison_data:
            print("\t".join(row))

# 使用例
evaluator = ModelEvaluator()

# 分類モデルを評価
y_pred_class = best_model.predict(X_test)
y_prob_class = best_model.predict_proba(X_test)
evaluator.evaluate_classification(y_test, y_pred_class, y_prob_class, "最良の分類モデル")

# 全モデルを比較
evaluator.compare_models()

第6段階:モデル展開

展開戦略

モデルデプロイは、モデルを実際の運用に投入するプロセスです、まるで開発した製品を市場に出すようなものです。

デプロイ方法

  1. バッチ予測:定期的に大量のデータを処理
  2. リアルタイム予測:オンラインサービス、即時応答
  3. 組み込みデプロイ:モデルを既存システムに統合
  4. エッジデプロイ:デバイス側でモデルを実行

モデル展開の例

実例

# モデルデプロイの例
import pickle
import json
from datetime import datetime

class ModelDeployer:
    def __init__(self):
        self.deployed_models = {}
        self.deployment_logs = []
   
    def save_model(self, model, model_name, filepath=None):
        """モデルの保存"""
        if filepath is None:
            filepath = f"{model_name}.pkl"
       
        with open(filepath, 'wb') as f:
            pickle.dump(model, f)
       
        print(f"モデル {model_name} は {filepath} に保存されました")
       
        # デプロイログを記録
        log_entry = {
            'timestamp': datetime.now().isoformat(),
            'action': 'save_model',
            'model_name': model_name,
            'filepath': filepath
        }
        self.deployment_logs.append(log_entry)
       
        return filepath
   
    def load_model(self, model_name, filepath):
        """モデルの読み込み"""
        with open(filepath, 'rb') as f:
            model = pickle.load(f)
       
        self.deployed_models[model_name] = model
        print(f"モデル {model_name} は {filepath} から読み込まれました")
       
        # デプロイログを記録
        log_entry = {
            'timestamp': datetime.now().isoformat(),
            'action': 'load_model',
            'model_name': model_name,
            'filepath': filepath
        }
        self.deployment_logs.append(log_entry)
       
        return model
   
    def create_prediction_service(self, model_name, encoders=None, scaler=None):
        """予測サービスの作成"""
        if model_name not in self.deployed_models:
            raise ValueError(f"モデル {model_name} はデプロイされていません")
       
        model = self.deployed_models[model_name]
       
        def predict_service(input_data):
            """予測サービス関数"""
            try:
                # データ前処理
                if encoders:
                    for col, encoder in encoders.items():
                        if col in input_data.columns:
                            input_data[col] = encoder.transform(input_data[col])
               
                if scaler:
                    numeric_cols = input_data.select_dtypes(include=['number']).columns
                    input_data[numeric_cols] = scaler.transform(input_data[numeric_cols])
               
                # 予測
                prediction = model.predict(input_data)
               
                # 分類モデルの場合は確率も返す
                if hasattr(model, 'predict_proba'):
                    probability = model.predict_proba(input_data)
                    return {
                        'prediction': prediction.tolist(),
                        'probability': probability.tolist(),
                        'status': 'success',
                        'timestamp': datetime.now().isoformat()
                    }
                else:
                    return {
                        'prediction': prediction.tolist(),
                        'status': 'success',
                        'timestamp': datetime.now().isoformat()
                    }
           
            except Exception as e:
                return {
                    'error': str(e),
                    'status': 'error',
                    'timestamp': datetime.now().isoformat()
                }
       
        # サービス作成ログを記録
        log_entry = {
            'timestamp': datetime.now().isoformat(),
            'action': 'create_service',
            'model_name': model_name
        }
        self.deployment_logs.append(log_entry)
       
        return predict_service
   
    def monitor_model(self, model_name, input_data, true_labels=None):
        """モデル性能の監視"""
        if model_name not in self.deployed_models:
            raise ValueError(f"モデル {model_name} はデプロイされていません")
       
        predict_service = self.create_prediction_service(model_name)
       
        # 予測結果を取得
        result = predict_service(input_data)
       
        # 監視情報
        monitoring_info = {
            'timestamp': datetime.now().isoformat(),
            'model_name': model_name,
            'input_shape': input_data.shape,
            'prediction_count': len(result.get('prediction', [])),
            'status': result.get('status', 'unknown')
        }
       
        # 実ラベルがある場合は性能指標を計算
        if true_labels is not None and 'prediction' in result:
            predictions = result['prediction']
            if len(predictions) == len(true_labels):
                accuracy = accuracy_score(true_labels, predictions)
                monitoring_info['accuracy'] = accuracy
       
        print("モデル監視情報:")
        for key, value in monitoring_info.items():
            print(f"  {key}: {value}")
       
        return monitoring_info
   
    def get_deployment_logs(self):
        """デプロイログの取得"""
        return self.deployment_logs

# 使用例
deployer = ModelDeployer()

# 最良モデルを保存
model_path = deployer.save_model(best_model, "best_classification_model")

# モデルを読み込み
deployer.load_model("best_classification_model", model_path)

# 予測サービスを作成
prediction_service = deployer.create_prediction_service(
    "best_classification_model", encoders, scaler
)

# 予測サービスを使用
test_input = X_test.head(5)
prediction_result = prediction_service(test_input)
print("\n予測結果:")
print(json.dumps(prediction_result, indent=2, ensure_ascii=False))

# モデルを監視
deployer.monitor_model("best_classification_model", test_input, y_test.head(5).values)

完全なフローの例

実例

# 完全な機械学習プロセスの例
class MLProjectPipeline:
    def __init__(self):
        self.data_collector = DataCollector()
        self.data_preparer = None
        self.model_trainer = ModelTrainer()
        self.model_evaluator = ModelEvaluator()
        self.model_deployer = ModelDeployer()
   
    def run_complete_pipeline(self, target_column):
        """完全な機械学習パイプラインを実行する"""
        print("=" * 60)
        print("機械学習プロジェクトの完全なフロー")
        print("=" * 60)
       
        # 1. データ収集
        print("\n"第1步:データ収集")
        print("-" * 30)
        user_data = self.data_collector.collect_user_data(1000)
        behavior_data = self.data_collector.collect_behavior_data(5000)
       
        # データを結合(簡略化した例)
        merged_data = pd.merge(user_data, behavior_data, on='user_id', how='inner')
       
        # 目的変数を作成(例: 購入するかどうか)
        merged_data['purchased'] = (merged_data['behavior_type'] == '購入').astype(int)
       
        # 2. データ準備
        print("\n"第2步:データ準備")
        print("-" * 30)
       
        # 特徴量の列を選択
        feature_columns = ['age', 'gender', 'city', 'duration']
        if all(col in merged_data.columns for col in feature_columns):
            data_for_ml = merged_data[feature_columns + ['purchased']].copy()
           
            # カテゴリ変数を処理
            data_for_ml['gender'] = data_for_ml['gender'].map({'男性': 0, '女性': 1})
            data_for_ml['city'] = data_for_ml['city'].map({'北京': 0, '上海': 1, '広州': 2})
           
            # データ準備
            self.data_preparer = DataPreparer(data_for_ml)
            splits, encoders, scaler = self.data_preparer.prepare_pipeline('purchased')
           
            # 3. モデル訓練
            print("\n"第3步:モデル訓練")
            print("-" * 30)
           
            # モデルを登録
            self.model_trainer.register_model(
                'ロジスティック回帰', LogisticRegression(random_state=42), 'classification'
            )
            self.model_trainer.register_model(
                'ランダムフォレスト', RandomForestClassifier(n_estimators=100, random_state=42), 'classification'
            )
           
            # モデルを訓練
            trained_models = self.model_trainer.train_all_models(
                splits['X_train'], splits['y_train']
            )
           
            # 4. モデル評価
            print("\n"第4步:モデル評価")
            print("-" * 30)
           
            results = self.model_trainer.evaluate_models(
                splits['X_test'], splits['y_test']
            )
           
            best_name, best_model = self.model_trainer.get_best_model(results)
           
            # 5. モデルデプロイ
            print("\n"第5步:モデルデプロイ")
            print("-" * 30)
           
            # モデルを保存
            model_path = self.model_deployer.save_model(best_model, "production_model")
           
            # 予測サービスの作成
            prediction_service = self.model_deployer.create_prediction_service(
                "production_model"
            )
           
            # 予測サービスのテスト
            test_input = splits['X_test'].head(3)
            prediction_result = prediction_service(test_input)
           
            print("\n"予測サービスのテスト結果:")
            print(json.dumps(prediction_result, indent=2, ensure_ascii=False))
           
            print("\n" + "=" * 60)
            print(機械学習プロジェクトのフローが完了しました!)
            print("=" * 60)
           
            return {
                'data': data_for_ml,
                'splits': splits,
                'best_model': best_model,
                'best_model_name': best_name,
                'evaluation_results': results,
                'prediction_service': prediction_service
            }
       
        else:
            print("データ列が不完全なため、プロセスを続行できません")
            return None

# 完全なフローを実行
pipeline = MLProjectPipeline()
project_results = pipeline.run_complete_pipeline('purchased')
その他の拡張