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