Certainly! Below is a comprehensive Python-based framework that outlines the entire process of building "DemandPredict," a hybrid univariate-multivariate demand forecasting model for e-commerce inventory management:
Step 1: Import Libraries
import pandas as pd
import numpy as np
# For Univariate Models
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.holtwinters import ExponentialSmoothing
# For Multivariate Models
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
# For Hybrid & Ensemble Methods
from sklearn.ensemble import BaggingRegressor, AdaBoostRegressor
# For Performance Evaluation
from sklearn.metrics import mean_squared_error, mean_absolute_error
# For Data Preprocessing and Visualization
import matplotlib.pyplot as plt
import seaborn as sns
Step 2: Load Data
Assume historical sales data and external market trends are stored in CSV files.
historical_sales = pd.read_csv('historical_sales.csv') # Sales data for a product
market_trends = pd.read_csv('market_trends.csv') # Market trends like seasonality, holidays, etc.
Step 3: Data Preprocessing
# Handle missing values if any
historical_sales.fillna(method='ffill', inplace=True)
market_trends.fillna(method='ffill', inplace=True)
# Merge datasets on a common column, say 'date'
data = pd.merge(historical_sales, market_trends, on='date', how='inner')
# Convert 'date' to datetime
data['date'] = pd.to_datetime(data['date'])
# Set 'date' column as index
data.set_index('date', inplace=True)
Step 4: Univariate Models
ARIMA Model
# Create an ARIMA model
def arima_model(train):
model = ARIMA(train, order=(5,1,0)) # Example order
model_fit = model.fit()
return model_fit
# Fit and predict with ARIMA model
train_data = data['sales'] # Assuming column 'sales' contains sales data
arima_fit = arima_model(train_data)
arima_forecast = arima_fit.forecast(steps=30)
Exponential Smoothing
# Exponential Smoothing model
def exp_smoothing(train):
model = ExponentialSmoothing(train, seasonal='add', seasonal_periods=12).fit()
return model
exp_fit = exp_smoothing(train_data)
exp_forecast = exp_fit.forecast(30)
Step 5: Multivariate Models
Linear Regression
# Prepare features and target
X = data.drop(columns='sales')
y = data['sales']
# Train-test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Linear Regression model
linear_model = LinearRegression()
linear_model.fit(X_train, y_train)
# Forecast with Linear Regression
linear_forecast = linear_model.predict(X_test)
Decision Trees
# Decision Trees model
tree_model = DecisionTreeRegressor()
tree_model.fit(X_train, y_train)
# Forecast with Decision Trees
tree_forecast = tree_model.predict(X_test)
Step 6: Hybrid Approach
Weighted Averaging
# Combine univariate and multivariate forecasts using weighted averaging
hybrid_forecast = (0.25 * arima_forecast.values +
0.25 * exp_forecast.values +
0.25 * linear_forecast[:30] + # Assuming we're taking 30 steps forecast
0.25 * tree_forecast[:30])
Bagging and Boosting
# Bagging
bagging_model = BaggingRegressor(base_estimator=LinearRegression(), n_estimators=10, random_state=42)
bagging_model.fit(X_train, y_train)
bagging_forecast = bagging_model.predict(X_test)
# Boosting
boosting_model = AdaBoostRegressor(base_estimator=DecisionTreeRegressor(), n_estimators=50, random_state=42)
boosting_model.fit(X_train, y_train)
boosting_forecast = boosting_model.predict(X_test)
Step 7: Evaluate Models
# Evaluation Metrics
def evaluate(true, pred):
mse = mean_squared_error(true, pred)
mae = mean_absolute_error(true, pred)
return mse, mae
# Assuming test data is also split for 30 days for forecasting
true_values = y_test[:30]
metrics = {
'ARIMA': evaluate(true_values, arima_forecast),
'Exponential Smoothing': evaluate(true_values, exp_forecast),
'Linear Regression': evaluate(true_values, linear_forecast[:30]),
'Decision Tree': evaluate(true_values, tree_forecast[:30]),
'Hybrid': evaluate(true_values, hybrid_forecast),
'Bagging': evaluate(true_values, bagging_forecast[:30]),
'Boosting': evaluate(true_values, boosting_forecast[:30])
}
# Print evaluation metrics
for model, metric in metrics.items():
print(f"{model} - MSE: {metric[0]}, MAE: {metric[1]}")
Conclusion
# Plot Forecast vs True Values
plt.figure(figsize=(14, 7))
plt.plot(true_values.index, true_values, label='Actual Sales')
plt.plot(true_values.index, hybrid_forecast, label='Hybrid Forecast', linestyle='--')
plt.legend()
plt.show()
This code provides a robust framework for building, training, and evaluating a hybrid demand forecasting model by combining univariate and multivariate approaches. To further refine and make the project operational, consider adding hyperparameter tuning, cross-validation, and scalability using cloud services.
Deployment
For deployment on cloud platforms like AWS or Google Cloud, you can package the model using Docker and deploy it using services like AWS SageMaker or GCP AI Platform, ensuring that your model can scale and handle real-time data for continuous predictions.