Scikit-learn 線形回帰

scikit-learnBeginner
オンラインで実践に進む

はじめに

この実験では、最も人気のある Python ライブラリの一つである scikit-learn を使用して、機械学習モデルを構築する基本を学びます。ここでは、価格や温度のような連続値を予測するために使用される、基本的かつ強力なアルゴリズムである線形回帰に焦点を当てます。

私たちの目標は、カリフォルニアの地区における住宅価格の中央値を予測できるモデルを構築することです。私たちは、scikit-learn に含まれているカリフォルニア住宅データセットを使用します。

この実験を通して、以下のことを学びます。

  • scikit-learn からデータセットをロードする。
  • トレーニングとテストのためにデータを準備し、分割する。
  • 線形回帰モデルを作成し、トレーニングする。
  • トレーニング済みのモデルを使用して予測を行う。

すべてのタスクは WebIDE 内で実行します。さあ、始めましょう!

datasets.fetch_california_housing() でカリフォルニア住宅データセットをロードする

このステップでは、まずモデルのデータセットをロードすることから始めます。scikit-learn にはいくつかの組み込みデータセットが付属しており、学習や練習に最適です。ここではカリフォルニア住宅データセットを使用します。

まず、Python スクリプトを作成する必要があります。~/project ディレクトリに main.py という名前のファイルが既に作成されています。これは WebIDE の左側にあるファイルエクスプローラーで見つけることができます。

main.py を開き、以下のコードを追加してください。このコードは、必要なライブラリ(sklearn.datasets からの fetch_california_housingpandas)をインポートし、データセットをロードします。pandas を使用して、データを DataFrame に変換します。DataFrame は、表示や操作が容易な表形式のデータ構造です。

main.py に以下のコードを追加してください。

import pandas as pd
from sklearn.datasets import fetch_california_housing

## Load the California housing dataset
california = fetch_california_housing()

## Create a DataFrame
california_df = pd.DataFrame(california.data, columns=california.feature_names)
california_df['MedHouseVal'] = california.target

## Print the first 5 rows of the DataFrame
print("California Housing Dataset:")
print(california_df.head())

次に、スクリプトを実行して出力を確認しましょう。WebIDE でターミナルを開き(「Terminal」->「New Terminal」メニューを使用できます)、以下のコマンドを実行してください。

python3 main.py

コンソールにデータセットの最初の 5 行が表示されるはずです。MedHouseVal 列は私たちのターゲット変数であり、カリフォルニア地区の住宅価格の中央値を表しており、10 万ドル単位($100,000)で表現されています。

California Housing Dataset:
   MedInc  HouseAge  AveRooms  AveBedrms  Population  AveOccup  Latitude  Longitude  MedHouseVal
0  8.3252      41.0  6.984127   1.023810       322.0  2.555556     37.88    -122.23        4.526
1  8.3014      21.0  6.238137   0.971880      2401.0  2.109842     37.86    -122.22        3.585
2  7.2574      52.0  8.288136   1.073446       496.0  2.802260     37.85    -122.24        3.521
3  5.6431      52.0  5.817352   1.073059       558.0  2.547945     37.85    -122.25        3.413
4  3.8462      52.0  6.281853   1.081081       565.0  2.181467     37.85    -122.25        3.422

sklearn.model_selection の train_test_split を使用してデータを訓練用とテスト用に分割する

このステップでは、トレーニングプロセスに向けてデータを準備します。機械学習の重要な部分は、モデルが一度も見たことのないデータで評価することです。これを行うために、データセットを 2 つの部分に分割します。トレーニングセットとテストセットです。モデルはトレーニングセットから学習し、テストセットを使用してそのパフォーマンスを評価します。

まず、特徴量(入力変数、X)とターゲット(予測したい値、y)を分離する必要があります。この場合、XMedHouseVal 以外のすべての列になり、yMedHouseVal 列になります。

次に、sklearn.model_selectiontrain_test_split 関数を使用して分割を実行します。

以下のコードを main.py ファイルに追加してください。

from sklearn.model_selection import train_test_split

## Prepare the data
X = california_df.drop('MedHouseVal', axis=1)  ## Features (input variables)
y = california_df['MedHouseVal']  ## Target variable (what we want to predict)

## Split the data into training and testing sets
## test_size=0.2: テスト用に 20% のデータを確保し、トレーニング用に 80% を使用
## random_state=42: 分割を再現可能にする(実行ごとに同じ結果が得られる)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

## Print the shapes of the new datasets to confirm the split
print("\n--- Data Split ---")
print("X_train shape:", X_train.shape)  ## Training features
print("X_test shape:", X_test.shape)    ## Test features
print("y_train shape:", y_train.shape)  ## Training target values
print("y_test shape:", y_test.shape)    ## Test target values

ターミナルからスクリプトを再度実行してください。

python3 main.py

DataFrame の下に、新しく作成されたトレーニングセットとテストセットの形状が表示されます。これにより、データが正しく分割されたことが確認できます。

--- Data Split ---
X_train shape: (16512, 8)
X_test shape: (4128, 8)
y_train shape: (16512,)
y_test shape: (4128,)

sklearn.linear_model から LinearRegression モデルを初期化する

このステップでは、線形回帰モデルを作成します。scikit-learn を使用すると、これが非常に簡単になります。sklearn.linear_model モジュールから LinearRegression クラスをインポートし、そのインスタンスを作成するだけです。

このインスタンスは、線形回帰アルゴリズムを含むオブジェクトです。線形回帰は、y = mx + b という式を使用して、データポイントを通過する最適な直線を見つけます。ここで、m は各特徴量の係数(重み)、b は切片です。ここでは、ほとんどの基本的なケースでうまく機能するデフォルトのパラメータを使用します。

