半年分の商品ごとの需要予測を行うためのサンプルコード

2024年6月17日

以下は、Pythonのscikit-learnライブラリを使用して半年分の商品ごとの需要予測を行うためのサンプルコードです。この例では、線形回帰モデルを使用していますが、実際のデータに合わせて他の回帰アルゴリズムを選択することもできます。また、データの準備やモデルの評価などのステップも考慮する必要があります。

python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# ダミーデータの生成
np.random.seed(0)
n_samples = 1000
n_features = 5
n_months = 6  # 半年分のデータ

# 説明変数(特徴量)の生成
X = np.random.rand(n_samples, n_features)

# 目的変数(需要)の生成(仮定)
y = np.random.rand(n_samples, n_months)  # 商品ごとに半年分の需要データを仮定

# 商品IDを付与
product_ids = ['Product{}'.format(i) for i in range(n_samples)]
df = pd.DataFrame(X, columns=[f'Feature{i}' for i in range(1, n_features + 1)])
df['Product_ID'] = product_ids
for i in range(n_months):
    df[f'Month{i+1}_Demand'] = y[:, i]

# 商品ごとに半年分の需要予測モデルを構築
models = {}
for product_id, group in df.groupby('Product_ID'):
    X_product = group.drop(['Product_ID'] + [f'Month{i+1}_Demand' for i in range(n_months)], axis=1)
    y_product = group[[f'Month{i+1}_Demand' for i in range(n_months)]]
    
    X_train, X_test, y_train, y_test = train_test_split(X_product, y_product, test_size=0.2, random_state=42)
    
    model = LinearRegression()
    model.fit(X_train, y_train)
    models[product_id] = model

# 予測
product_id_to_predict = 'Product0'  # 予測対象の商品ID
X_to_predict = df[df['Product_ID'] == product_id_to_predict].drop(['Product_ID'] + [f'Month{i+1}_Demand' for i in range(n_months)], axis=1)
predicted_demand = models[product_id_to_predict].predict(X_to_predict)

# 予測結果の表示
print("Predicted Demand for Product {}: {}".format(product_id_to_predict, predicted_demand))

このコードでは、各商品ごとに半年分の需要データを持つ仮想のデータセットを生成し、線形回帰モデルを使用して商品ごとに回帰モデルをトレーニングしています。そして、予測対象の商品の特徴量を入力して、その商品の需要を予測しています。実際の需要予測では、より多くのデータの準備やモデルの評価、パフォーマンスの向上のためのチューニングなどが必要です。

未分類

Posted by ぼっち