Repository navigation
Expand file tree
/
Copy pathmodel.py
More file actions
128 lines (96 loc) · 2.99 KB
/
Copy pathmodel.py
File metadata and controls
128 lines (96 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import pickle
import numpy as np
import pandas as pd
import kagglehub
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error
# 1) Load dataset
path = kagglehub.dataset_download(
"anirudhchauhan/retail-store-inventory-forecasting-dataset"
)
dt = pd.read_csv(f"{path}/retail_store_inventory.csv")
# Save csv for Streamlit
dt.to_csv("retail_store_inventory.csv", index=False)
# 2) Data cleaning
dt = dt.drop_duplicates()
dt = dt.dropna()
dt = dt.drop(columns=[
"Store ID",
"Product ID",
"Inventory Level",
"Units Ordered",
"Demand Forecast",
"Date",
"Competitor Pricing",
"Weather Condition"
])
# 3) Split features and target
y = dt["Units Sold"]
X = dt.drop("Units Sold", axis=1)
# 4) Preprocessing
cat_cols = ["Category", "Region", "Seasonality"]
num_cols = ["Price", "Discount", "Holiday/Promotion"]
preprocess = ColumnTransformer(
[
("num", SimpleImputer(strategy="median"), num_cols),
("cat", Pipeline([
("imputer", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore"))
]), cat_cols)
]
)
# 5) Train-test split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 6) Train multiple regression models
models = {
"Linear Regression": LinearRegression(),
"Decision Tree": DecisionTreeRegressor(random_state=42),
"Random Forest": RandomForestRegressor(random_state=42, n_jobs=-1)
}
print("Model comparison:\n")
for name, model in models.items():
pipe = Pipeline([("prep", preprocess), ("model", model)])
pipe.fit(X_train, y_train)
pred = pipe.predict(X_test)
mae = mean_absolute_error(y_test, pred)
rmse = np.sqrt(mean_squared_error(y_test, pred))
print(name)
print("MAE:", round(mae, 2))
print("RMSE:", round(rmse, 2))
print()
# 7) Hyperparameter tuning (Random Forest)
rf_pipe = Pipeline([
("prep", preprocess),
("model", RandomForestRegressor(random_state=42, n_jobs=-1))
])
param_grid = {
"model__n_estimators": [100, 200],
"model__max_depth": [None, 15]
}
grid = GridSearchCV(
rf_pipe,
param_grid,
cv=3,
scoring="neg_root_mean_squared_error",
n_jobs=-1
)
grid.fit(X_train, y_train)
best_model = grid.best_estimator_
pred = best_model.predict(X_test)
print("Best Random Forest")
print("MAE:", round(mean_absolute_error(y_test, pred), 2))
print("RMSE:", round(np.sqrt(mean_squared_error(y_test, pred)), 2))
# 8) Save best model
with open("best_model.pkl", "wb") as f:
pickle.dump(best_model, f)
print("\nSaved best_model.pkl")
print("Saved retail_store_inventory.csv")