LoginSignup
1
2

【Python】線形回帰を使ったシンプルな需要予測

Last updated at Posted at 2023-08-31

線形回帰

$\ y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots + \beta_p x_p + \epsilon $

ここで:

  • $y$は目的変数
  • $x_1,x_2,...,x_p$は説明変数
  • $\beta_0はy軸の切片$
  • $\beta_1,\beta_2,...,\beta_p$は各説明変数の係数
  • $\epsilonは誤差項$

線形回帰の目的は、観測データに最も適合する線(または高次元の場合は超平面)を見つけることです。

実際のy値とモデルによって予測されるy値との差の二乗和を最小化することによって見つけられます。

$\ \text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2 $

ここで:

  • $MSE$は平均二乗誤差
  • $y_i$は$i$番目の実際の$y$値
  • $\hat{y}_i$は$i$番目の予測された$y$値
  • $n$はデータポイントの数

$MSE$を最小化することで、
$\beta$の値(係数)を最適化できます。

予測モデルを使用して未来の需要を予測する関数

Parameters:

  • data: 過去の需要データ。リストまたはNumPy配列を想定。
  • days_ahead: 何日後の需要を予測するか。

Returns:

  • forecasted_value: 予測された需要値
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

def demand_forecast(data, days_ahead):
    X = [data[i: i+5] for i in range(len(data)-5)]
    y = data[5:]

    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)
    
    predictions = model.predict(X_test)
    mse = mean_squared_error(y_test, predictions)
    print(f"Test MSE: {mse}")
    
    forecasted_input = data[-5:]
    for _ in range(days_ahead):
        next_day = model.predict([forecasted_input[-5:]])
        forecasted_input.append(next_day[0])

    forecasted_value = forecasted_input[-1]
    
    return forecasted_value

data = [100, 110, 105, 120, 130, 140, 135, 145, 160, 170, 175, 180]
forecast = demand_forecast(data, 1)
print(f"Forecasted demand for next day: {forecast}")

実行結果

Test MSE: 35.25317352782804
Forecasted demand for next day: 192.21572958313527

厳密な実装

・前処理
・モデル選択
・特徴量エンジニアリング

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2