AI时间序列预测在商业中的应用:需求、收入与库存预测
面向精准商业预测的实用机器学习方法
AI时间序列预测在商业中的应用:需求、收入与库存预测
面向精准商业预测的实用机器学习方法
掌握基于AI的时间序列预测在商业中的应用——从需求预测、收入预测到库存优化和异常检测,使用现代深度学习与统计混合模型。
AI时间序列预测在商业中的应用:需求、收入与库存预测
为什么传统预测方法不够用
大多数企业仍依赖Excel趋势线、移动平均或简单指数平滑。这些方法在以下场景中表现不佳:
AI预测能够应对所有这些挑战,同时显著提升准确率。
现代预测方法
Neural Prophet(Facebook Prophet + 神经网络)
python
from neuralprophet import NeuralProphet
import pandas as pd加载业务数据
df = pd.read_csv('daily_sales.csv')
df.columns = ['ds', 'y'] # NeuralProphet格式配置模型
model = NeuralProphet(
# 季节性成分
yearly_seasonality=True,
weekly_seasonality=True,
daily_seasonality=False,
# 趋势建模
trend_reg=0.1, # 正则化
# 神经网络组件
n_lags=30, # 使用过去30天作为输入
n_forecasts=14, # 预测未来14天
# 训练
batch_size=64,
epochs=50
)添加节假日和事件
model.add_country_holidays(country_name='US')添加自定义事件(产品发布、促销)
events_df = pd.DataFrame({
'event': 'black_friday',
'ds': ['2023-11-24', '2024-11-29']
})
model.add_events(['black_friday'])训练
metrics = model.fit(df, freq='D', events_df=events_df)预测
future = model.make_future_dataframe(df, n_historic_predictions=True, periods=30)
forecast = model.predict(future)print(f"MAPE: {metrics['MAE'].mean():.2f}")
N-BEATS 和 N-HiTS(最先进的深度学习)
python
from neuralforecast import NeuralForecast
from neuralforecast.models import NHITS, NBEATS, PatchTST定义模型
models = [
NHITS(
h=14, # 预测范围
input_size=60, # 上下文窗口
max_steps=1000,
scaler_type='standard'
),
NBEATS(
h=14,
input_size=60,
max_steps=1000
),
PatchTST(
h=14,
input_size=512, # 长上下文窗口
patch_len=16,
max_steps=1000
)
]nf = NeuralForecast(models=models, freq='D')
nf.fit(df)
集成预测(优于任何单一模型)
predictions = nf.predict()
大规模需求预测
层次化预测
python
from hierarchicalforecast.core import HierarchicalReconciliation
from hierarchicalforecast.methods import MinTrace同时预测所有层级:
总计 → 区域 → 州 → 城市 → 门店 → 产品
def hierarchical_demand_forecast(df, hierarchy_spec, h=30):
"""
确保自上而下的一致性:门店预测之和 = 区域预测
"""
# 在每个层级生成基础预测
base_forecasts = {}
for level in hierarchy_spec:
level_data = df.groupby([level, 'ds'])['y'].sum().reset_index()
model = NeuralProphet(n_forecasts=h)
model.fit(level_data)
base_forecasts[level] = model.predict(...)
# 使用MinTrace进行协调(最优协调)
hrec = HierarchicalReconciliation(reconcilers=[MinTrace(method='mint_shrink')])
reconciled = hrec.reconcile(base_forecasts, hierarchy_spec)
return reconciled
结果:每个层级预测值正确求和
概率预测
python
from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA, AutoETS, AutoCESdef probabilistic_forecast(df, h=30, confidence_levels=[80, 95]):
"""
返回预测区间,而不仅仅是点预测
对库存规划至关重要(需要给定置信度下的安全库存)
"""
models = [
AutoARIMA(season_length=7),
AutoETS(season_length=7),
AutoCES(season_length=7)
]
sf = StatsForecast(models=models, freq='D', n_jobs=-1)
sf.fit(df)
forecast_df = sf.predict(h=h, level=confidence_levels)
# 输出包含:
# 'AutoARIMA', 'AutoARIMA-lo-80', 'AutoARIMA-hi-80'
# 'AutoARIMA-lo-95', 'AutoARIMA-hi-95'
return forecast_df
收入预测
多变量收入模型
python
import xgboost as xgb
from sklearn.preprocessing import LabelEncoderdef build_revenue_forecast_model(df: pd.DataFrame) -> dict:
"""
梯度提升模型,融合多种业务信号
"""
# 特征工程
df['month'] = df['date'].dt.month
df['quarter'] = df['date'].dt.quarter
df['day_of_week'] = df['date'].dt.dayofweek
df['is_weekend'] = df['day_of_week'].isin([5, 6]).astype(int)
# 滞后特征
for lag in [7, 14, 30, 90]:
df[f'revenue_lag_{lag}'] = df['revenue'].shift(lag)
# 滚动特征
for window in [7, 30, 90]:
df[f'revenue_rolling_mean_{window}'] = df['revenue'].rolling(window).mean()
df[f'revenue_rolling_std_{window}'] = df['revenue'].rolling(window).std()
# 外部变量
features = [
'month', 'quarter', 'day_of_week', 'is_weekend',
'marketing_spend', 'num_new_customers', 'avg_order_value',
'customer_churn_rate', 'nps_score',
*[f'revenue_lag_{l}' for l in [7, 14, 30, 90]],
*[f'revenue_rolling_mean_{w}' for w in [7, 30, 90]],
*[f'revenue_rolling_std_{w}' for w in [7, 30, 90]]
]
model = xgb.XGBRegressor(
n_estimators=500,
learning_rate=0.05,
max_depth=6,
subsample=0.8
)
model.fit(
df[features].dropna(),
df['revenue'].iloc[len(df) - len(df[features].dropna()):]
)
return {'model': model, 'features': features, 'importance': model.feature_importances_}
时间序列异常检测
python
from merlion.models.anomaly import IsolationForest
from merlion.post_process.threshold import AggregateAlertsdef detect_metric_anomalies(time_series: pd.DataFrame) -> list:
"""
检测业务指标中的异常
应用场景:收入下降、流量激增、库存短缺
"""
model = IsolationForest(IsolationForestConfig(
n_estimators=100,
n_past=100 # 上下文窗口
))
model.train(time_series)
anomaly_score = model.get_anomaly_score(time_series)
# 应用阈值获取二值异常标签
threshold = AggregateAlerts(AggregateAlertsConfig(count=3, lookback=5))
anomaly_labels = threshold(anomaly_score)
# 返回异常时间戳及严重程度
return [
{'timestamp': ts, 'severity': score}
for ts, score in zip(anomaly_labels.index, anomaly_labels.values)
if score > 0
]
工具与框架
关键要点
相关工具