image.vision\ocr\training_framework.mbt

96.3% · 155 / 161 points · 781 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # 训练框架 ocr/training_framework
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// OCR 模型训练框架(v13.1.0)
  7. 7// 数据增强、优化器、学习率调度、训练循环、模型评估、早停机制
  8. 8
  9. 9///|
  10. 10/// 优化器类型
  11. 11/// `#non_exhaustive` 表示未来可能添加新构造器
  12. 12#derive(Eq, @debug.Debug)
  13. 13#non_exhaustive
  14. 14pub(all) enum OptimizerType {
  15. 15 SGD
  16. 16 Momentum
  17. 17 Adam
  18. 18 RMSprop
  19. 19 Adagrad
  20. 20}
  21. 21
  22. 22///|
  23. 23pub extend OptimizerType with @debug.Debug::{to_repr}
  24. 24
  25. 25///|
  26. 26pub extend OptimizerType with Eq::{not_equal, equal}
  27. 27
  28. 28///|
  29. 29/// 优化器配置
  30. 30#derive(Eq, @debug.Debug)
  31. 31pub(all) struct OptimizerConfig {
  32. 32 optimizer_type : OptimizerType
  33. 33 learning_rate : Double
  34. 34 momentum : Double
  35. 35 beta1 : Double
  36. 36 beta2 : Double
  37. 37 epsilon : Double
  38. 38 weight_decay : Double
  39. 39 grad_clip : Double
  40. 40}
  41. 41
  42. 42///|
  43. 43pub extend OptimizerConfig with Eq::{not_equal, equal}
  44. 44
  45. 45///|
  46. 46pub extend OptimizerConfig with @debug.Debug::{to_repr}
  47. 47
  48. 48///|
  49. 49/// 学习率调度器类型
  50. 50/// `#non_exhaustive` 表示未来可能添加新构造器
  51. 51#derive(Eq, @debug.Debug)
  52. 52#non_exhaustive
  53. 53pub(all) enum LRSchedulerType {
  54. 54 Constant
  55. 55 StepDecay
  56. 56 ExponentialDecay
  57. 57 CosineAnnealing
  58. 58 WarmupCosine
  59. 59 ReduceOnPlateau
  60. 60}
  61. 61
  62. 62///|
  63. 63pub extend LRSchedulerType with @debug.Debug::{to_repr}
  64. 64
  65. 65///|
  66. 66pub extend LRSchedulerType with Eq::{not_equal, equal}
  67. 67
  68. 68///|
  69. 69/// 学习率调度器配置
  70. 70#derive(Eq, @debug.Debug)
  71. 71pub(all) struct LRSchedulerConfig {
  72. 72 scheduler_type : LRSchedulerType
  73. 73 initial_lr : Double
  74. 74 min_lr : Double
  75. 75 decay_rate : Double
  76. 76 decay_steps : Int32
  77. 77 warmup_steps : Int32
  78. 78 patience : Int32
  79. 79 factor : Double
  80. 80}
  81. 81
  82. 82///|
  83. 83pub extend LRSchedulerConfig with Eq::{not_equal, equal}
  84. 84
  85. 85///|
  86. 86pub extend LRSchedulerConfig with @debug.Debug::{to_repr}
  87. 87
  88. 88///|
  89. 89/// 数据增强类型
  90. 90/// `#non_exhaustive` 表示未来可能添加新构造器
  91. 91#derive(Eq, @debug.Debug)
  92. 92#non_exhaustive
  93. 93pub(all) enum AugmentationType {
  94. 94 RandomRotation
  95. 95 RandomShift
  96. 96 RandomScale
  97. 97 RandomShear
  98. 98 RandomNoise
  99. 99 RandomBlur
  100. 100 RandomBrightness
  101. 101 RandomContrast
  102. 102 ElasticTransform
  103. 103}
  104. 104
  105. 105///|
  106. 106pub extend AugmentationType with @debug.Debug::{to_repr}
  107. 107
  108. 108///|
  109. 109pub extend AugmentationType with Eq::{not_equal, equal}
  110. 110
  111. 111///|
  112. 112/// 数据增强配置
  113. 113#derive(Eq, @debug.Debug)
  114. 114pub(all) struct AugmentationConfig {
  115. 115 enabled : Bool
  116. 116 augmentation_types : Array[AugmentationType]
  117. 117 rotation_range : Double // 度
  118. 118 shift_range : Double // 比例
  119. 119 scale_range : Double // 比例
  120. 120 noise_level : Double
  121. 121 blur_sigma : Double
  122. 122 brightness_range : Double
  123. 123 contrast_range : Double
  124. 124 probability : Double // 每个增强的应用概率
  125. 125}
  126. 126
  127. 127///|
  128. 128pub extend AugmentationConfig with Eq::{not_equal, equal}
  129. 129
  130. 130///|
  131. 131pub extend AugmentationConfig with @debug.Debug::{to_repr}
  132. 132
  133. 133///|
  134. 134/// 训练配置
  135. 135#derive(Eq, @debug.Debug)
  136. 136pub(all) struct TrainingConfig {
  137. 137 epochs : Int32
  138. 138 batch_size : Int32
  139. 139 optimizer : OptimizerConfig
  140. 140 lr_scheduler : LRSchedulerConfig
  141. 141 augmentation : AugmentationConfig
  142. 142 early_stopping_patience : Int32
  143. 143 early_stopping_min_delta : Double
  144. 144 save_best_only : Bool
  145. 145 checkpoint_interval : Int32
  146. 146 log_interval : Int32
  147. 147 validation_split : Double
  148. 148 shuffle : Bool
  149. 149 random_seed : Int32
  150. 150}
  151. 151
  152. 152///|
  153. 153pub extend TrainingConfig with Eq::{not_equal, equal}
  154. 154
  155. 155///|
  156. 156pub extend TrainingConfig with @debug.Debug::{to_repr}
  157. 157
  158. 158///|
  159. 159/// 训练指标
  160. 160#derive(Eq, @debug.Debug)
  161. 161pub(all) struct TrainingMetrics {
  162. 162 epoch : Int32
  163. 163 train_loss : Double
  164. 164 train_accuracy : Double
  165. 165 val_loss : Double
  166. 166 val_accuracy : Double
  167. 167 learning_rate : Double
  168. 168 time_ms : Double
  169. 169 is_best : Bool
  170. 170}
  171. 171
  172. 172///|
  173. 173pub extend TrainingMetrics with Eq::{not_equal, equal}
  174. 174
  175. 175///|
  176. 176pub extend TrainingMetrics with @debug.Debug::{to_repr}
  177. 177
  178. 178///|
  179. 179/// 训练状态
  180. 180#derive(Eq, @debug.Debug)
  181. 181pub(all) struct TrainingState {
  182. 182 current_epoch : Int32
  183. 183 best_val_accuracy : Double
  184. 184 best_epoch : Int32
  185. 185 epochs_without_improvement : Int32
  186. 186 total_training_time_ms : Double
  187. 187 history : Array[TrainingMetrics]
  188. 188 is_completed : Bool
  189. 189 stop_reason : String
  190. 190}
  191. 191
  192. 192///|
  193. 193pub extend TrainingState with Eq::{not_equal, equal}
  194. 194
  195. 195///|
  196. 196pub extend TrainingState with @debug.Debug::{to_repr}
  197. 197
  198. 198///|
  199. 199/// 数据加载器
  200. 200#derive(Eq, @debug.Debug)
  201. 201pub(all) struct DataLoader {
  202. 202 samples : Array[DLTrainingSample]
  203. 203 batch_size : Int32
  204. 204 shuffle : Bool
  205. 205 current_index : Int32
  206. 206 epoch : Int32
  207. 207}
  208. 208
  209. 209///|
  210. 210pub extend DataLoader with Eq::{not_equal, equal}
  211. 211
  212. 212///|
  213. 213pub extend DataLoader with @debug.Debug::{to_repr}
  214. 214
  215. 215///|
  216. 216/// 创建默认训练配置
  217. 217pub fn create_default_training_config() -> TrainingConfig {
  218. 218● TrainingConfig::{
  219. 219 epochs: 50,
  220. 220 batch_size: 32,
  221. 221 optimizer: OptimizerConfig::{
  222. 222 optimizer_type: OptimizerType::Adam,
  223. 223 learning_rate: 0.001,
  224. 224 momentum: 0.9,
  225. 225 beta1: 0.9,
  226. 226 beta2: 0.999,
  227. 227 epsilon: 0.0000001,
  228. 228 weight_decay: 0.0001,
  229. 229 grad_clip: 1.0,
  230. 230 },
  231. 231 lr_scheduler: LRSchedulerConfig::{
  232. 232 scheduler_type: LRSchedulerType::CosineAnnealing,
  233. 233 initial_lr: 0.001,
  234. 234 min_lr: 0.00001,
  235. 235 decay_rate: 0.1,
  236. 236 decay_steps: 10,
  237. 237 warmup_steps: 5,
  238. 238 patience: 5,
  239. 239 factor: 0.5,
  240. 240 },
  241. 241 augmentation: AugmentationConfig::{
  242. 242 enabled: true,
  243. 243 augmentation_types: [
  244. 244 AugmentationType::RandomRotation,
  245. 245 AugmentationType::RandomShift,
  246. 246 AugmentationType::RandomScale,
  247. 247 AugmentationType::RandomNoise,
  248. 248 ],
  249. 249 rotation_range: 15.0,
  250. 250 shift_range: 0.1,
  251. 251 scale_range: 0.1,
  252. 252 noise_level: 0.05,
  253. 253 blur_sigma: 1.0,
  254. 254 brightness_range: 0.2,
  255. 255 contrast_range: 0.2,
  256. 256 probability: 0.5,
  257. 257 },
  258. 258 early_stopping_patience: 10,
  259. 259 early_stopping_min_delta: 0.001,
  260. 260 save_best_only: true,
  261. 261 checkpoint_interval: 5,
  262. 262 log_interval: 1,
  263. 263 validation_split: 0.2,
  264. 264 shuffle: true,
  265. 265 random_seed: 42,
  266. 266 }
  267. 267}
  268. 268
  269. 269///|
  270. 270/// 创建数据加载器
  271. 271pub fn create_data_loader(
  272. 272 samples : Array[DLTrainingSample],
  273. 273 batch_size : Int32,
  274. 274 shuffle : Bool,
  275. 275) -> DataLoader raise @types.LoadError {
  276. 276 // 输入验证
  277. 277● if samples.length() == 0 {
  278. 278● raise @types.LoadError::DecodeFailed(
  279. 279 "create_data_loader: 样本列表不能为空",
  280. 280 )
  281. 281 }
  282. 282 if batch_size <= 0 {
  283. 283● raise @types.LoadError::DecodeFailed(
  284. 284 "create_data_loader: 批大小必须大于0",
  285. 285 )
  286. 286 }
  287. 287 DataLoader::{ samples, batch_size, shuffle, current_index: 0, epoch: 0, }
  288. 288}
  289. 289
  290. 290///|
  291. 291/// 获取下一批数据
  292. 292pub fn next_batch(
  293. 293 loader : DataLoader,
  294. 294) -> (Array[DLTrainingSample], DataLoader) raise @types.LoadError {
  295. 295 // 输入验证
  296. 296● if loader.samples.length() == 0 {
  297. 297● raise @types.LoadError::DecodeFailed(
  298. 298 "next_batch: 数据加载器的样本列表不能为空",
  299. 299 )
  300. 300 }
  301. 301 if loader.batch_size <= 0 {
  302. 302● raise @types.LoadError::DecodeFailed("next_batch: 批大小必须大于0")
  303. 303 }
  304. 304 let end_index = if loader.current_index + loader.batch_size <
  305. 305● loader.samples.length() {
  306. 306● loader.current_index + loader.batch_size
  307. 307 } else {
  308. 308● loader.samples.length()
  309. 309 }
  310. 310 let batch : Array[DLTrainingSample] = []
  311. 311 for i in loader.current_index..<end_index {
  312. 312● batch.push(loader.samples[i])
  313. 313 }
  314. 314● let new_index = if end_index >= loader.samples.length() {
  315. 315● 0
  316. 316 } else {
  317. 317● end_index
  318. 318 }
  319. 319● let new_epoch = if end_index >= loader.samples.length() {
  320. 320● loader.epoch + 1
  321. 321 } else {
  322. 322● loader.epoch
  323. 323 }
  324. 324 (
  325. 325 batch,
  326. 326 DataLoader::{
  327. 327 samples: loader.samples,
  328. 328 batch_size: loader.batch_size,
  329. 329 shuffle: loader.shuffle,
  330. 330 current_index: new_index,
  331. 331 epoch: new_epoch,
  332. 332 },
  333. 333 )
  334. 334}
  335. 335
  336. 336///|
  337. 337/// 幂运算
  338. 338fn power_double(base : Double, exp : Int32) -> Double {
  339. 339● let mut result = 1.0
  340. 340 for _ in 0..<exp {
  341. 341● result = result * base
  342. 342 }
  343. 343 result
  344. 344}
  345. 345
  346. 346///|
  347. 347/// 近似 cos 函数(泰勒级数)
  348. 348fn approx_cos(x : Double) -> Double {
  349. 349 // 归一化到 [-pi, pi]
  350. 350● let pi = 3.141592653589793
  351. 351 let mut t = x % (2.0 * pi)
  352. 352 if t > pi {
  353. 353○ t = t - 2.0 * pi
  354. 354 }
  355. 355 if t < -pi {
  356. 356○ t = t + 2.0 * pi
  357. 357 }
  358. 358 // 泰勒级数
  359. 359 let mut result = 1.0
  360. 360 let mut term = 1.0
  361. 361 for i in 1..<10 {
  362. 362● term = term *
  363. 363 (-t * t) /
  364. 364● ((2.0 * i.to_double() - 1.0) * (2.0 * i.to_double()))
  365. 365 result = result + term
  366. 366 }
  367. 367 result
  368. 368}
  369. 369
  370. 370///|
  371. 371/// 计算学习率
  372. 372pub fn calculate_learning_rate(
  373. 373 config : LRSchedulerConfig,
  374. 374 epoch : Int32,
  375. 375 current_lr : Double,
  376. 376 val_loss : Double,
  377. 377) -> Double raise @types.LoadError {
  378. 378 // 输入验证
  379. 379● if epoch < 0 {
  380. 380● raise @types.LoadError::DecodeFailed(
  381. 381 "calculate_learning_rate: 轮次不能为负",
  382. 382 )
  383. 383 }
  384. 384 if current_lr <= 0.0 {
  385. 385● raise @types.LoadError::DecodeFailed(
  386. 386 "calculate_learning_rate: 当前学习率必须大于0",
  387. 387 )
  388. 388 }
  389. 389 if val_loss < 0.0 {
  390. 390● raise @types.LoadError::DecodeFailed(
  391. 391 "calculate_learning_rate: 验证损失不能为负",
  392. 392 )
  393. 393 }
  394. 394 if config.initial_lr <= 0.0 {
  395. 395● raise @types.LoadError::DecodeFailed(
  396. 396 "calculate_learning_rate: 初始学习率必须大于0",
  397. 397 )
  398. 398 }
  399. 399 if config.min_lr < 0.0 {
  400. 400● raise @types.LoadError::DecodeFailed(
  401. 401 "calculate_learning_rate: 最小学习率不能为负",
  402. 402 )
  403. 403 }
  404. 404● match config.scheduler_type {
  405. 405● LRSchedulerType::Constant => config.initial_lr
  406. 406● LRSchedulerType::StepDecay => {
  407. 407● let decay_factor = (epoch / config.decay_steps).to_double()
  408. 408 let lr = config.initial_lr *
  409. 409● power_double(config.decay_rate, decay_factor.to_int())
  410. 410 if lr > config.min_lr {
  411. 411● lr
  412. 412 } else {
  413. 413● config.min_lr
  414. 414 }
  415. 415 }
  416. 416● LRSchedulerType::ExponentialDecay => {
  417. 417● let lr = config.initial_lr * power_double(config.decay_rate, epoch)
  418. 418 if lr > config.min_lr {
  419. 419● lr
  420. 420 } else {
  421. 421○ config.min_lr
  422. 422 }
  423. 423 }
  424. 424● LRSchedulerType::CosineAnnealing => {
  425. 425 let pi = 3.141592653589793
  426. 426● let cos_val = approx_cos(pi * epoch.to_double() / 50.0)
  427. 427 let lr = config.min_lr +
  428. 428 0.5 * (config.initial_lr - config.min_lr) * (1.0 + cos_val)
  429. 429 lr
  430. 430 }
  431. 431 LRSchedulerType::WarmupCosine =>
  432. 432● if epoch < config.warmup_steps {
  433. 433● config.initial_lr *
  434. 434● (epoch.to_double() + 1.0) /
  435. 435● config.warmup_steps.to_double()
  436. 436 } else {
  437. 437● let pi = 3.141592653589793
  438. 438● let progress = (epoch - config.warmup_steps).to_double() /
  439. 439● (50.0 - config.warmup_steps.to_double())
  440. 440● let cos_val = approx_cos(pi * progress)
  441. 441 config.min_lr +
  442. 442 0.5 * (config.initial_lr - config.min_lr) * (1.0 + cos_val)
  443. 443 }
  444. 444● LRSchedulerType::ReduceOnPlateau => current_lr
  445. 445 }
  446. 446}
  447. 447
  448. 448///|
  449. 449/// 数据增强:随机旋转
  450. 450pub fn augment_random_rotation(
  451. 451 sample : DLTrainingSample,
  452. 452 angle_range : Double,
  453. 453) -> DLTrainingSample {
  454. 454● ignore(angle_range)
  455. 455 // 简化版:实际应旋转图像
  456. 456 sample
  457. 457}
  458. 458
  459. 459///|
  460. 460/// 数据增强:随机平移
  461. 461pub fn augment_random_shift(
  462. 462 sample : DLTrainingSample,
  463. 463 shift_range : Double,
  464. 464) -> DLTrainingSample {
  465. 465● ignore(shift_range)
  466. 466 // 简化版:实际应平移图像
  467. 467 sample
  468. 468}
  469. 469
  470. 470///|
  471. 471/// 数据增强:随机缩放
  472. 472pub fn augment_random_scale(
  473. 473 sample : DLTrainingSample,
  474. 474 scale_range : Double,
  475. 475) -> DLTrainingSample {
  476. 476● ignore(scale_range)
  477. 477 // 简化版:实际应缩放图像
  478. 478 sample
  479. 479}
  480. 480
  481. 481///|
  482. 482/// 数据增强:随机噪声
  483. 483pub fn augment_random_noise(
  484. 484 sample : DLTrainingSample,
  485. 485 noise_level : Double,
  486. 486) -> DLTrainingSample {
  487. 487● let augmented_data : Array[Double] = []
  488. 488 for pixel in sample.image_data {
  489. 489● let noise = pixel * noise_level * (if pixel > 0.5 { 1.0 } else { -1.0 })
  490. 490 let new_pixel = if pixel + noise > 1.0 {
  491. 491● 1.0
  492. 492● } else if pixel + noise < 0.0 {
  493. 493○ 0.0
  494. 494 } else {
  495. 495● pixel + noise
  496. 496 }
  497. 497● augmented_data.push(new_pixel)
  498. 498 }
  499. 499 DLTrainingSample::{
  500. 500 image_data: augmented_data,
  501. 501 label: sample.label,
  502. 502 label_text: sample.label_text,
  503. 503 width: sample.width,
  504. 504 height: sample.height,
  505. 505 }
  506. 506}
  507. 507
  508. 508///|
  509. 509/// 应用数据增强
  510. 510pub fn apply_augmentation(
  511. 511 sample : DLTrainingSample,
  512. 512 config : AugmentationConfig,
  513. 513) -> DLTrainingSample {
  514. 514● if !config.enabled {
  515. 515● return sample
  516. 516 }
  517. 517 let mut augmented = sample
  518. 518 for aug_type in config.augmentation_types {
  519. 519 // 简化:固定应用噪声增强
  520. 520● match aug_type {
  521. 521 AugmentationType::RandomNoise =>
  522. 522● augmented = augment_random_noise(augmented, config.noise_level)
  523. 523● _ => ()
  524. 524 }
  525. 525 }
  526. 526 augmented
  527. 527}
  528. 528
  529. 529///|
  530. 530/// 计算准确率
  531. 531pub fn calculate_accuracy(
  532. 532 predictions : Array[Int32],
  533. 533 labels : Array[Int32],
  534. 534) -> Double {
  535. 535● if predictions.length() == 0 || labels.length() == 0 {
  536. 536● return 0.0
  537. 537 }
  538. 538 let mut correct = 0
  539. 539● let len = if predictions.length() < labels.length() {
  540. 540● predictions.length()
  541. 541 } else {
  542. 542● labels.length()
  543. 543 }
  544. 544 for i in 0..<len {
  545. 545● if predictions[i] == labels[i] {
  546. 546● correct += 1
  547. 547 }
  548. 548 }
  549. 549● correct.to_double() / len.to_double()
  550. 550}
  551. 551
  552. 552///|
  553. 553/// 早停检查
  554. 554pub fn check_early_stopping(
  555. 555 state : TrainingState,
  556. 556 config : TrainingConfig,
  557. 557 current_val_accuracy : Double,
  558. 558) -> (Bool, TrainingState) {
  559. 559● let improvement = current_val_accuracy - state.best_val_accuracy
  560. 560 if improvement > config.early_stopping_min_delta {
  561. 561● let new_state = TrainingState::{
  562. 562 current_epoch: state.current_epoch,
  563. 563 best_val_accuracy: current_val_accuracy,
  564. 564 best_epoch: state.current_epoch,
  565. 565 epochs_without_improvement: 0,
  566. 566 total_training_time_ms: state.total_training_time_ms,
  567. 567 history: state.history,
  568. 568 is_completed: false,
  569. 569 stop_reason: "",
  570. 570 }
  571. 571 (false, new_state)
  572. 572 } else {
  573. 573● let new_epochs_without = state.epochs_without_improvement + 1
  574. 574 let should_stop = new_epochs_without >= config.early_stopping_patience
  575. 575 let new_state = TrainingState::{
  576. 576 current_epoch: state.current_epoch,
  577. 577 best_val_accuracy: state.best_val_accuracy,
  578. 578 best_epoch: state.best_epoch,
  579. 579 epochs_without_improvement: new_epochs_without,
  580. 580 total_training_time_ms: state.total_training_time_ms,
  581. 581 history: state.history,
  582. 582 is_completed: should_stop,
  583. 583 stop_reason: if should_stop {
  584. 584● "early_stopping"
  585. 585 } else {
  586. 586● ""
  587. 587 },
  588. 588 }
  589. 589 (should_stop, new_state)
  590. 590 }
  591. 591}
  592. 592
  593. 593///|
  594. 594/// 创建训练状态
  595. 595pub fn create_training_state() -> TrainingState {
  596. 596● TrainingState::{
  597. 597 current_epoch: 0,
  598. 598 best_val_accuracy: 0.0,
  599. 599 best_epoch: 0,
  600. 600 epochs_without_improvement: 0,
  601. 601 total_training_time_ms: 0.0,
  602. 602 history: [],
  603. 603 is_completed: false,
  604. 604 stop_reason: "",
  605. 605 }
  606. 606}
  607. 607
  608. 608///|
  609. 609/// 记录训练指标
  610. 610pub fn record_training_metrics(
  611. 611 state : TrainingState,
  612. 612 metrics : TrainingMetrics,
  613. 613) -> TrainingState {
  614. 614● let new_history = state.history
  615. 615● new_history.push(metrics)
  616. 616 TrainingState::{
  617. 617 current_epoch: metrics.epoch,
  618. 618 best_val_accuracy: if metrics.val_accuracy > state.best_val_accuracy {
  619. 619● metrics.val_accuracy
  620. 620 } else {
  621. 621● state.best_val_accuracy
  622. 622 },
  623. 623 best_epoch: if metrics.val_accuracy > state.best_val_accuracy {
  624. 624● metrics.epoch
  625. 625 } else {
  626. 626● state.best_epoch
  627. 627 },
  628. 628 epochs_without_improvement: if metrics.val_accuracy >
  629. 629 state.best_val_accuracy {
  630. 630● 0
  631. 631 } else {
  632. 632● state.epochs_without_improvement + 1
  633. 633 },
  634. 634 total_training_time_ms: state.total_training_time_ms + metrics.time_ms,
  635. 635 history: new_history,
  636. 636 is_completed: state.is_completed,
  637. 637 stop_reason: state.stop_reason,
  638. 638 }
  639. 639}
  640. 640
  641. 641///|
  642. 642/// 生成训练进度报告
  643. 643pub fn generate_training_progress_report(
  644. 644 state : TrainingState,
  645. 645 config : TrainingConfig,
  646. 646) -> String {
  647. 647● let mut report = "## 训练进度报告\n\n"
  648. 648 report = report + "### 当前状态\n\n"
  649. 649 report = report + "| 指标 | 值 |\n"
  650. 650 report = report + "|------|------|\n"
  651. 651 report = report +
  652. 652 "| 当前轮次 | " +
  653. 653● state.current_epoch.to_string() +
  654. 654 " / " +
  655. 655● config.epochs.to_string() +
  656. 656 " |\n"
  657. 657 report = report +
  658. 658 "| 最佳验证准确率 | " +
  659. 659● (state.best_val_accuracy * 100.0).to_string() +
  660. 660 "% |\n"
  661. 661● report = report + "| 最佳轮次 | " + state.best_epoch.to_string() + " |\n"
  662. 662 report = report +
  663. 663 "| 无改进轮次 | " +
  664. 664● state.epochs_without_improvement.to_string() +
  665. 665 " / " +
  666. 666● config.early_stopping_patience.to_string() +
  667. 667 " |\n"
  668. 668 report = report +
  669. 669 "| 总训练时间 | " +
  670. 670● (state.total_training_time_ms / 1000.0).to_string() +
  671. 671 " 秒 |\n"
  672. 672 report = report +
  673. 673 "| 训练状态 | " +
  674. 674 (if state.is_completed {
  675. 675● "已完成 (" + state.stop_reason + ")"
  676. 676 } else {
  677. 677● "进行中"
  678. 678 }) +
  679. 679 " |\n\n"
  680. 680
  681. 681● if state.history.length() > 0 {
  682. 682● report = report + "### 最近 5 轮训练记录\n\n"
  683. 683 report = report +
  684. 684 "| Epoch | Train Loss | Train Acc | Val Loss | Val Acc | LR |\n"
  685. 685 report = report +
  686. 686 "|-------|------------|-----------|----------|---------|----|\n"
  687. 687● let start = if state.history.length() > 5 {
  688. 688● state.history.length() - 5
  689. 689 } else {
  690. 690● 0
  691. 691 }
  692. 692● for i in start..<state.history.length() {
  693. 693● let h = state.history[i]
  694. 694● report = report + "| " + h.epoch.to_string() + " | "
  695. 695● report = report + h.train_loss.to_string() + " | "
  696. 696● report = report + (h.train_accuracy * 100.0).to_string() + "% | "
  697. 697● report = report + h.val_loss.to_string() + " | "
  698. 698● report = report + (h.val_accuracy * 100.0).to_string() + "% | "
  699. 699● report = report + h.learning_rate.to_string() + " |\n"
  700. 700 }
  701. 701 }
  702. 702
  703. 703 report
  704. 704}
  705. 705
  706. 706///|
  707. 707/// 划分训练集和验证集
  708. 708pub fn split_train_validation(
  709. 709 samples : Array[DLTrainingSample],
  710. 710 validation_split : Double,
  711. 711 shuffle : Bool,
  712. 712) -> (Array[DLTrainingSample], Array[DLTrainingSample]) {
  713. 713● ignore(shuffle)
  714. 714● let total = samples.length()
  715. 715● let val_count = (total.to_double() * validation_split).to_int()
  716. 716 let train_count = total - val_count
  717. 717
  718. 718 let train_samples : Array[DLTrainingSample] = []
  719. 719 let val_samples : Array[DLTrainingSample] = []
  720. 720
  721. 721 for i in 0..<train_count {
  722. 722● train_samples.push(samples[i])
  723. 723 }
  724. 724 for i in train_count..<total {
  725. 725● val_samples.push(samples[i])
  726. 726 }
  727. 727
  728. 728 (train_samples, val_samples)
  729. 729}
  730. 730
  731. 731///|
  732. 732/// 混淆矩阵计算
  733. 733pub fn compute_confusion_matrix(
  734. 734 predictions : Array[Int32],
  735. 735 labels : Array[Int32],
  736. 736 num_classes : Int32,
  737. 737) -> Array[Array[Int32]] {
  738. 738● let matrix : Array[Array[Int32]] = []
  739. 739 for _ in 0..<num_classes {
  740. 740● let row : Array[Int32] = []
  741. 741 for _ in 0..<num_classes {
  742. 742● row.push(0)
  743. 743 }
  744. 744● matrix.push(row)
  745. 745 }
  746. 746● let len = if predictions.length() < labels.length() {
  747. 747○ predictions.length()
  748. 748 } else {
  749. 749● labels.length()
  750. 750 }
  751. 751 for i in 0..<len {
  752. 752● let true_label = labels[i]
  753. 753 let pred_label = predictions[i]
  754. 754 if true_label < num_classes && pred_label < num_classes {
  755. 755● let row = matrix[true_label]
  756. 756 row[pred_label] = row[pred_label] + 1
  757. 757 }
  758. 758 }
  759. 759 matrix
  760. 760}
  761. 761
  762. 762///|
  763. 763/// 计算每类准确率
  764. 764pub fn compute_per_class_accuracy(
  765. 765 confusion_matrix : Array[Array[Int32]],
  766. 766) -> Array[Double] {
  767. 767● let accuracies : Array[Double] = []
  768. 768● for i in 0..<confusion_matrix.length() {
  769. 769● let mut total = 0
  770. 770● for j in 0..<confusion_matrix[i].length() {
  771. 771● total += confusion_matrix[i][j]
  772. 772 }
  773. 773 let accuracy = if total > 0 {
  774. 774● confusion_matrix[i][i].to_double() / total.to_double()
  775. 775 } else {
  776. 776● 0.0
  777. 777 }
  778. 778● accuracies.push(accuracy)
  779. 779 }
  780. 780 accuracies
  781. 781}