メインコンテンツへスキップ
見出し画像

【Python 100日チャレンジ】Day 94 - 線形回帰モデルを学ぼう

    「中学で習った y = ax + b が、ここで役に立つとは...!」

    ついに初めての予測モデル!
    線形回帰は機械学習の最も基本であり、
    すべてのデータサイエンティストが最初に学ぶアルゴリズムです。

    住宅価格、売上予測、年収予測...数値を
    予測したいすべての場面で活躍します。

    今日は「勉強時間から試験点数を予測する」という
    シンプルな例から始めて、
    線形回帰の魅力を体験してみたいと思います!!

    完読時間:15分 ⭐⭐⭐⭐⭐

    🎯 今日の学習目標

    1. 線形回帰の原理を理解する

    2. LinearRegressionでモデルを作る

    3. モデルの性能を評価する

    📚 事前知識

    この記事を読む前に以下の内容を理解しておくと良いでしょう。


    🎯 線形回帰とは?

    心配しないでください!複雑な数式はすべてスキップします。中学校で習った一次関数 y = ax + b だけ覚えていれば十分です。

    データを最もよく説明する直線を見つけること

    # 例:勉強時間 vs 試験点数
    勉強時間 = [1, 2, 3, 4, 5]
    点数 = [50, 55, 60, 65, 70]
    
    # 線形回帰が見つけるもの:y = 5x + 45
    # 「勉強1時間増えると点数5点上がる!」

    一次関数の復習

    y = ax + b
    y:予測する値(従属変数)
    x:入力値(独立変数)
    a:傾き(どれくらい急か?)
    b:切片(x=0の時のy値)

    視覚化で理解する

    import matplotlib.pyplot as plt
    import numpy as np
    
    # データ
    study_hours = np.array([1, 2, 3, 4, 5])
    scores = np.array([50, 55, 60, 65, 70])
    
    # グラフを描く
    plt.figure(figsize=(8, 6))
    plt.scatter(study_hours, scores, color='blue', s=100, label='実際のデータ')
    
    # 直線を描く(y = 5x + 45)
    x_line = np.linspace(0, 6, 100)
    y_line = 5 * x_line + 45
    plt.plot(x_line, y_line, color='red', linewidth=2, label='y = 5x + 45')
    
    plt.xlabel('勉強時間(時間)', fontsize=12)
    plt.ylabel('試験点数(点)', fontsize=12)
    plt.title('線形回帰:勉強時間 vs 試験点数', fontsize=14)
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.savefig('linear_regression.png', dpi=150, bbox_inches='tight')
    print("グラフ保存:linear_regression.png")

    線形回帰の目標

    誤差(Error)を最小化する直線を見つけること

    # 実際値 vs 予測値
    実際 = [50, 55, 60, 65, 70]
    予測 = [50, 55, 60, 65, 70]  # 完璧!
    誤差 = 実際 - 予測  # [0, 0, 0, 0, 0]
    
    # 機械学習がやること:誤差の二乗和を最小化
    # MSE (Mean Squared Error) = (誤差²の平均)

    💻 LinearRegressionでモデルを作ろう

    基本的な使い方

    from sklearn.linear_model import LinearRegression
    import numpy as np
    
    # 1. データ準備
    X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)  # 2次元に!
    y = np.array([50, 55, 60, 65, 70])
    
    # 2. モデル作成
    model = LinearRegression()
    
    # 3. モデル学習
    model.fit(X, y)
    
    # 4. 係数確認
    print(f"傾き (a):{model.coef_[0]:.2f}")
    print(f"切片 (b):{model.intercept_:.2f}")
    print(f"=> y = {model.coef_[0]:.2f}x + {model.intercept_:.2f}")

    出力:

    傾き (a):5.00
    切片 (b):45.00
    => y = 5.00x + 45.00

    予測してみる

    # 新しいデータを予測
    new_hours = np.array([[6], [7], [10]])
    predictions = model.predict(new_hours)
    
    for hours, score in zip(new_hours, predictions):
        print(f"{hours[0]}時間勉強 → 予想点数:{score:.1f}点")

    出力:

    6時間勉強 → 予想点数:75.0点
    7時間勉強 → 予想点数:80.0点
    10時間勉強 → 予想点数:95.0点

    実践例:住宅価格予測

    from sklearn.linear_model import LinearRegression
    from sklearn.model_selection import train_test_split
    import numpy as np
    
    # 住宅データ(平米数 vs 価格)
    house_size = np.array([20, 30, 40, 50, 60, 70, 80, 90, 100]).reshape(-1, 1)
    house_price = np.array([2000, 3500, 5000, 6000, 7500, 9000, 10000, 11500, 13000])  # 万円
    
    # 訓練/テスト分離
    X_train, X_test, y_train, y_test = train_test_split(
        house_size, house_price, test_size=0.2, random_state=42
    )
    
    # モデル学習
    model = LinearRegression()
    model.fit(X_train, y_train)
    
    # 予測
    y_pred = model.predict(X_test)
    
    # 結果出力
    print("テスト結果:")
    for size, actual, pred in zip(X_test, y_test, y_pred):
        print(f"平米数:{size[0]:3.0f}平米 | 実際:{actual:.0f}万円 | 予測:{pred:.0f}万円")
    
    # 新しい家を予測
    new_house = np.array([[75]])
    predicted_price = model.predict(new_house)
    print(f"\n75平米の家の予想価格:{predicted_price[0]:.0f}万円")

    🎯 モデル性能を評価しよう

    R² Score(決定係数)

    モデルがデータをどれだけよく説明するか?

    from sklearn.metrics import r2_score
    
    # R²を計算
    r2 = model.score(X_test, y_test)
    print(f"R² Score:{r2:.4f}")
    
    # 解釈:
    # 1.0 = 完璧な予測(100%)
    # 0.8 = 非常に良い(80%)
    # 0.5 = 普通(50%)
    # 0.0 = 予測できない

    MAE(Mean Absolute Error)

    平均絶対誤差

    from sklearn.metrics import mean_absolute_error
    
    mae = mean_absolute_error(y_test, y_pred)
    print(f"MAE:{mae:.0f}万円")
    print(f"平均的に{mae:.0f}万円程度の誤差")

    MSE(Mean Squared Error)

    平均二乗誤差(大きな誤差により大きなペナルティ)

    from sklearn.metrics import mean_squared_error
    import numpy as np
    
    mse = mean_squared_error(y_test, y_pred)
    print(f"MSE:{mse:.2f}")
    
    # RMSE(Root MSE)- 元の単位で
    rmse = np.sqrt(mse)
    print(f"RMSE:{rmse:.0f}万円")

    💻 実習例:年収予測

    from sklearn.linear_model import LinearRegression
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import r2_score, mean_absolute_error
    import numpy as np
    
    # データ:経験年数 vs 年収(万円)
    experience = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape(-1, 1)
    salary = np.array([280, 320, 360, 400, 450, 500, 550, 600, 650, 700])
    
    # データ分離
    X_train, X_test, y_train, y_test = train_test_split(
        experience, salary, test_size=0.2, random_state=42
    )
    
    # モデル学習
    model = LinearRegression()
    model.fit(X_train, y_train)
    
    # 予測
    y_pred = model.predict(X_test)
    
    # 評価
    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)
    
    print(f"傾き:{model.coef_[0]:.2f}(経験1年あたりの年収上昇)")
    print(f"切片:{model.intercept_:.2f}万円")
    print(f"\nR² Score:{r2:.4f}")
    print(f"MAE:{mae:.2f}万円")
    
    # 将来予測
    future_exp = np.array([[15], [20]])
    future_salary = model.predict(future_exp)
    
    print("\n将来の年収予測:")
    for exp, sal in zip(future_exp, future_salary):
        print(f"経験{exp[0]}年 → 予想年収:{sal:,.0f}万円")

    🎯 重回帰分析

    複数の特徴を使う

    from sklearn.linear_model import LinearRegression
    import numpy as np
    
    # データ:[平米数, 部屋数, 階数] vs 価格
    X = np.array([
        [30, 2, 5],   # 30平米、2部屋、5階
        [50, 3, 10],
        [70, 4, 15],
        [40, 2, 8],
        [60, 3, 12]
    ])
    y = np.array([3500, 6000, 9000, 5000, 7500])  # 万円
    
    # モデル学習
    model = LinearRegression()
    model.fit(X, y)
    
    # 係数確認
    print("係数:")
    print(f"平米数:{model.coef_[0]:.3f}")
    print(f"部屋数:{model.coef_[1]:.3f}")
    print(f"階数:{model.coef_[2]:.3f}")
    print(f"切片:{model.intercept_:.3f}")
    
    # 新しい家を予測
    new_house = np.array([[45, 3, 7]])  # 45平米、3部屋、7階
    predicted_price = model.predict(new_house)
    print(f"\n45平米、3部屋、7階 → {predicted_price[0]:.0f}万円")

    💡 線形回帰の限界

    1. 線形関係のみモデリング

    # 非線形データには不適切
    X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
    y = np.array([1, 4, 9, 16, 25])  # y = x²
    
    model = LinearRegression()
    model.fit(X, y)
    print(f"R² Score:{model.score(X, y):.4f}")  # 低い!

    2. 外れ値に敏感

    # 外れ値があると直線が大きく歪む
    X = np.array([1, 2, 3, 4, 100]).reshape(-1, 1)
    y = np.array([2, 4, 6, 8, 1000])  # 最後が外れ値

    3. 外挿(Extrapolation)に注意

    # 訓練範囲:1〜10
    # 予測範囲:100 → 不正確!

    💡 実践のコツと注意点

    Q1:いつ線形回帰を使うべきですか?

    数値を予測したくて、関係が直線に近い時!

    線形回帰が良い場合:

    • 住宅価格予測(平米数、部屋数 → 価格)

    • 売上予測(広告費 → 売上)

    • 試験点数予測(勉強時間 → 点数)

    • 年収予測(経験、学歴 → 年収)

    線形回帰が悪い場合:

    • 分類問題(合格/不合格、スパム/正常 → Day 95 ロジスティック回帰を使用)

    • 明確な非線形関係(人口増加、ウイルス拡散 → 多項式回帰)

    • 時系列データ(株価、天気 → ARIMA, LSTM)

    ヒント:まず線形回帰から始めてください!シンプルで解釈しやすいのでbaselineとして最適です。

    Q2:データが直線じゃない場合はどうすればいいですか?

    複数の方法があります!

    方法1:多項式回帰(Polynomial Regression)

    from sklearn.preprocessing import PolynomialFeatures
    from sklearn.linear_model import LinearRegression
    
    # 2次式に変換:x, x²
    poly = PolynomialFeatures(degree=2)
    X_poly = poly.fit_transform(X)
    
    # 線形回帰を適用
    model = LinearRegression()
    model.fit(X_poly, y)
    
    # これで曲線をモデリングできます!

    方法2:データ変換

    import numpy as np
    
    # 対数変換(指数関係の時)
    X_log = np.log(X + 1)
    
    # 平方根変換
    X_sqrt = np.sqrt(X)

    方法3:他のアルゴリズムを使用

    from sklearn.tree import DecisionTreeRegressor
    from sklearn.ensemble import RandomForestRegressor
    
    # 決定木は非線形関係もよく学習します
    model = DecisionTreeRegressor()
    model.fit(X, y)

    Q3:R² Scoreをどう解釈しますか?

    「モデルがデータをどれだけ説明するか?」です!

    R²値の意味:

    • R² = 1.0:100%完璧(すべての点が直線上に)

    • R² = 0.95:95%説明(非常に優秀)

    • R² = 0.80:80%説明(良い)

    • R² = 0.50:50%説明(普通)

    • R² = 0.0:0%説明(予測できない)

    • R² < 0:平均より悪い(何か間違っている!)

    分野別の基準:

    • 物理学:> 0.95(法則が明確)

    • 工学:> 0.80(制御された環境)

    • 経済学:> 0.50(変数が多い)

    • 社会科学:> 0.30(人間の行動は複雑)

    注意:R² 1.0は疑ってください!過学習かもしれません。

    Q4:MAE, MSE, RMSE...何が違うんですか?

    すべて「誤差」を測定しますが、方法が異なります!

    実生活の例:住宅価格予測(単位:万円)

    実際 = [5000, 10000, 15000, 20000]
    予測 = [6000, 9000, 16000, 18000]
    誤差 = [1000, 1000, 1000, 2000]

    MAE(Mean Absolute Error):

    MAE = (1000 + 1000 + 1000 + 2000) / 4 = 1250万円
    • 意味:「平均的に1250万円の差がある」

    • 長所:理解しやすい、単位そのまま

    • 使用:誤差が均等に重要な時

    MSE(Mean Squared Error):

    MSE = (1000² + 1000² + 1000² + 2000²) / 4 = 1,750,000
    • 意味:誤差を二乗して平均

    • 長所:大きな誤差により大きなペナルティ

    • 短所:単位が二乗(万円²)

    • 使用:大きな誤差を避けたい時

    RMSE(Root Mean Squared Error):

    RMSE = √1,750,000 = 1322万円
    • 意味:MSEの平方根(元の単位で)

    • 長所:MSEの長所 + 解釈しやすい

    • 使用:最もよく使われる!

    Q5:データはいくつ必要ですか?

    特徴数の10倍以上が良いです!

    経験則:

    • 特徴1個(単純線形回帰):最小30個、推奨100個以上

    • 特徴5個(重回帰分析):最小50個、推奨100-200個

    • 特徴10個:最小100個、推奨200-500個

    • 一般公式:データ数 > 10 × 特徴数

    データが少ない時の対処法:

    1. 特徴を減らす:重要な特徴のみ選択

    2. Cross-validation:データを複数回再利用

    3. 正則化(Regularization):過学習防止


    🧪 練習問題

    問題:広告費と売上予測

    広告費(万円)と売上(万円)データで回帰モデルを作ってみましょう。

    import numpy as np
    
    ad_cost = np.array([100, 200, 300, 400, 500]).reshape(-1, 1)
    sales = np.array([500, 900, 1300, 1700, 2100])
    
    # TODO:
    # 1. LinearRegressionモデルを学習
    # 2. R² Scoreを計算
    # 3. 広告費600万円の時の予想売上を予測

    答え:

    from sklearn.linear_model import LinearRegression
    import numpy as np
    
    ad_cost = np.array([100, 200, 300, 400, 500]).reshape(-1, 1)
    sales = np.array([500, 900, 1300, 1700, 2100])
    
    # 1. モデル学習
    model = LinearRegression()
    model.fit(ad_cost, sales)
    
    # 2. R² Score
    r2 = model.score(ad_cost, sales)
    print(f"R² Score:{r2:.4f}")
    
    # 3. 予測
    new_ad_cost = np.array([[600]])
    predicted_sales = model.predict(new_ad_cost)
    print(f"広告費600万円 → 予想売上:{predicted_sales[0]:.0f}万円")

    出力:

    R² Score:1.0000
    広告費600万円 → 予想売上:2500万円

    📝 今日学んだ内容のまとめ

    1. 線形回帰:データを最もよく説明する直線を見つける

    2. 公式:y = ax + b(a=傾き、b=切片)

    3. 使い方:LinearRegression().fit(X, y)

    4. 評価:R²(高いほど良い)、MAE/MSE(低いほど良い)

    5. 重回帰:複数の特徴を同時に使用可能

    🔗 関連資料


    📚 前回の学習

    Day 93:データ前処理の基礎を学ぼう ⭐⭐⭐⭐⭐

    前回は、欠損値処理、データスケーリング、カテゴリカルエンコーディングを学びました!

    📚 次回の学習

    Day 95:分類モデル(ロジスティック回帰)を学ぼう ⭐⭐⭐⭐⭐

    次回は、分類問題を解きます。合格/不合格、スパム/正常など!


    📚 シリーズをまとめて読む

    Python 100日チャレンジの全記事は、
    マガジン「Python 100日チャレンジ」 でまとめて読めます 😊
    よろしければ、フォローしていただけると嬉しい です!


    🚀 遅いと思った時が一番早い時期です! 🚀
    Day 94/100 | Phase 10:機械学習とAI入門 | #100DaysOfPython

    よんよんわれ
     
     
    ソフトウェアエンジニアです。 ものづくりが好きで、プライベートでも複数のサイドプロジェクトに取り組んでいます。 最近は、AIと自動化を活用したサービス開発に力を入れています。 Note、Xなどでお友達になっていただけたら嬉しいです☺️

    あなたへのおすすめ