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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
| #二阶段训练脚本
import os
import sys
import subprocess
import argparse
import yaml
def train_step2(base_config_path, output_root_dir,
pretrained_model_path_stage1,
synthetic_train_label, synthetic_eval_label):
"""
执行第二阶段训练:解冻骨干网络,使用合成数据。
参数:
base_config_path: 基础配置文件路径
output_root_dir: 所有输出的根目录 (例如 './output_multistage')
pretrained_model_path_stage1: 第一阶段训练得到的最佳模型路径
synthetic_train_label: 合成数据的训练标签文件路径
synthetic_eval_label: 合成数据的验证标签文件路径
"""
stage_name = 'step2'
stage_output_dir = os.path.join(output_root_dir, stage_name)
os.makedirs(stage_output_dir, exist_ok=True)
print(f"\n" + "#"*50)
print(f"### 开始 {stage_name} 阶段训练: 解冻骨干网络,使用合成数据 ###")
print("#"*50)
# 读取基础配置
with open(base_config_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
# --- 修改配置以适应第二阶段训练 ---
config['Global']['save_model_dir'] = stage_output_dir
config['Global']['epoch_num'] = 20 # 增加 epoch 数量,让整个网络有足够时间微调
# 关键修改:解冻骨干网络
config['Architecture']['Backbone']['freeze'] = False
# 设置数据路径 (仍然是合成数据)
config['Train']['dataset']['label_file_list'] = [synthetic_train_label]
config['Eval']['dataset']['label_file_list'] = [synthetic_eval_label]
# 加载第一阶段训练得到的最佳模型
config['Global']['pretrained_model'] = pretrained_model_path_stage1
# 降低学习率,避免破坏预训练特征
config['Optimizer']['lr']['learning_rate'] = 0.00004
# 保存修改后的配置
stage_config_path = os.path.join(stage_output_dir, f'{stage_name}_config.yml')
with open(stage_config_path, 'w', encoding='utf-8') as f:
yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
print(f"[{stage_name}] 阶段配置文件已保存: {stage_config_path}")
# 执行训练命令
# 假设 train_step2.py 脚本和 tools 目录在同一父目录下
train_script_path = os.path.join(os.path.dirname(__file__), 'tools', 'train.py')
cmd = [
'python', train_script_path,
'-c', stage_config_path,
'-o', f"Global.use_gpu=true",
'-o', f"Global.use_visualdl=true" # 启用VisualDL监控
]
print(f"执行命令: {' '.join(cmd)}")
try:
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
for byte_line in process.stdout:
try:
line = byte_line.decode('utf-8', errors='ignore').strip()
if line:
print(f"[{stage_name}] {line}")
except Exception as e:
print(f"[{stage_name}] Warning: Could not decode line: {byte_line}. Error: {e}")
process.wait()
if process.returncode != 0:
print(f"[{stage_name}] Error: Subprocess failed with exit code {process.returncode}")
raise RuntimeError(f"{stage_name} 阶段训练失败,请检查日志。")
print(f"[{stage_name}] 阶段训练完成!")
# 保存最佳模型通 save_model_dir/best_accuracy
best_model_dir = os.path.join(config['Global']['save_model_dir'], 'best_accuracy')
print(f"[{stage_name}] 最佳模型保存在: {best_model_dir}")
return best_model_dir
except Exception as e:
print(f"[{stage_name}] An error occurred during training: {e}")
raise
def main():
parser = argparse.ArgumentParser(description="PaddleOCR第二阶段训练脚本")
parser.add_argument("--base_config", type=str, default="config_rec/PP-OCRv5_mobile_rec2.yml",
help="基础配置文件路径")
parser.add_argument("--output_root_dir", type=str, default="./output",
help="所有阶段输出的根目录")
parser.add_argument("--pretrained_model_path_stage1", type=str,
default="./output/step1/best_model/model",
help="第一阶段训练得到的最佳模型路径")
parser.add_argument("--synthetic_train_label", type=str, default="./train_data/train.txt",
help="合成数据的训练标签文件路径")
parser.add_argument("--synthetic_eval_label", type=str, default="./train_data/val.txt",
help="合成数据的验证标签文件路径")
args = parser.parse_args()
# 确保总输出目录存在
if not os.path.exists(args.output_root_dir):
os.makedirs(args.output_root_dir)
best_model_stage2_path = train_step2(
base_config_path=args.base_config,
output_root_dir=args.output_root_dir,
pretrained_model_path_stage1=args.pretrained_model_path_stage1,
synthetic_train_label=args.synthetic_train_label,
synthetic_eval_label=args.synthetic_eval_label
)
if best_model_stage2_path:
print("\n" + "="*50)
print("第二阶段训练成功完成!")
print(f"第二阶段最佳模型路径: {best_model_stage2_path}")
print("="*50)
else:
print("第二阶段训练失败,请检查错误信息")
if __name__ == "__main__":
main()
|