在庫の回帰をするサンプルコード頂戴

在庫を回帰する場合、在庫数を目的変数として、他の特徴量を説明変数として扱います。以下は、在庫回帰のサンプルコードです。

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 # 特徴量の生成 features = { 'sales': np.random.randint(0, 100, n_samples), # 仮想的な売上データ 'price': np.random.rand(n_samples) * 100, # 仮想的な価格データ 'advertising': np.random.randint(0, 10, n_samples), # 広告費データ 'competitor_price': np.random.rand(n_samples) * 100, # 競合他社の価格データ 'seasonality': np.random.rand(n_samples), # 季節性データ } # 在庫数の生成 coefficients = np.array([0.5, -2, 1, -0.5, 0.1]) # 特徴量ごとの係数 intercept = 50 # 切片 X = pd.DataFrame(features) y = np.dot(X.values, coefficients) + intercept + np.random.normal(0, 5, n_samples) # 在庫数 # データを訓練データとテストデータに分割 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) # モデルの評価 train_score = model.score(X_train, y_train) test_score = model.score(X_test, y_test) print(f"Train R^2 score: {train_score:.3f}") print(f"Test R^2 score: {test_score:.3f}") # テストデータを用いた予測 y_pred = model.predict(X_test) # 平均二乗誤差の計算 mse = mean_squared_error(y_test, y_pred) print(f"Mean Squared Error: {mse:.3f}")

このコードでは、在庫数を生成するための係数と切片を定義し、それらの係数を使って特徴量と乗算して目的変数を生成しています。その後、特徴量と目的変数を使って線形回帰モデルを訓練し、性能を評価しています。

未分類

Posted by ぼっち