2025-07-02 11:05:23 +08:00
|
|
|
|
"""
|
|
|
|
|
多店铺销售预测系统 - 数据处理工具函数
|
|
|
|
|
支持多店铺数据的加载、过滤和处理
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import pandas as pd
|
|
|
|
|
import numpy as np
|
|
|
|
|
import os
|
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
from typing import Optional, List, Tuple, Dict, Any
|
2025-07-15 10:37:25 +08:00
|
|
|
|
from core.config import DEFAULT_DATA_PATH
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
2025-07-15 10:37:25 +08:00
|
|
|
|
def load_multi_store_data(file_path: str = None,
|
2025-07-02 11:05:23 +08:00
|
|
|
|
store_id: Optional[str] = None,
|
|
|
|
|
product_id: Optional[str] = None,
|
|
|
|
|
start_date: Optional[str] = None,
|
|
|
|
|
end_date: Optional[str] = None) -> pd.DataFrame:
|
|
|
|
|
"""
|
|
|
|
|
加载多店铺销售数据,支持按店铺、产品、时间范围过滤
|
|
|
|
|
|
|
|
|
|
参数:
|
2025-07-15 10:37:25 +08:00
|
|
|
|
file_path: 数据文件路径 (支持 .csv, .xlsx, .parquet)。如果为None,则使用config中定义的默认路径。
|
2025-07-02 11:05:23 +08:00
|
|
|
|
store_id: 店铺ID,为None时返回所有店铺数据
|
|
|
|
|
product_id: 产品ID,为None时返回所有产品数据
|
|
|
|
|
start_date: 开始日期 (YYYY-MM-DD)
|
|
|
|
|
end_date: 结束日期 (YYYY-MM-DD)
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
DataFrame: 过滤后的销售数据
|
|
|
|
|
"""
|
|
|
|
|
|
2025-07-15 10:37:25 +08:00
|
|
|
|
# 如果未提供文件路径,则使用配置文件中的默认路径
|
|
|
|
|
if file_path is None:
|
|
|
|
|
file_path = DEFAULT_DATA_PATH
|
2025-07-14 19:26:57 +08:00
|
|
|
|
|
2025-07-15 10:37:25 +08:00
|
|
|
|
if not os.path.exists(file_path):
|
|
|
|
|
raise FileNotFoundError(f"数据文件不存在: {file_path}")
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
if file_path.endswith('.csv'):
|
|
|
|
|
df = pd.read_csv(file_path)
|
|
|
|
|
elif file_path.endswith('.xlsx'):
|
|
|
|
|
df = pd.read_excel(file_path)
|
|
|
|
|
elif file_path.endswith('.parquet'):
|
|
|
|
|
df = pd.read_parquet(file_path)
|
|
|
|
|
else:
|
|
|
|
|
raise ValueError(f"不支持的文件格式: {file_path}")
|
|
|
|
|
|
|
|
|
|
print(f"成功加载数据文件: {file_path}")
|
|
|
|
|
except Exception as e:
|
|
|
|
|
print(f"加载文件 {file_path} 失败: {e}")
|
|
|
|
|
raise
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
|
|
|
|
# 按店铺过滤
|
|
|
|
|
if store_id:
|
|
|
|
|
df = df[df['store_id'] == store_id].copy()
|
|
|
|
|
print(f"按店铺过滤: {store_id}, 剩余记录数: {len(df)}")
|
|
|
|
|
|
|
|
|
|
# 按产品过滤
|
|
|
|
|
if product_id:
|
|
|
|
|
df = df[df['product_id'] == product_id].copy()
|
|
|
|
|
print(f"按产品过滤: {product_id}, 剩余记录数: {len(df)}")
|
|
|
|
|
|
2025-07-14 19:26:57 +08:00
|
|
|
|
# 标准化列名和数据类型
|
|
|
|
|
df = standardize_column_names(df)
|
|
|
|
|
|
|
|
|
|
# 在标准化之后进行时间范围过滤
|
2025-07-02 11:05:23 +08:00
|
|
|
|
if start_date:
|
2025-07-14 19:26:57 +08:00
|
|
|
|
try:
|
|
|
|
|
start_date_dt = pd.to_datetime(start_date)
|
|
|
|
|
# 确保比较是在datetime对象之间
|
|
|
|
|
if 'date' in df.columns:
|
|
|
|
|
df = df[df['date'] >= start_date_dt].copy()
|
|
|
|
|
print(f"开始日期过滤: {start_date_dt}, 剩余记录数: {len(df)}")
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
print(f"警告: 无效的开始日期格式 '{start_date}',已忽略。")
|
|
|
|
|
|
2025-07-02 11:05:23 +08:00
|
|
|
|
if end_date:
|
2025-07-14 19:26:57 +08:00
|
|
|
|
try:
|
|
|
|
|
end_date_dt = pd.to_datetime(end_date)
|
|
|
|
|
# 确保比较是在datetime对象之间
|
|
|
|
|
if 'date' in df.columns:
|
|
|
|
|
df = df[df['date'] <= end_date_dt].copy()
|
|
|
|
|
print(f"结束日期过滤: {end_date_dt}, 剩余记录数: {len(df)}")
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
print(f"警告: 无效的结束日期格式 '{end_date}',已忽略。")
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
|
|
|
|
if len(df) == 0:
|
|
|
|
|
print("警告: 过滤后没有数据")
|
|
|
|
|
|
|
|
|
|
return df
|
|
|
|
|
|
|
|
|
|
def standardize_column_names(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
|
|
"""
|
2025-07-14 19:26:57 +08:00
|
|
|
|
标准化列名以匹配训练代码和API期望的格式
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
df: 原始DataFrame
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
DataFrame: 标准化列名后的DataFrame
|
|
|
|
|
"""
|
|
|
|
|
df = df.copy()
|
|
|
|
|
|
2025-07-14 19:26:57 +08:00
|
|
|
|
# 定义列名映射并强制重命名
|
|
|
|
|
rename_map = {
|
|
|
|
|
'sales_quantity': 'sales', # 修复:匹配原始列名
|
|
|
|
|
'temperature_2m_mean': 'temperature', # 新增:处理温度列
|
|
|
|
|
'dayofweek': 'weekday' # 修复:匹配原始列名
|
2025-07-02 11:05:23 +08:00
|
|
|
|
}
|
2025-07-14 19:26:57 +08:00
|
|
|
|
df.rename(columns={k: v for k, v in rename_map.items() if k in df.columns}, inplace=True)
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
2025-07-14 19:26:57 +08:00
|
|
|
|
# 确保date列是datetime类型
|
2025-07-02 11:05:23 +08:00
|
|
|
|
if 'date' in df.columns:
|
2025-07-14 19:26:57 +08:00
|
|
|
|
df['date'] = pd.to_datetime(df['date'], errors='coerce')
|
|
|
|
|
df.dropna(subset=['date'], inplace=True) # 移除无法解析的日期行
|
|
|
|
|
else:
|
|
|
|
|
# 如果没有date列,无法继续,返回空DataFrame
|
|
|
|
|
return pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
# 计算 sales_amount
|
|
|
|
|
# 由于没有price列,sales_amount的计算逻辑需要调整或移除
|
|
|
|
|
# 这里我们注释掉它,因为原始数据中已有sales_amount
|
|
|
|
|
# if 'sales_amount' not in df.columns and 'sales' in df.columns and 'price' in df.columns:
|
|
|
|
|
# # 先确保sales和price是数字
|
|
|
|
|
# df['sales'] = pd.to_numeric(df['sales'], errors='coerce')
|
|
|
|
|
# df['price'] = pd.to_numeric(df['price'], errors='coerce')
|
|
|
|
|
# df['sales_amount'] = df['sales'] * df['price']
|
|
|
|
|
|
|
|
|
|
# 创建缺失的特征列
|
|
|
|
|
if 'weekday' not in df.columns:
|
|
|
|
|
df['weekday'] = df['date'].dt.dayofweek
|
|
|
|
|
|
|
|
|
|
if 'month' not in df.columns:
|
|
|
|
|
df['month'] = df['date'].dt.month
|
|
|
|
|
|
|
|
|
|
# 添加缺失的元数据列
|
|
|
|
|
meta_columns = {
|
|
|
|
|
'store_name': 'Unknown Store',
|
|
|
|
|
'store_location': 'Unknown Location',
|
|
|
|
|
'store_type': 'Unknown',
|
|
|
|
|
'product_name': 'Unknown Product',
|
|
|
|
|
'product_category': 'Unknown Category'
|
|
|
|
|
}
|
|
|
|
|
for col, default in meta_columns.items():
|
|
|
|
|
if col not in df.columns:
|
|
|
|
|
df[col] = default
|
|
|
|
|
|
|
|
|
|
# 添加缺失的布尔特征列
|
2025-07-02 11:05:23 +08:00
|
|
|
|
default_features = {
|
2025-07-14 19:26:57 +08:00
|
|
|
|
'is_holiday': False,
|
|
|
|
|
'is_weekend': None,
|
|
|
|
|
'is_promotion': False,
|
|
|
|
|
'temperature': 20.0
|
2025-07-02 11:05:23 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for feature, default_value in default_features.items():
|
|
|
|
|
if feature not in df.columns:
|
2025-07-14 19:26:57 +08:00
|
|
|
|
if feature == 'is_weekend':
|
2025-07-02 11:05:23 +08:00
|
|
|
|
df['is_weekend'] = df['weekday'].isin([5, 6])
|
|
|
|
|
else:
|
|
|
|
|
df[feature] = default_value
|
|
|
|
|
|
|
|
|
|
# 确保数值类型正确
|
2025-07-14 19:26:57 +08:00
|
|
|
|
numeric_columns = ['sales', 'sales_amount', 'weekday', 'month', 'temperature']
|
2025-07-02 11:05:23 +08:00
|
|
|
|
for col in numeric_columns:
|
|
|
|
|
if col in df.columns:
|
|
|
|
|
df[col] = pd.to_numeric(df[col], errors='coerce')
|
|
|
|
|
|
|
|
|
|
# 确保布尔类型正确
|
|
|
|
|
boolean_columns = ['is_holiday', 'is_weekend', 'is_promotion']
|
|
|
|
|
for col in boolean_columns:
|
|
|
|
|
if col in df.columns:
|
|
|
|
|
df[col] = df[col].astype(bool)
|
|
|
|
|
|
2025-07-14 19:26:57 +08:00
|
|
|
|
print(f"数据标准化完成,可用特征列: {[col for col in ['sales', 'weekday', 'month', 'is_holiday', 'is_weekend', 'is_promotion', 'temperature'] if col in df.columns]}")
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
|
|
|
|
return df
|
|
|
|
|
|
2025-07-15 10:37:25 +08:00
|
|
|
|
def get_available_stores(file_path: str = None) -> List[Dict[str, Any]]:
|
2025-07-02 11:05:23 +08:00
|
|
|
|
"""
|
|
|
|
|
获取可用的店铺列表
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
file_path: 数据文件路径
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
List[Dict]: 店铺信息列表
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
df = load_multi_store_data(file_path)
|
|
|
|
|
|
2025-07-14 19:26:57 +08:00
|
|
|
|
if 'store_id' not in df.columns:
|
|
|
|
|
print("数据文件中缺少 'store_id' 列")
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
# 智能地获取店铺信息,即使某些列缺失
|
|
|
|
|
store_info = []
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
2025-07-14 19:26:57 +08:00
|
|
|
|
# 使用drop_duplicates获取唯一的店铺组合
|
|
|
|
|
stores_df = df.drop_duplicates(subset=['store_id'])
|
|
|
|
|
|
|
|
|
|
for _, row in stores_df.iterrows():
|
|
|
|
|
store_info.append({
|
|
|
|
|
'store_id': row['store_id'],
|
|
|
|
|
'store_name': row.get('store_name', f"店铺 {row['store_id']}"),
|
|
|
|
|
'location': row.get('store_location', '未知位置'),
|
|
|
|
|
'type': row.get('store_type', '标准'),
|
|
|
|
|
'opening_date': row.get('opening_date', '未知'),
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return store_info
|
2025-07-02 11:05:23 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
print(f"获取店铺列表失败: {e}")
|
|
|
|
|
return []
|
|
|
|
|
|
2025-07-15 10:37:25 +08:00
|
|
|
|
def get_available_products(file_path: str = None,
|
2025-07-02 11:05:23 +08:00
|
|
|
|
store_id: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
|
|
|
"""
|
|
|
|
|
获取可用的产品列表
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
file_path: 数据文件路径
|
|
|
|
|
store_id: 店铺ID,为None时返回所有产品
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
List[Dict]: 产品信息列表
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
df = load_multi_store_data(file_path, store_id=store_id)
|
|
|
|
|
|
|
|
|
|
# 获取唯一产品信息
|
|
|
|
|
product_columns = ['product_id', 'product_name']
|
|
|
|
|
if 'product_category' in df.columns:
|
|
|
|
|
product_columns.append('product_category')
|
|
|
|
|
if 'unit_price' in df.columns:
|
|
|
|
|
product_columns.append('unit_price')
|
|
|
|
|
|
|
|
|
|
products = df[product_columns].drop_duplicates()
|
|
|
|
|
|
|
|
|
|
return products.to_dict('records')
|
|
|
|
|
except Exception as e:
|
|
|
|
|
print(f"获取产品列表失败: {e}")
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
def get_store_product_sales_data(store_id: str,
|
|
|
|
|
product_id: str,
|
2025-07-15 10:37:25 +08:00
|
|
|
|
file_path: str = None) -> pd.DataFrame:
|
2025-07-02 11:05:23 +08:00
|
|
|
|
"""
|
|
|
|
|
获取特定店铺和产品的销售数据,用于模型训练
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
file_path: 数据文件路径
|
|
|
|
|
store_id: 店铺ID
|
|
|
|
|
product_id: 产品ID
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
DataFrame: 处理后的销售数据,包含模型需要的特征
|
|
|
|
|
"""
|
|
|
|
|
# 加载数据
|
|
|
|
|
df = load_multi_store_data(file_path, store_id=store_id, product_id=product_id)
|
|
|
|
|
|
|
|
|
|
if len(df) == 0:
|
|
|
|
|
raise ValueError(f"没有找到店铺 {store_id} 产品 {product_id} 的销售数据")
|
|
|
|
|
|
|
|
|
|
# 确保数据按日期排序
|
|
|
|
|
df = df.sort_values('date').copy()
|
|
|
|
|
|
|
|
|
|
# 数据标准化已在load_multi_store_data中完成
|
|
|
|
|
# 验证必要的列是否存在
|
---
**日期**: 2025-07-18
**主题**: 模型保存逻辑重构与集中化管理
### 目标
根据 `xz训练模型保存规则.md`,将系统中分散的模型文件保存逻辑统一重构,创建一个集中、健壮且可测试的路径管理系统。
### 核心成果
1. **创建了 `server/utils/file_save.py` 模块**: 这个新模块现在是系统中处理模型文件保存路径的唯一权威来源。
2. **实现了三种训练模式的路径生成**: 系统现在可以为“按店铺”、“按药品”和“全局”三种训练模式正确生成层级化的、可追溯的目录结构。
3. **集成了智能ID处理**:
* 对于包含**多个ID**的训练场景,系统会自动计算一个简短的哈希值作为目录名。
* 对于全局训练中只包含**单个店铺或药品ID**的场景,系统会直接使用该ID作为目录名,增强了路径的可读性。
4. **重构了整个训练流程**: 修改了API层、进程管理层以及所有模型训练器,使它们能够协同使用新的路径管理模块。
5. **添加了自动化测试**: 创建了 `test/test_file_save_logic.py` 脚本,用于验证所有路径生成和版本管理逻辑的正确性。
### 详细文件修改记录
1. **`server/utils/file_save.py`**
* **操作**: 创建
* **内容**: 实现了 `ModelPathManager` 类,包含以下核心方法:
* `_hash_ids`: 对ID列表进行排序和哈希。
* `_generate_identifier`: 根据训练模式和参数生成唯一的模型标识符。
* `get_next_version` / `save_version_info`: 线程安全地管理 `versions.json` 文件,实现版本号的获取和更新。
* `get_model_paths`: 作为主入口,协调以上方法,生成包含所有产物路径的字典。
2. **`server/api.py`**
* **操作**: 修改
* **位置**: `start_training` 函数 (`/api/training` 端点)。
* **内容**:
* 导入并实例化 `ModelPathManager`。
* 在接收到训练请求后,调用 `path_manager.get_model_paths()` 来获取所有路径信息。
* 将获取到的 `path_info` 字典和原始请求参数 `training_params` 一并传递给后台训练任务管理器。
* 修复了因重复传递关键字参数 (`model_type`, `training_mode`) 导致的 `TypeError`。
* 修复了 `except` 块中因未导入 `traceback` 模块导致的 `UnboundLocalError`。
3. **`server/utils/training_process_manager.py`**
* **操作**: 修改
* **内容**:
* 修改 `submit_task` 方法,使其能接收 `training_params` 和 `path_info` 字典。
* 在 `TrainingTask` 数据类中增加了 `path_info` 字段来存储路径信息。
* 在 `TrainingWorker` 中,将 `path_info` 传递给实际的训练函数。
* 在 `_monitor_results` 方法中,当任务成功完成时,调用 `path_manager.save_version_info` 来更新 `versions.json`,完成版本管理的闭环。
4. **所有训练器文件** (`mlstm_trainer.py`, `kan_trainer.py`, `tcn_trainer.py`, `transformer_trainer.py`)
* **操作**: 修改
* **内容**:
* 统一修改了主训练函数的签名,增加了 `path_info=None` 参数。
* 移除了所有内部手动构建文件路径的逻辑。
* 所有保存操作(最终模型、检查点、损失曲线图)现在都直接从传入的 `path_info` 字典中获取预先生成好的路径。
* 简化了 `save_checkpoint` 辅助函数,使其也依赖 `path_info`。
5. **`test/test_file_save_logic.py`**
* **操作**: 创建
* **内容**:
* 编写了一个独立的测试脚本,用于验证 `ModelPathManager` 的所有功能。
* 覆盖了所有训练模式及其子场景(包括单ID和多ID哈希)。
* 测试了版本号的正确递增和 `versions.json` 的写入。
* 修复了测试脚本中因绝对/相对路径不匹配和重复关键字参数导致的多个 `AssertionError` 和 `TypeError`。
---
**日期**: 2025-07-18 (后续修复)
**主题**: 修复API层调用路径管理器时的 `TypeError`
### 问题描述
在完成所有重构和测试后,实际运行API时,`POST /api/training` 端点在调用 `path_manager.get_model_paths` 时崩溃,并抛出 `TypeError: get_model_paths() got multiple values for keyword argument 'training_mode'`。
### 根本原因
这是一个回归错误。在修复测试脚本 `test_file_save_logic.py` 中的类似问题时,我未能将相同的修复逻辑应用回 `server/api.py`。代码在调用 `get_model_paths` 时,既通过关键字参数 `training_mode=...` 明确传递了该参数,又通过 `**data` 将其再次传入,导致了冲突。
### 解决方案
1. **文件**: `server/api.py`
2. **位置**: `start_training` 函数。
3. **操作**: 修改了对 `get_model_paths` 的调用逻辑。
4. **内容**:
```python
# 移除 model_type 和 training_mode 以避免重复关键字参数错误
data_for_path = data.copy()
data_for_path.pop('model_type', None)
data_for_path.pop('training_mode', None)
path_info = path_manager.get_model_paths(
training_mode=training_mode,
model_type=model_type,
**data_for_path # 传递剩余的payload
)
```
5. **原因**: 在通过 `**` 解包传递参数之前,先从字典副本中移除了所有会被明确指定的关键字参数,从而确保了函数调用签名的正确性。
---
**日期**: 2025-07-18 (最终修复)
**主题**: 修复因中间层函数签名未更新导致的 `TypeError`
### 问题描述
在完成所有重构后,实际运行API并触发训练任务时,程序在后台进程中因 `TypeError: train_model() got an unexpected keyword argument 'path_info'` 而崩溃。
### 根本原因
这是一个典型的“中间人”遗漏错误。我成功地修改了调用链的两端(`api.py` -> `training_process_manager.py` 和 `*_trainer.py`),但忘记了修改它们之间的中间层——`server/core/predictor.py` 中的 `train_model` 方法。`training_process_manager` 尝试将 `path_info` 传递给 `predictor.train_model`,但后者的函数签名中并未包含这个新参数,导致了 `TypeError`。
### 解决方案
1. **文件**: `server/core/predictor.py`
2. **位置**: `train_model` 函数的定义处。
3. **操作**: 在函数签名中增加了 `path_info=None` 参数。
4. **内容**:
```python
def train_model(self, ..., progress_callback=None, path_info=None):
# ...
```
5. **位置**: `train_model` 函数内部,对所有具体训练器(`train_product_model_with_mlstm`, `_with_kan`, etc.)的调用处。
6. **操作**: 在所有调用中,将接收到的 `path_info` 参数透传下去。
7. **内容**:
```python
# ...
metrics = train_product_model_with_transformer(
...,
path_info=path_info
)
# ...
```
8. **原因**: 通过在中间层函数上“打通”`path_info` 参数的传递通道,确保了从API层到最终训练器层的完整数据流,解决了 `TypeError`。
---
**日期**: 2025-07-18 (最终修复)
**主题**: 修复“按药品训练-聚合所有店铺”模式下的路径生成错误
### 问题描述
在实际运行中发现,当进行“按药品训练”并选择“聚合所有店铺”时,生成的模型保存路径中包含了错误的后缀 `_None`,而不是预期的 `_all` (例如 `.../17002608_None/...`)。
### 根本原因
在 `server/utils/file_save.py` 的 `_generate_identifier` 和 `get_model_paths` 方法中,当 `store_id` 从前端传来为 `None` 时,代码 `scope = store_id if store_id else 'all'` 会因为 `store_id` 是 `None` 而正确地将 `scope` 设为 `'all'`。然而,在 `get_model_paths` 方法中,我错误地使用了 `kwargs.get('store_id', 'all')`,这在 `store_id` 键存在但值为 `None` 时,仍然会返回 `None`,导致了路径拼接错误。
### 解决方案
1. **文件**: `server/utils/file_save.py`
2. **位置**: `_generate_identifier` 和 `get_model_paths` 方法中处理 `product` 训练模式的部分。
3. **操作**: 将逻辑从 `scope = kwargs.get('store_id', 'all')` 修改为更严谨的 `scope = store_id if store_id is not None else 'all'`。
4. **内容**:
```python
# in _generate_identifier
scope = store_id if store_id is not None else 'all'
# in get_model_paths
store_id = kwargs.get('store_id')
scope = store_id if store_id is not None else 'all'
scope_folder = f"{product_id}_{scope}"
```
5. **原因**: 这种写法能正确处理 `store_id` 键不存在、或键存在但值为 `None` 的两种情况,确保在这两种情况下 `scope` 都被正确地设置为 `'all'`,从而生成符合规范的路径。
---
**日期**: 2025-07-18 (最终修复)
**主题**: 修复 `KeyError: 'price'` 和单ID哈希错误
### 问题描述
在完成大规模重构后,实际运行时发现了两个隐藏的bug:
1. 在“按店铺训练”模式下,训练因 `KeyError: 'price'` 而失败。
2. 在“按店铺训练”模式下,当只选择一个“指定药品”时,系统仍然错误地对该药品的ID进行了哈希处理,而不是直接使用ID。
### 根本原因
1. **`KeyError`**: `server/utils/multi_store_data_utils.py` 中的 `get_store_product_sales_data` 函数包含了一个硬编码的列校验,该校验要求 `price` 列必须存在,但这与当前的数据源不符。
2. **哈希错误**: `server/utils/file_save.py` 中的 `get_model_paths` 方法在处理 `store` 训练模式时,没有复用 `_generate_identifier` 中已经写好的单ID判断逻辑,导致了逻辑不一致。
### 解决方案
1. **修复 `KeyError`**:
* **文件**: `server/utils/multi_store_data_utils.py`
* **位置**: `get_store_product_sales_data` 函数。
* **操作**: 从 `required_columns` 列表中移除了 `'price'`,根除了这个硬性依赖。
2. **修复哈希逻辑**:
* **文件**: `server/utils/file_save.py`
* **位置**: `_generate_identifier` 和 `get_model_paths` 方法中处理 `store` 训练模式的部分。
* **操作**: 统一了逻辑,确保在这两个地方都使用了 `scope = product_ids[0] if len(product_ids) == 1 else self._hash_ids(product_ids)` 的判断,从而在只选择一个药品时直接使用其ID。
3. **更新测试**:
* **文件**: `test/test_file_save_logic.py`
* **操作**: 增加了新的测试用例,专门验证“按店铺训练-单个指定药品”场景下的路径生成是否正确。
---
**日期**: 2025-07-18 (最终修复)
**主题**: 修复全局训练范围值不匹配导致的 `ValueError`
### 问题描述
在完成所有重构后,实际运行API并触发“全局训练-所有店铺所有药品”时,程序因 `ValueError: 未知的全局训练范围: all_stores_all_products` 而崩溃。
### 根本原因
前端传递的 `training_scope` 值为 `all_stores_all_products`,而 `server/utils/file_save.py` 中的 `_generate_identifier` 和 `get_model_paths` 方法只处理了 `all` 这个值,未能兼容前端传递的具体字符串,导致逻辑判断失败。
### 解决方案
1. **文件**: `server/utils/file_save.py`
2. **位置**: `_generate_identifier` 和 `get_model_paths` 方法中处理 `global` 训练模式的部分。
3. **操作**: 将逻辑判断从 `if training_scope == 'all':` 修改为 `if training_scope in ['all', 'all_stores_all_products']:`。
4. **原因**: 使代码能够同时兼容两种表示“所有范围”的字符串,确保了前端请求的正确处理。
5. **更新测试**:
* **文件**: `test/test_file_save_logic.py`
* **操作**: 增加了新的测试用例,专门验证 `training_scope` 为 `all_stores_all_products` 时的路径生成是否正确。
---
**日期**: 2025-07-18 (最终优化)
**主题**: 优化全局训练自定义模式下的单ID路径生成
### 问题描述
根据用户反馈,希望在全局训练的“自定义范围”模式下,如果只选择单个店铺和/或单个药品,路径中应直接使用ID而不是哈希值,以增强可读性。
### 解决方案
1. **文件**: `server/utils/file_save.py`
2. **位置**: `_generate_identifier` 和 `get_model_paths` 方法中处理 `global` 训练模式 `custom` 范围的部分。
3. **操作**: 为 `store_ids` 和 `product_ids` 分别增加了单ID判断逻辑。
4. **内容**:
```python
# in _generate_identifier
s_id = store_ids[0] if len(store_ids) == 1 else self._hash_ids(store_ids)
p_id = product_ids[0] if len(product_ids) == 1 else self._hash_ids(product_ids)
scope_part = f"custom_s_{s_id}_p_{p_id}"
# in get_model_paths
store_ids = kwargs.get('store_ids', [])
product_ids = kwargs.get('product_ids', [])
s_id = store_ids[0] if len(store_ids) == 1 else self._hash_ids(store_ids)
p_id = product_ids[0] if len(product_ids) == 1 else self._hash_ids(product_ids)
scope_parts.extend(['custom', s_id, p_id])
```
5. **原因**: 使 `custom` 模式下的路径生成逻辑与 `selected_stores` 和 `selected_products` 模式保持一致,在只选择一个ID时优先使用ID本身,提高了路径的可读性和一致性。
6. **更新测试**:
* **文件**: `test/test_file_save_logic.py`
* **操作**: 增加了新的测试用例,专门验证“全局训练-自定义范围-单ID”场景下的路径生成是否正确。
2025-07-18 16:45:21 +08:00
|
|
|
|
required_columns = ['sales', 'weekday', 'month', 'is_holiday', 'is_weekend', 'is_promotion', 'temperature']
|
2025-07-02 11:05:23 +08:00
|
|
|
|
missing_columns = [col for col in required_columns if col not in df.columns]
|
|
|
|
|
|
|
|
|
|
if missing_columns:
|
|
|
|
|
print(f"警告: 数据标准化后仍缺少列 {missing_columns}")
|
|
|
|
|
raise ValueError(f"无法获取完整的特征数据,缺少列: {missing_columns}")
|
|
|
|
|
|
2025-07-14 19:26:57 +08:00
|
|
|
|
# 定义模型训练所需的所有列(特征 + 目标)
|
|
|
|
|
final_columns = [
|
|
|
|
|
'date', 'sales', 'product_id', 'product_name', 'store_id', 'store_name',
|
|
|
|
|
'weekday', 'month', 'is_holiday', 'is_weekend', 'is_promotion', 'temperature'
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
# 筛选出DataFrame中实际存在的列
|
|
|
|
|
existing_columns = [col for col in final_columns if col in df.columns]
|
|
|
|
|
|
|
|
|
|
# 返回只包含这些必需列的DataFrame
|
|
|
|
|
return df[existing_columns]
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
2025-07-14 19:26:57 +08:00
|
|
|
|
def aggregate_multi_store_data(product_id: Optional[str] = None,
|
|
|
|
|
store_id: Optional[str] = None,
|
|
|
|
|
aggregation_method: str = 'sum',
|
2025-07-15 10:37:25 +08:00
|
|
|
|
file_path: str = None) -> pd.DataFrame:
|
2025-07-02 11:05:23 +08:00
|
|
|
|
"""
|
2025-07-14 19:26:57 +08:00
|
|
|
|
聚合销售数据,可按产品(全局)或按店铺(所有产品)
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
file_path: 数据文件路径
|
2025-07-14 19:26:57 +08:00
|
|
|
|
product_id: 产品ID (用于全局模型)
|
|
|
|
|
store_id: 店铺ID (用于店铺聚合模型)
|
2025-07-02 11:05:23 +08:00
|
|
|
|
aggregation_method: 聚合方法 ('sum', 'mean', 'median')
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
DataFrame: 聚合后的销售数据
|
|
|
|
|
"""
|
2025-07-14 19:26:57 +08:00
|
|
|
|
# 根据是全局聚合、店铺聚合还是真正全局聚合来加载数据
|
|
|
|
|
if store_id:
|
|
|
|
|
# 店铺聚合:加载该店铺的所有数据
|
|
|
|
|
df = load_multi_store_data(file_path, store_id=store_id)
|
|
|
|
|
if len(df) == 0:
|
|
|
|
|
raise ValueError(f"没有找到店铺 {store_id} 的销售数据")
|
|
|
|
|
grouping_entity = f"店铺 {store_id}"
|
|
|
|
|
elif product_id:
|
|
|
|
|
# 按产品聚合:加载该产品在所有店铺的数据
|
|
|
|
|
df = load_multi_store_data(file_path, product_id=product_id)
|
|
|
|
|
if len(df) == 0:
|
|
|
|
|
raise ValueError(f"没有找到产品 {product_id} 的销售数据")
|
|
|
|
|
grouping_entity = f"产品 {product_id}"
|
|
|
|
|
else:
|
|
|
|
|
# 真正全局聚合:加载所有数据
|
|
|
|
|
df = load_multi_store_data(file_path)
|
|
|
|
|
if len(df) == 0:
|
|
|
|
|
raise ValueError("数据文件为空,无法进行全局聚合")
|
|
|
|
|
grouping_entity = "所有产品"
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
|
|
|
|
# 按日期聚合(使用标准化后的列名)
|
|
|
|
|
agg_dict = {}
|
|
|
|
|
if aggregation_method == 'sum':
|
|
|
|
|
agg_dict = {
|
|
|
|
|
'sales': 'sum', # 标准化后的销量列
|
|
|
|
|
'sales_amount': 'sum',
|
|
|
|
|
'price': 'mean' # 标准化后的价格列,取平均值
|
|
|
|
|
}
|
|
|
|
|
elif aggregation_method == 'mean':
|
|
|
|
|
agg_dict = {
|
|
|
|
|
'sales': 'mean',
|
|
|
|
|
'sales_amount': 'mean',
|
|
|
|
|
'price': 'mean'
|
|
|
|
|
}
|
|
|
|
|
elif aggregation_method == 'median':
|
|
|
|
|
agg_dict = {
|
|
|
|
|
'sales': 'median',
|
|
|
|
|
'sales_amount': 'median',
|
|
|
|
|
'price': 'median'
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# 确保列名存在
|
|
|
|
|
available_cols = df.columns.tolist()
|
|
|
|
|
agg_dict = {k: v for k, v in agg_dict.items() if k in available_cols}
|
|
|
|
|
|
|
|
|
|
# 聚合数据
|
|
|
|
|
aggregated_df = df.groupby('date').agg(agg_dict).reset_index()
|
|
|
|
|
|
|
|
|
|
# 获取产品信息(取第一个店铺的信息)
|
|
|
|
|
product_info = df[['product_id', 'product_name', 'product_category']].iloc[0]
|
|
|
|
|
for col, val in product_info.items():
|
|
|
|
|
aggregated_df[col] = val
|
|
|
|
|
|
|
|
|
|
# 添加店铺信息标识为全局
|
|
|
|
|
aggregated_df['store_id'] = 'GLOBAL'
|
|
|
|
|
aggregated_df['store_name'] = f'全部店铺-{aggregation_method.upper()}'
|
|
|
|
|
aggregated_df['store_location'] = '全局聚合'
|
|
|
|
|
aggregated_df['store_type'] = 'global'
|
|
|
|
|
|
|
|
|
|
# 对聚合后的数据进行标准化(添加缺失的特征列)
|
|
|
|
|
aggregated_df = aggregated_df.sort_values('date').copy()
|
|
|
|
|
aggregated_df = standardize_column_names(aggregated_df)
|
|
|
|
|
|
2025-07-14 19:26:57 +08:00
|
|
|
|
# 定义模型训练所需的所有列(特征 + 目标)
|
|
|
|
|
final_columns = [
|
|
|
|
|
'date', 'sales', 'product_id', 'product_name', 'store_id', 'store_name',
|
|
|
|
|
'weekday', 'month', 'is_holiday', 'is_weekend', 'is_promotion', 'temperature'
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
# 筛选出DataFrame中实际存在的列
|
|
|
|
|
existing_columns = [col for col in final_columns if col in aggregated_df.columns]
|
|
|
|
|
|
|
|
|
|
# 返回只包含这些必需列的DataFrame
|
|
|
|
|
return aggregated_df[existing_columns]
|
2025-07-02 11:05:23 +08:00
|
|
|
|
|
2025-07-15 10:37:25 +08:00
|
|
|
|
def get_sales_statistics(file_path: str = None,
|
2025-07-02 11:05:23 +08:00
|
|
|
|
store_id: Optional[str] = None,
|
|
|
|
|
product_id: Optional[str] = None) -> Dict[str, Any]:
|
|
|
|
|
"""
|
|
|
|
|
获取销售数据统计信息
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
file_path: 数据文件路径
|
|
|
|
|
store_id: 店铺ID
|
|
|
|
|
product_id: 产品ID
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
Dict: 统计信息
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
df = load_multi_store_data(file_path, store_id=store_id, product_id=product_id)
|
|
|
|
|
|
|
|
|
|
if len(df) == 0:
|
|
|
|
|
return {'error': '没有数据'}
|
|
|
|
|
|
|
|
|
|
stats = {
|
|
|
|
|
'total_records': len(df),
|
|
|
|
|
'date_range': {
|
|
|
|
|
'start': df['date'].min().strftime('%Y-%m-%d'),
|
|
|
|
|
'end': df['date'].max().strftime('%Y-%m-%d')
|
|
|
|
|
},
|
|
|
|
|
'stores': df['store_id'].nunique(),
|
|
|
|
|
'products': df['product_id'].nunique(),
|
|
|
|
|
'total_sales_amount': float(df['sales_amount'].sum()) if 'sales_amount' in df.columns else 0,
|
|
|
|
|
'total_quantity': int(df['quantity_sold'].sum()) if 'quantity_sold' in df.columns else 0,
|
|
|
|
|
'avg_daily_sales': float(df.groupby('date')['quantity_sold'].sum().mean()) if 'quantity_sold' in df.columns else 0
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return stats
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return {'error': str(e)}
|
|
|
|
|
|
|
|
|
|
# 向后兼容的函数
|
2025-07-15 10:37:25 +08:00
|
|
|
|
def load_data(file_path=None, store_id=None):
|
2025-07-02 11:05:23 +08:00
|
|
|
|
"""
|
|
|
|
|
向后兼容的数据加载函数
|
|
|
|
|
"""
|
|
|
|
|
return load_multi_store_data(file_path, store_id=store_id)
|