Python機械学習ライブラリ

この章では、機械学習で最も中核となる4つのPythonライブラリ、NumPy、Pandas、Matplotlib、Scikit-learnについて詳しく説明します。

機械学習ライブラリは、専門的なツールボックスのようなものです、各ライブラリには特定の用途があり、組み合わせて使用することで複雑な機械学習タスクを完了できます。

四大中核ライブラリの役割

  • Numpy:数値計算の基礎であり、効率的な配列操作を提供します
  • Pandas:データ処理の利器であり、データ構造と分析ツールを提供します
  • Matplotlib:データ可視化のペンであり、さまざまなチャートを作成します
  • scikit-learn:機械学習のスイスアーミーナイフであり、完全なMLツールチェーンを提供します

NumPy:数値計算の基礎

NumPyとは?

NumPyは数学計算の電卓のようなものです、しかしその機能は何倍も強力です。NumPyはPythonの科学計算の基礎ライブラリであり、効率的な多次元配列オブジェクトを提供します。

NumPyの核心概念

1. 配列(Array)

例

# NumPy 配列の基本操作
import numpy as np

# 配列を作成するさまざまな方法
print("=== NumPy 配列の作成 ===")

# リストから作成
arr1 = np.array([1, 2, 3, 4, 5])
print(f"リストから作成:{arr1}")

# 等差数列を作成
arr2 = np.arange(0, 10, 2)  # 0から10まで、ステップ2
print(f"等差数列:{arr2}")

# 等間隔配列を作成
arr3 = np.linspace(0, 1, 5)  # 0から1まで、5点
print(f"等間隔配列:{arr3}")

# 特殊な配列を作成
zeros_arr = np.zeros((2, 3))  # 2行3列のゼロ配列
ones_arr = np.ones((2, 3))    # 2行3列の1配列
identity_arr = np.eye(3)      # 3x3の単位行列

