Files
FoodClassifier/GRID_SEARCH_README.md
T

150 lines
4.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CosFace超参数网格搜索使用指南
## 概述
已完成CosFace超参数网格搜索功能的实施,用于优化`scale (s)``margin (m)`两个核心超参数。
## 修改文件清单
### 1. `requirements.txt`
- ✅ 添加依赖:`pandas>=2.0.0``seaborn>=0.12.0`
### 2. `train/train_cosface_embedding.py`
-`TaskConfig`添加`test_dir`字段
-`TASKS`字典中所有任务添加测试集路径
### 3. `train/grid_search_cosface.py` (新建)
- ✅ 完整的网格搜索脚本 (~350行)
## 搜索空间配置
当前为dish任务配置的搜索空间:
```python
GRID_PARAMS = {
'dish': {
's': [56.0, 60.0, 64.0, 68.0], # 4个scale值
'm': [0.32, 0.35, 0.38, 0.40], # 4个margin值
}
}
```
**总配置数**: 4 × 4 = **16组实验**
## 使用方法
### 1. 安装依赖
```bash
pip install pandas>=2.0.0 seaborn>=0.12.0
```
### 2. 运行网格搜索
```bash
# 完整搜索(16组配置)
python train/grid_search_cosface.py --task dish
# 测试运行(限制配置数)
python train/grid_search_cosface.py --task dish --max_configs 2
# 自定义参数
python train/grid_search_cosface.py --task dish --epochs 100 --patience 10 --min_epochs 25
```
### 3. 参数说明
- `--task`: 任务名称 (`dish` / `whole_ingredient` / `processed_ingredient`)
- `--max_configs`: 限制最大配置数(用于测试,可选)
- `--epochs`: 每个配置的最大训练轮数(默认100)
- `--patience`: 早停容忍轮数(默认10
- `--min_epochs`: 最小训练轮数(默认25
## 输出文件
运行后会在`model/DishClassification/grid_search_YYYYMMDD_HHMMSS/`目录下生成:
1. **`grid_search_results.csv`** - 所有配置的详细结果表格
2. **`heatmap.png`** - 参数热力图(测试集准确率)
3. **`summary.txt`** - 搜索总结报告(含最佳配置)
4. **`model_s{s}_m{m}.pth`** - 每个配置的模型权重
5. **`grid_search.log`** - 完整训练日志
## 评估指标
- **主要指标**: 测试集准确率 (`test_acc`) - 用于选择最佳配置
- **辅助指标**: 验证集准确率、训练轮数、训练时间
## 应用最佳配置
网格搜索完成后:
1. 查看`summary.txt`找到最佳配置
2. 手动更新`train/train_cosface_embedding.py`中的`TASKS`字典:
```python
'dish': TaskConfig(
# ... 其他配置保持不变 ...
cosface_s=64.0, # 更新为最佳s值
cosface_m=0.38, # 更新为最佳m值
)
```
3. 后续训练将自动使用最佳配置
## 预计耗时
基于以下假设:
- 每个配置平均训练25-40个epoch(早停机制)
- 每个epoch约1-2分钟
- **单个配置**: ~30-60分钟
- **16组配置总耗时**: ~8-16小时
**建议**: 使用GPU运行,可在夜间或周末执行完整搜索。
## 注意事项
1. **数据集要求**: 确保`dataset/DishClassification/test/`目录存在且有数据
2. **GPU推荐**: 网格搜索计算量大,强烈建议使用GPU
3. **磁盘空间**: 每个配置约占用500MB,16组需8GB空间
4. **中断恢复**: 当前版本不支持断点续训,建议一次性完成
## 高级用法
### 修改搜索空间
编辑`train/grid_search_cosface.py`中的`GRID_PARAMS`字典:
```python
GRID_PARAMS = {
'dish': {
's': [60.0, 64.0, 68.0, 72.0], # 自定义scale范围
'm': [0.30, 0.35, 0.40, 0.45], # 自定义margin范围
}
}
```
### 调整早停策略
通过命令行参数调整:
```bash
python train/grid_search_cosface.py --task dish --patience 15 --min_epochs 30
```
## 故障排除
**问题1**: `ModuleNotFoundError: No module named 'pandas'`
- 解决: `pip install pandas seaborn`
**问题2**: 测试集目录不存在
- 解决: 确认`dataset/DishClassification/test/`路径正确且有数据
**问题3**: CUDA out of memory
- 解决: 减小`batch_size`或在CPU上运行(速度较慢)
## 示例结果解读
`summary.txt`示例:
```
最佳配置:
s (scale) = 64.0
m (margin) = 0.38
测试集准确率 = 98.50%
验证集准确率 = 100.00%
训练轮数 = 32
训练时间 = 45.3 分钟
```
这表示s=64.0, m=0.38是最优组合,在测试集上达到98.50%准确率。