Linear Regression Formula
図 1: 線形回帰の式 y = mx + b。ここで m は傾き、b は切片です

以下のコードを main.py ファイルに追加してください。これにより、LinearRegression クラスがインポートされ、モデルオブジェクトが作成されます。

from sklearn.linear_model import LinearRegression

## 線形回帰モデルを初期化する
model = LinearRegression()

## モデルをプリントして作成を確認する
print("\n--- Model Initialized ---")
print(model)

ターミナルから main.py スクリプトを再度実行します。

python3 main.py

出力には、LinearRegression オブジェクトを示す行が含まれるようになります。これにより、モデルが正常に初期化されたことが確認できます。

--- Model Initialized ---
LinearRegression()

model.fit(X_train, y_train) でモデルをフィットさせる

このステップでは、モデルをトレーニングします。このプロセスは、データをモデルに「フィットさせる」と呼ばれることがよくあります。フィット中、モデルは特徴量(X_train)とターゲット変数(y_train)の関係を学習します。線形回帰の場合、これはターゲットを最もよく予測するために、各特徴量に対する最適な係数を見つけることを意味します。

モデルオブジェクトの fit() メソッドを使用し、トレーニングデータを引数として渡します。

以下のコードを main.py ファイルに追加してください。

## Fit (train) the model on the training data
## The fit() method learns the relationship between features (X_train) and target (y_train)
## It calculates optimal coefficients for each feature and the intercept using least squares optimization
model.fit(X_train, y_train)

## After fitting, the model has learned the coefficients and intercept.
## The intercept represents the predicted value when all features are zero
print("\n--- Model Trained ---")
print("Intercept:", model.intercept_)

ターミナルからスクリプトを実行してください。

python3 main.py

スクリプトが実行された後、出力に線形回帰モデルの切片を示す新しいセクションが表示されます。切片は、すべての特徴量の値がゼロの場合の予測値です。ここに数値が表示されることで、モデルがデータで正常にトレーニングされたことが確認できます。

--- Model Trained ---
Intercept: -37.023277706064185

model.predict(X_test) でテストデータに対して予測を行う

この最終ステップでは、トレーニング済みのモデルを使用して予測を行います。これが予測モデルを構築する最終的な目標です。トレーニング中にモデルが見ていないテストデータ(X_test)を使用して、そのパフォーマンスを評価します。

トレーニング済みのモデルオブジェクトの predict() メソッドを使用し、テスト特徴量(X_test)を引数として渡します。このメソッドは、ターゲット変数に対する予測値の配列を返します。

以下のコードを main.py ファイルに追加してください。

## Make predictions on the test data
## The predict() method uses the learned coefficients and intercept to calculate predictions
## Formula: prediction = intercept + (coeff1 * feature1) + (coeff2 * feature2) + ...
predictions = model.predict(X_test)

## Print the first 5 predictions (values are in $100,000 units)
print("\n--- Predictions ---")
print(predictions[:5])

これで、スクリプトを最後に一度ターミナルから実行してください。

python3 main.py

出力には、テストセットに対する最初の 5 つの予測された住宅価格が含まれるようになります。これらの値は、X_test の特徴量に基づいて、モデルが中央値の住宅価値がこうあるべきだと考えているものです。これらの予測値を y_test の実際の値と比較することで、モデルの精度を測ることができます。

--- Predictions ---
[0.71912284 1.76401657 2.70965883 2.83892593 2.60465725]

おめでとうございます!scikit-learn を使用して、線形回帰モデルを正常に構築、トレーニング、および使用することができました。

まとめ

この実験では、scikit-learn を使用して基本的な機械学習モデルを構築するワークフロー全体を完了しました。

まず、カリフォルニア住宅データセットをロードし、pandas を使用して準備しました。次に、データをトレーニングセットとテストセットに分割することの重要性を学び、train_test_split を使用して分割を実行しました。

その後、LinearRegression モデルを初期化し、fit() メソッドを使用してトレーニングデータでトレーニングし、最後にトレーニング済みモデルを使用して、未知のテストデータに対して predict() メソッドで予測を行いました。

この実験は、scikit-learn の強固な基礎を提供します。ここから、以下のようなより高度なトピックを探求できます。

  • モデル評価: 平均二乗誤差(MSE)や決定係数(R-squared)などの指標を計算してモデルの精度を測定する
  • 特徴量スケーリング: パフォーマンス向上のために特徴量を標準化または正規化する
  • 正則化: 過学習を防ぐために Ridge または Lasso 回帰を使用する
  • クロスバリデーション: k-fold クロスバリデーションを使用したより堅牢な評価
  • その他のアルゴリズム: Random Forest、Support Vector Machines、またはニューラルネットワークを試す

Summary

In this lab, you have completed the entire workflow for building a basic machine learning model using scikit-learn.

You started by loading the California housing dataset and preparing it using pandas. Then, you learned the importance of splitting your data into training and testing sets and performed the split using train_test_split.

Following that, you initialized a LinearRegression model, trained it on your training data using the fit() method, used the trained model to make predictions on unseen test data with the predict() method, and finally visualized the results to understand your model's performance.

This lab provides a solid foundation in scikit-learn. From here, you can explore more advanced topics such as:

  • Model evaluation: Calculate metrics like Mean Squared Error (MSE) or R-squared to measure model accuracy
  • Data visualization: Create more advanced plots like residual plots, feature importance charts, or correlation matrices
  • Feature scaling: Standardize or normalize features for better performance
  • Regularization: Use Ridge or Lasso regression to prevent overfitting
  • Cross-validation: More robust evaluation using k-fold cross-validation
  • Other algorithms: Try Random Forest, Support Vector Machines, or Neural Networks