print(f"ゼロ配列:\n{zeros_arr}")
print(f"1配列:\n{ones_arr}")
print(f"単位行列:\n{identity_arr}")
```

2. 配列操作

例

# 配列の基本操作
print("\n=== 配列の基本操作 ===)

# 配列の属性
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"配列:\n{arr}")
print(f"形状:{arr.shape}")
print(f"次元:{arr.ndim}")
print(f"要素数:{arr.size}")
print(f"データ型:{arr.dtype}")

# 配列のインデックスとスライス
print(f"最初の行:{arr)
print(f"最初の列:{arr[:, 0]}")
print(f"要素[1,2]:{arr[1, 2]}")

# 配列の演算
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

print(f"加算:{arr1 + arr2}")
print(f"乗算:{arr1 * arr2}")
print(f"ドット積:{np.dot(arr1, arr2)}")

# 統計関数
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(f"平均値:{np.mean(data)}")
print(f"標準偏差:{np.std(data)}")
print(f"最大値:{np.max(data)}")
print(f"最小値:{np.min(data)}")
print(f"中央値:{np.median(data)}")

NumPyの実用的な応用例

例

# NumPyの実用的な応用:単純線形回帰
def numpy_linear_regression():
    """NumPyを使用して単純線形回帰を実装"""
   
    # サンプルデータを生成
    np.random.seed(42)
    X = 2 * np.random.rand(100, 1)  # 特徴量
    y = 4 + 3 * X + np.random.randn(100, 1)  # ラベル + ノイズ
   
    # x0 = 1 を X に追加
    X_b = np.c_[np.ones((100, 1)), X]  # バイアス項を追加
   
    # 正規方程式を使用して解く:θ = (X^T * X)^(-1) * X^T * y
    theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
   
    print("=== NumPy 線形回帰の例 ===")
    print(f"学習されたパラメータ:切片={theta_best)
   
    # 予測
    X_new = np.array([[0], [2]])
    X_new_b = np.c_[np.ones((2, 1)), X_new]
    y_predict = X_new_b.dot(theta_best)
   
    print(f"予測結果:X=0 のとき y={y_predict)
   
    return theta_best, X, y

# サンプルを実行
theta, X, y = numpy_linear_regression()

Pandas:データ処理の利器

Pandasとは?

Pandasはデータ処理のスイスアーミーナイフのようなものです、強力なデータ構造とデータ分析ツールを提供し、表形式データの処理に特に適しています。

Pandasの核心データ構造

1. Series(一次元データ)

例

# Pandas Series の基本操作
import pandas as pd

print("=== Pandas Series ===")

# リストから Series を作成
s1 = pd.Series([1, 2, 3, 4, 5])
print(f"リストから作成:\n{s1}")

# インデックス付き Series
s2 = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(f"\nインデックス付き Series:\n{s2}")

# 辞書から Series を作成
s3 = pd.Series({'数学': 90, '英語': 85, '物理': 88})
print(f"\n辞書から作成:\n{s3}")

# Series 操作
print(f"\n要素へのアクセス:s2['b'] = {s2['b']}")
print(f"スライス:s2[0:2] =\n{s2[0:2]}")
print(f"統計情報:\n{s2.describe()}")

2. DataFrame(二次元データ)

例

# Pandas DataFrame の基本操作
print("\n=== Pandas DataFrame ===")

# DataFrame を作成
data = {
    '名前': ['張三', '李四', '王五', '趙六'],
    '年齢': [25, 30, 35, 28],
    '都市': ['北京', '上海', '広州', '深圳'],
    '給与': [15000, 20000, 18000, 22000]
}

df = pd.DataFrame(data)
print("元の DataFrame:")
print(df)

# DataFrame の基本操作
print(f"\nDataFrame の形状:{df.shape}")
print(f"\n列名:{list(df.columns)}")
print(f"\nデータ型:\n{df.dtypes}")

# データの選択
print(f"\n'名前'列を選択:\n{df['名前']}")
print(f"\n最初の2行を選択:\n{df.head(2)}")
print(f"\n年齢が28より大きい行を選択:\n{df[df['年齢'] > 28]}")

# 統計情報
print(f"\n数値列の統計情報:\n{df.describe()}")

# 新しい列を追加
df['年収'] = df['給与'] * 12
print(f"\n年収列を追加した後:\n{df}")

Pandas データ処理の例

例

# Pandas データ処理の完全な例
def pandas_data_processing():
    """Pandas データ処理の完全な流れを示す"""
   
    print("=== Pandas データ処理の例 ===")
   
    # 1. サンプルデータを作成
    np.random.seed(42)
    n_samples = 1000
   
    data = {
        '学生ID': range(1, n_samples + 1),
        '名前': [f'学生{i}' for i in range(1, n_samples + 1)],
        '年齢': np.random.randint(18, 25, n_samples),
        '性別': np.random.choice(['男', '女'], n_samples),
        '数学の成績': np.random.normal(75, 15, n_samples),
        '英語の成績': np.random.normal(80, 12, n_samples),
        '物理の成績': np.random.normal(72, 18, n_samples),
        'クラス': np.random.choice(['1組', '2組', '3組'], n_samples)
    }
   
    df = pd.DataFrame(data)
   
    # 2. データクリーニング
    print("元データの形状:", df.shape)
   
    # 異常値の処理(成績は0〜100の範囲内であるべき)
    score_columns = ['数学の成績', '英語の成績', '物理の成績']
    for col in score_columns:
        df[col] = df[col].clip(0, 100)
   
    # 3. 特徴量エンジニアリング
    # 合計点と平均点を計算する
    df['合計点'] = df[score_columns].sum(axis=1)
    df['平均点'] = df[score_columns].mean(axis=1)
   
    # ランクを追加
    def get_grade(score):
        if score >= 90:
            return 'A'
        elif score >= 80:
            return 'B'
        elif score >= 70:
            return 'C'
        elif score >= 60:
            return 'D'
        else:
            return 'F'
   
    df['ランク'] = df['平均点'].apply(get_grade)
   
    # 4. データ分析
    print("\n=== データ分析結果 ===")
   
    # 基本統計
    print("各科目の平均点:")
    print(df[score_columns].mean())
   
    # クラスごとの分析
    print("\n各クラスの平均点:")
    class_avg = df.groupby('クラス')['平均点'].mean()
    print(class_avg)
   
    # 性別ごとの分析
    print("\n性別分布:")
    gender_count = df['性別'].value_counts()
    print(gender_count)
   
    # ランク分布
    print("\nランク分布:")
    grade_dist = df['ランク'].value_counts().sort_index()
    print(grade_dist)
   
    # 5. データフィルタリング
    print("\n=== 特定データのフィルタリング ===")
   
    # 優秀な学生(平均点 > 85)
    excellent_students = df[df['平均点'] > 85].head(5)
    print("優秀な学生(上位5名):")
    print(excellent_students[['氏名', '平均点', 'ランク']])
   
    # 各クラスの最高得点の学生
    print("\n各クラスの最高得点の学生:")
    top_students = df.loc[df.groupby('クラス')['平均点'].idxmax()]
    print(top_students[['クラス', '氏名', '平均点']])
   
    return df

# 実行例
student_df = pandas_data_processing()

Matplotlib:データ可視化のペン

Matplotlibとは?

Matplotlib はデータアーティストの絵筆のようなものです、退屈なデータを直感的なグラフに変換し、データの中のパターンや関係を理解するのに役立ちます。

Matplotlibの基本チャート

例

# Matplotlib 基本グラフの例
import matplotlib.pyplot as plt
import numpy as np

# 中国語フォントを設定(中国語が豆腐表示になるのを防ぐ)
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False

def matplotlib_basic_charts():
    """Matplotlib の基本グラフをデモする"""
   
    print("=== Matplotlib 基本グラフの例 ===")
   
    # 1. 折れ線グラフ
    plt.figure(figsize=(12, 8))
   
    plt.subplot(2, 3, 1)
    x = np.linspace(0, 10, 100)
    y1 = np.sin(x)
    y2 = np.cos(x)
    plt.plot(x, y1, label='sin(x)')
    plt.plot(x, y2, label='cos(x)')
    plt.title('三角関数')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.grid(True)
   
    # 2. 散布図
    plt.subplot(2, 3, 2)
    np.random.seed(42)
    x = np.random.randn(100)
    y = 2 * x + np.random.randn(100) * 0.5
    plt.scatter(x, y, alpha=0.6, c='blue')
    plt.title('散布図')
    plt.xlabel('X')
    plt.ylabel('Y')
   
    # 3. 棒グラフ
    plt.subplot(2, 3, 3)
    categories = ['A', 'B', 'C', 'D', 'E']
    values = [23, 45, 56, 78, 32]
    plt.bar(categories, values, color=['red', 'green', 'blue', 'orange', 'purple'])
    plt.title('棒グラフ')
    plt.xlabel('カテゴリ')
    plt.ylabel('数値')
   
    # 4. ヒストグラム
    plt.subplot(2, 3, 4)
    data = np.random.normal(100, 15, 1000)
    plt.hist(data, bins=30, alpha=0.7, color='skyblue', edgecolor='black')
    plt.title('ヒストグラム')
    plt.xlabel('数値')
    plt.ylabel('頻度')
   
    # 5. 円グラフ
    plt.subplot(2, 3, 5)
    sizes = [30, 25, 20, 15, 10]
    labels = ['A', 'B', 'C', 'D', 'E']
    colors = ['gold', 'lightcoral', 'lightskyblue', 'lightgreen', 'plum']
    plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
    plt.title('円グラフ')
   
    # 6. 箱ひげ図
    plt.subplot(2, 3, 6)
    data1 = np.random.normal(0, 1, 100)
    data2 = np.random.normal(2, 1, 100)
    data3 = np.random.normal(-2, 1, 100)
    plt.boxplot([data1, data2, data3], labels=['グループ1', 'グループ2', 'グループ3'])
    plt.title('箱ひげ図')
    plt.ylabel('数値')
   
    plt.tight_layout()
    plt.show()
   
    print("グラフが表示されました!")

# 実行例
matplotlib_basic_charts()

高度な可視化の例

例

# 高度な可視化の例
def advanced_visualization():
    """高度な可視化テクニックをデモする"""
   
    print("=== 高度な可視化の例 ===")
   
    # より複雑なデータを作成
    np.random.seed(42)
    n_points = 200
   
    # 相関データを生成
    x = np.random.randn(n_points)
    y = 2 * x + np.random.randn(n_points) * 0.5
    colors = np.random.rand(n_points)
    sizes = 1000 * np.random.rand(n_points)
   
    # 1. バブルチャート
    plt.figure(figsize=(15, 5))
   
    plt.subplot(1, 3, 1)
    scatter = plt.scatter(x, y, c=colors, s=sizes, alpha=0.6, cmap='viridis')
    plt.colorbar(scatter, label='色の値')
    plt.title('バブルチャート')
    plt.xlabel('X')
    plt.ylabel('Y')
   
    # 2. ヒートマップ
    plt.subplot(1, 3, 2)
    data = np.random.randn(10, 10)
    im = plt.imshow(data, cmap='coolwarm', aspect='auto')
    plt.colorbar(im, label='数値')
    plt.title('ヒートマップ')
   
    # 3. サブプロットの組み合わせ
    plt.subplot(1, 3, 3)
   
    # サブプロットを作成
    gs = plt.GridSpec(2, 2, subplot_kw={'projection': 'polar'})
   
    ax1 = plt.subplot(gs[0, 0])
    theta = np.linspace(0, 2*np.pi, 100)
    r = np.sin(3*theta)
    ax1.plot(theta, r)
    ax1.set_title('極座標グラフ')
   
    ax2 = plt.subplot(gs[0, 1])
    categories = ['A', 'B', 'C', 'D']
    values = [15, 30, 45, 10]
    ax2.bar(categories, values)
    ax2.set_title('棒グラフ')
   
    ax3 = plt.subplot(gs[1, :])
    x_line = np.linspace(0, 10, 100)
    y_line1 = np.sin(x_line)
    y_line2 = np.cos(x_line)
    ax3.plot(x_line, y_line1, label='sin')
    ax3.plot(x_line, y_line2, label='cos')
    ax3.set_title('複合グラフ')
    ax3.legend()
   
    plt.tight_layout()
    plt.show()
   
    print("高度なグラフが表示されました!")

# 実行例
advanced_visualization()

Scikit-learn:機械学習のスイスアーミーナイフ

Scikit-learnとは?

Scikit-learn は機械学習の工具箱のようなものです、データ前処理からモデル訓練・評価までの完全なツールチェーンを提供し、Python 機械学習の事実上の標準です。

Scikit-learnの核心機能

例

# Scikit-learn のコア機能の例
from sklearn.datasets import make_classification, load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

def scikit_learn_basics():
    """Scikit-learn のコア機能をデモする"""
   
    print("=== Scikit-learn コア機能の例 ===")
   
    # 1. データ生成
    X, y = make_classification(
        n_samples=1000,
        n_features=20,
        n_classes=3,
        n_informative=15,
        random_state=42
    )
   
    print(f"データ形状:X={X.shape}, y={y.shape}")
    print(f"カテゴリ分布:{np.bincount(y)}")
   
    # 2. データ分割
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=42, stratify=y
    )
   
    print(f"トレーニングセットのサイズ:{X_train.shape)
    print(f"テストセットのサイズ:{X_test.shape)
   
    # 3. データ前処理
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
   
    print("データ標準化が完了しました")
   
    # 4. モデル学習と比較
    models = {
        'ロジスティック回帰': LogisticRegression(random_state=42),
        'ランダムフォレスト': RandomForestClassifier(n_estimators=100, random_state=42),
        'サポートベクターマシン': SVC(random_state=42)
    }
   
    results = {}
   
    for name, model in models.items():
        print(f"\n訓練 {name}...")
       
        # モデルを学習
        model.fit(X_train_scaled, y_train)
       
        # 予測
        y_pred = model.predict(X_test_scaled)
       
        # 評価
        accuracy = accuracy_score(y_test, y_pred)
        results[name] = accuracy
       
        print(f"{name} 精度:{accuracy:.4f}")
        print(f"分類レポート:\n{classification_report(y_test, y_pred)}")
   
    # 5. 結果比較
    print("\n=== モデル比較 ===")
    for name, accuracy in results.items():
        print(f"{name}: {accuracy:.4f}")
   
    best_model = max(results, key=results.get)
    print(f"\n最良モデル:{best_model}")
   
    return models[best_model]

# 実行例
best_model = scikit_learn_basics()

完全な機械学習フロー

例

# 機械学習の完全なフローの例
def complete_ml_pipeline():
    """機械学習の完全なフローをデモする"""
   
    print("=== 機械学習の完全なフロー ===")
   
    # 1. データの読み込み
    iris = load_iris()
    X = iris.data
    y = iris.target
    feature_names = iris.feature_names
    target_names = iris.target_names
   
    print(f"データセット:{iris.DESCR.split('\n')[0]}")
    print(f"特徴量の数:{len(feature_names)}")
    print(f"カテゴリ数:{len(target_names)}")
   
    # 2. データ探索
    df = pd.DataFrame(X, columns=feature_names)
    df['target'] = y
   
    print("\nデータプレビュー:")
    print(df.head())
   
    print("\nデータ統計:")
    print(df.describe())
   
    # 3. データ可視化
    plt.figure(figsize=(12, 4))
   
    plt.subplot(1, 2, 1)
    for i, target_name in enumerate(target_names):
        plt.scatter(
            df[df['target'] == i]['sepal length (cm)'],
            df[df['target'] == i]['sepal width (cm)'],
            label=target_name
        )
    plt.xlabel('がく片の長さ')
    plt.ylabel('がく片の幅')
    plt.title('がく片のサイズ分布')
    plt.legend()
   
    plt.subplot(1, 2, 2)
    for i, target_name in enumerate(target_names):
        plt.scatter(
            df[df['target'] == i]['petal length (cm)'],
            df[df['target'] == i]['petal width (cm)'],
            label=target_name
        )
    plt.xlabel('花弁の長さ')
    plt.ylabel('花弁の幅')
    plt.title('花弁のサイズ分布')
    plt.legend()
   
    plt.tight_layout()
    plt.show()
   
    # 4. データ準備
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.3, random_state=42, stratify=y
    )
   
    # 5. モデル学習
    from sklearn.ensemble import RandomForestClassifier
    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)
   
    # 6. モデル評価
    y_pred = model.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
   
    print(f"\nモデル精度:{accuracy:.4f}")
    print("\n混同行列:")
    print(confusion_matrix(y_test, y_pred))
    print("\n分類レポート:")
    print(classification_report(y_test, y_pred, target_names=target_names))
   
    # 7. 特徴量重要度
    feature_importance = model.feature_importances_
    feature_df = pd.DataFrame({
        '特徴量': feature_names,
        '重要度': feature_importance
    }).sort_values('重要度', ascending=False)
   
    print("\n特徴量重要度:")
    print(feature_df)
   
    # 8. 特徴量重要度の可視化
    plt.figure(figsize=(8, 4))
    plt.bar(feature_df['特徴量'], feature_df['重要度'])
    plt.title('特徴量重要度')
    plt.xlabel('特徴量')
    plt.ylabel('重要度')
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()
   
    return model, feature_df

# 実行例
trained_model, feature_importance = complete_ml_pipeline()

四ライブラリ連携の例

例

# 4つのライブラリ連携:完全な機械学習プロジェクト
def four_libraries_integration():
    """NumPy、Pandas、Matplotlib、Scikit-learn の連携をデモする"""
   
    print("=== 4つのライブラリ連携の例 ===")
   
    # 1. NumPy:シミュレーションデータの生成
    np.random.seed(42)
    n_samples = 500
   
    # 特徴量を生成
    study_hours = np.random.uniform(1, 10, n_samples)  # 学習時間
    sleep_hours = np.random.uniform(5, 9, n_samples)   # 睡眠時間
    practice_tests = np.random.randint(0, 20, n_samples) # 練習問題の数
   
    # ラベル(試験の成績)を生成、特徴量の線形結合にノイズを加える
    exam_scores = (
        5 * study_hours +
        3 * sleep_hours +
        2 * practice_tests +
        np.random.normal(0, 10, n_samples)
    )
   
    # スコアが0〜100の範囲になるようにする
    exam_scores = np.clip(exam_scores, 0, 100)
   
    # 2. Pandas:データフレームを作成しデータ処理を行う
    df = pd.DataFrame({
        '学習時間': study_hours,
        '睡眠時間': sleep_hours,
        '練習問題数': practice_tests,
        '試験の成績': exam_scores
    })
   
    # ランク列を追加
    df['ランク'] = pd.cut(df['試験の成績'],
                       bins=[0, 60, 70, 80, 90, 100],
                       labels=['F', 'D', 'C', 'B', 'A'])
   
    print("データプレビュー:)
    print(df.head())
    print(f"\nデータ形状:{df.shape}")
    print(f"\n等級分布:")
    print(df['等級'].value_counts().sort_index())
   
    # 3. Matplotlib:データ可視化
    plt.figure(figsize=(15, 10))
   
    # サブプロット1:特徴分布
    plt.subplot(2, 3, 1)
    df[['学習時間', '睡眠時間', '練習問題数']].hist(bins=20, ax=plt.gca())
    plt.title('特徴分布')
   
    # サブプロット2:成績分布
    plt.subplot(2, 3, 2)
    plt.hist(df['試験成績'], bins=20, alpha=0.7, color='skyblue')
    plt.title('試験成績分布')
    plt.xlabel('点数')
    plt.ylabel('頻度')
   
    # サブプロット3:学習時間 vs 成績
    plt.subplot(2, 3, 3)
    plt.scatter(df['学習時間'], df['試験成績'], alpha=0.6)
    plt.xlabel('学習時間')
    plt.ylabel('試験成績')
    plt.title('学習時間と成績の関係')
   
    # サブプロット4:睡眠時間 vs 成績
    plt.subplot(2, 3, 4)
    plt.scatter(df['睡眠時間'], df['試験成績'], alpha=0.6, color='orange')
    plt.xlabel('睡眠時間')
    plt.ylabel('試験成績')
    plt.title('睡眠時間と成績の関係')
   
    # サブプロット5:練習問題数 vs 成績
    plt.subplot(2, 3, 5)
    plt.scatter(df['練習問題数'], df['試験成績'], alpha=0.6, color='green')
    plt.xlabel('練習問題数')
    plt.ylabel('試験成績')
    plt.title('練習問題数と成績の関係')
   
    # サブプロット6:等級分布円グラフ
    plt.subplot(2, 3, 6)
    grade_counts = df['等級'].value_counts()
    plt.pie(grade_counts.values, labels=grade_counts.index, autopct='%1.1f%%')
    plt.title('等級分布')
   
    plt.tight_layout()
    plt.show()
   
    # 4. Scikit-learn:機械学習モデリング
    from sklearn.linear_model import LinearRegression
    from sklearn.ensemble import RandomForestRegressor
    from sklearn.metrics import mean_squared_error, r2_score
   
    # データの準備
    X = df[['学習時間', '睡眠時間', '練習問題数']]
    y = df['試験成績']
   
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=42
    )
   
    # 線形回帰モデルのトレーニング
    lr_model = LinearRegression()
    lr_model.fit(X_train, y_train)
    lr_pred = lr_model.predict(X_test)
    lr_mse = mean_squared_error(y_test, lr_pred)
    lr_r2 = r2_score(y_test, lr_pred)
   
    # ランダムフォレストモデルのトレーニング
    rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
    rf_model.fit(X_train, y_train)
    rf_pred = rf_model.predict(X_test)
    rf_mse = mean_squared_error(y_test, rf_pred)
    rf_r2 = r2_score(y_test, rf_pred)
   
    # モデル比較
    print("\n=== モデル比較 === ")
    print(f"線形回帰:MSE={lr_mse:.2f}, R²={lr_r2:.4f}")
    print(f"ランダムフォレスト:MSE={rf_mse:.2f}, R²={rf_r2:.4f}")
   
    # 線形回帰係数
    print(f"\n線形回帰係数:")
    for feature, coef in zip(X.columns, lr_model.coef_):
        print(f"{feature}: {coef:.2f}")
   
    # ランダムフォレストの特徴重要度
    print(f"\nランダムフォレストの特徴重要度:")
    for feature, importance in zip(X.columns, rf_model.feature_importances_):
        print(f"{feature}: {importance:.4f}")
   
    # 予測結果の可視化
    plt.figure(figsize=(12, 5))
   
    plt.subplot(1, 2, 1)
    plt.scatter(y_test, lr_pred, alpha=0.6)
    plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')
    plt.xlabel('実際の成績')
    plt.ylabel('予測成績')
    plt.title('線形回帰の予測結果')
   
    plt.subplot(1, 2, 2)
    plt.scatter(y_test, rf_pred, alpha=0.6)
    plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')
    plt.xlabel('実際の成績')
    plt.ylabel('予測成績')
    plt.title('ランダムフォレストの予測結果')
   
    plt.tight_layout()
    plt.show()
   
    return {
        'data': df,
        'linear_model': lr_model,
        'rf_model': rf_model,
        'linear_metrics': {'mse': lr_mse, 'r2': lr_r2},
        'rf_metrics': {'mse': rf_mse, 'r2': rf_r2}
    }

# 完全なサンプルを実行
results = four_libraries_integration()
その他の拡張