📝
EC2 インスタンスで回帰分析してみた
チュートリアルレベルの内容です。
あえて SageMaker を使用せずに EC2 インスタンスで回帰分析をやってみました。
1. EC2 インスタンスの作成
以下の設定で作成しました。
- AMI: Amazon Linux 2023
- インスタンスタイプ: t3.medium
- キーペア: 不要
- セッションマネージャーでの接続です
- セキュリティグループ: インバウンド、アウトバウンド全開放
- IAM インスタンスプロファイル: AdministratorAccess を付与したプロファイル
2. ライブラリのインストール
機械学習に必要なライブラリをインストールします。
$ sudo yum update -y
$ sudo yum install -y python3 python3-pip
$ pip3 install numpy pandas scikit-learn matplotlib
最後のコマンドで以下のようなエラーが発生する場合もありますが、AWS CLI との互換性の問題なので無視します。
Requirement already satisfied: six>=1.5 in /usr/lib/python3.9/site-packages (from python-dateutil>=2.8.2->pandas) (1.15.0)
Installing collected packages: zipp, numpy, tzdata, threadpoolctl, scipy, python-dateutil, pyparsing, pillow, packaging, kiwisolver, joblib, importlib-resources, fonttools, cycler, contourpy, scikit-learn, pandas, matplotlib
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
awscli 2.30.4 requires python-dateutil<=2.9.0,>=2.1, but you have python-dateutil 2.9.0.post0 which is incompatible.
Successfully installed contourpy-1.3.0 cycler-0.12.1 fonttools-4.60.1 importlib-resources-6.5.2 joblib-1.5.2 kiwisolver-1.4.7 matplotlib-3.9.4 numpy-2.0.2 packaging-25.0 pandas-2.3.3 pillow-11.3.0 pyparsing-3.2.5 python-dateutil-2.9.0.post0 scikit-learn-1.6.1 scipy-1.13.1 threadpoolctl-3.6.0 tzdata-2025.2 zipp-3.23.0
3. 回帰分析スクリプトの作成
$ nano regression.py
# 以下のスクリプトを貼り付けて保存
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# サンプルデータの作成
np.random.seed(42)
X = np.random.rand(100, 1) * 10 # 0-10の範囲の100個のデータ
y = 2 * X + 3 + np.random.randn(100, 1) * 2 # y = 2x + 3 + ノイズ
# データの分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# モデルの作成と学習
model = LinearRegression()
model.fit(X_train, y_train)
# 予測
y_pred = model.predict(X_test)
# 結果の表示
print("=== 回帰分析の結果 ===")
print(f"係数: {model.coef_[0][0]:.4f}")
print(f"切片: {model.intercept_[0]:.4f}")
print(f"R2スコア: {r2_score(y_test, y_pred):.4f}")
print(f"平均二乗誤差: {mean_squared_error(y_test, y_pred):.4f}")
print("\nEC2での機械学習が成功しました!")
4. 回帰分析の実行
手順 3 で作成したスクリプトファイルを実行します。
$ python3 regression.py
=== 回帰分析の結果 ===
係数: 1.9197
切片: 3.2858
R2スコア: 0.9287
平均二乗誤差: 2.6148
EC2での機械学習が成功しました!
これだけでは結果がわかりづらいのでグラフ化します。
5. グラフ化
$ nano regression_graph.py
# 以下のスクリプトを貼り付けて保存
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# サンプルデータの作成
np.random.seed(42)
X = np.random.rand(100, 1) * 10
y = 2 * X + 3 + np.random.randn(100, 1) * 2
# データの分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# モデルの作成と学習
model = LinearRegression()
model.fit(X_train, y_train)
# 予測
y_pred = model.predict(X_test)
# グラフの作成
plt.figure(figsize=(12, 5))
# グラフ1: 学習データと回帰直線
plt.subplot(1, 2, 1)
plt.scatter(X_train, y_train, color='blue', alpha=0.5, label='Training Data')
plt.plot(X_train, model.predict(X_train), color='red', linewidth=2, label=f'y = {model.coef_[0][0]:.2f}x + {model.intercept_[0]:.2f}')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Training Data and Regression Line')
plt.legend()
plt.grid(True, alpha=0.3)
# グラフ2: テストデータでの予測精度
plt.subplot(1, 2, 2)
plt.scatter(y_test, y_pred, color='green', alpha=0.6)
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--', linewidth=2, label='Perfect Prediction')
plt.xlabel('Actual Values')
plt.ylabel('Predicted Values')
plt.title(f'Prediction Accuracy (R² = {r2_score(y_test, y_pred):.4f})')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('regression_result.png', dpi=150, bbox_inches='tight')
print("グラフを 'regression_result.png' として保存しました!")
# 結果の表示
print("\n=== 回帰分析の結果 ===")
print(f"係数: {model.coef_[0][0]:.4f}")
print(f"切片: {model.intercept_[0]:.4f}")
print(f"R2スコア: {r2_score(y_test, y_pred):.4f}")
print(f"平均二乗誤差: {mean_squared_error(y_test, y_pred):.4f}")
$ python3 regression_graph.py
グラフを 'regression_result.png' として保存しました!
=== 回帰分析の結果 ===
係数: 1.9197
切片: 3.2858
R2スコア: 0.9287
平均二乗誤差: 2.6148
# 保存された画像ファイルをダウンロードするため、Web サーバーを起動
$ python3 -m http.server 8000
この状態で以下の URL にアクセスします。
- http://<EC2 インスタンスのパブリック IPv4 アドレス>:8000
regression_result.png をクリックしてダウンロードします。


6. 結果の分析

左側のグラフはトレーニング結果です。
- X 軸: 説明変数 (入力)
- 気温など
- Y 軸: 目的変数 (出力)
- 売上など
- 青い点: 学習用データ
- 赤い線: 学習したモデル
例えば、このグラフからは「気温が上がると売上もあがる」などの傾向が読み取れます。
右側のグラフはモデルの予測結果です。
- X 軸: 正解データ
- 実際の売上など
- Y 軸: モデルの出力
- 予測した売上など
- 緑の点: テストデータのペア (実際の値、予測値の座標)
- 赤い線: 完璧な予測線(実際 = 予測)
緑の点が赤い線に近いかどうか (R2スコア: 0.9287) でモデルの信頼性を評価します。
メトリクスと検証 - Amazon SageMaker AI
R2 は、決定係数とも呼ばれ、モデルが従属変数の分散をどれだけ説明できるかを定量化するために回帰で使用します。値は 1 から -1 の範囲です。数値が大きいほど、変動性を説明した割合が高いことを示します。ゼロ (0) に近い R2 値は、従属変数のほとんどをモデルが説明できなかったことを示します。負の値は、適合度が悪く、モデルは定数関数と比べてパフォーマンスが下回ることを示します。線形回帰の場合、これは水平線です。
まとめ
今回は EC2 インスタンスで回帰分析してみました。
どなたかの参考になれば幸いです。
Discussion