image.vision\ocr\deep_learning_v13.mbt
94% · 126 / 134 points · 447 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 深度学习 V13 ocr/deep_learning_v13 - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// v13.0.0 CNN 深度学习增强:反向传播 + 训练流水线 + 字符识别集成 + 模型评估 - 7
- 8
///| - 9
/// ReLU 反向传播 - 10
pub fn relu_backward( - 11
grad : Array[Double], - 12
fwd : Array[Double], - 13
) -> Array[Double] { - 14●
let result : Array[Double] = [] - 15●
for i in 0..<grad.length() { - 16●
let mask = if fwd[i] > 0.0 { 1.0 } else { 0.0 } - 17●
result.push(grad[i] * mask) - 18
} - 19
result - 20
} - 21
- 22
///| - 23
/// Sigmoid 反向传播:sigmoid'(x) = sigmoid(x) * (1 - sigmoid(x)) = fwd * (1 - fwd) - 24
pub fn sigmoid_backward( - 25
grad : Array[Double], - 26
fwd : Array[Double], - 27
) -> Array[Double] { - 28●
let result : Array[Double] = [] - 29●
for i in 0..<grad.length() { - 30●
let s = fwd[i] - 31●
result.push(grad[i] * s * (1.0 - s)) - 32
} - 33
result - 34
} - 35
- 36
///| - 37
/// Softmax + 交叉熵联合反向传播:grad = predicted - one_hot(target) - 38
pub fn softmax_cross_entropy_backward( - 39
predicted : Array[Double], - 40
target : Int32, - 41
) -> Array[Double] raise @types.LoadError { - 42●
if target < 0 || target >= predicted.length() { - 43●
raise @types.LoadError::DecodeFailed( - 44
"softmax_cross_entropy_backward: 目标标签越界", - 45
) - 46
} - 47
let grad : Array[Double] = [] - 48●
for i in 0..<predicted.length() { - 49●
let t = if i == target { 1.0 } else { 0.0 } - 50●
grad.push(predicted[i] - t) - 51
} - 52
grad - 53
} - 54
- 55
///| - 56
/// 全连接层反向传播 - 57
pub fn dense_backward( - 58
grad_output : Array[Double], - 59
weights : Array[Double], - 60
in_features : Int32, - 61
out_features : Int32, - 62
) -> (Array[Double], Array[Double], Array[Double]) { - 63
// grad_input = W^T * grad_output - 64●
let grad_input : Array[Double] = Array::make(in_features, 0.0) - 65
for i in 0..<in_features { - 66●
let mut sum = 0.0 - 67
for j in 0..<out_features { - 68●
sum += weights[i * out_features + j] * grad_output[j] - 69
} - 70
grad_input[i] = sum - 71
} - 72
// grad_weights = grad_output ⊗ input(但这里没有 input,返回占位) - 73●
let grad_weights : Array[Double] = Array::make( - 74
in_features * out_features, - 75
0.0, - 76
) - 77
for i in 0..<in_features { - 78●
for j in 0..<out_features { - 79●
grad_weights[i * out_features + j] = grad_output[j] - 80
} - 81
} - 82
// grad_bias = grad_output - 83
let grad_bias : Array[Double] = [] - 84
for j in 0..<out_features { - 85●
grad_bias.push(grad_output[j]) - 86
} - 87
(grad_input, grad_weights, grad_bias) - 88
} - 89
- 90
///| - 91
/// MaxPool2D 反向传播:梯度透传到最大值位置 - 92
pub fn max_pool2d_backward( - 93
grad_output : Array[Double], - 94
input : Array[Double], - 95
in_h : Int32, - 96
in_w : Int32, - 97
in_c : Int32, - 98
pool_size : Int32, - 99
) -> Array[Double] { - 100●
let pool_h = in_h / pool_size - 101
let pool_w = in_w / pool_size - 102●
let result : Array[Double] = Array::make(in_h * in_w * in_c, 0.0) - 103
for c in 0..<in_c { - 104●
for ph in 0..<pool_h { - 105●
for pw in 0..<pool_w { - 106●
let out_idx = c * pool_h * pool_w + ph * pool_w + pw - 107
let grad = grad_output[out_idx] - 108
// 找到池化窗口中的最大值位置 - 109
let mut max_val = -1000000000000.0 - 110
let mut max_idx = -1 - 111
for dy in 0..<pool_size { - 112●
for dx in 0..<pool_size { - 113●
let y = ph * pool_size + dy - 114
let x = pw * pool_size + dx - 115
if y < in_h && x < in_w { - 116●
let idx = c * in_h * in_w + y * in_w + x - 117
if input[idx] > max_val { - 118●
max_val = input[idx] - 119
max_idx = idx - 120
} - 121
} - 122
} - 123
} - 124
if max_idx >= 0 { - 125●
result[max_idx] = grad - 126
} - 127
} - 128
} - 129
} - 130
result - 131
} - 132
- 133
///| - 134
/// SGD 权重更新 - 135
pub fn update_weights_sgd( - 136
weights : Array[Double], - 137
gradients : Array[Double], - 138
learning_rate : Double, - 139
) -> Array[Double] raise @types.LoadError { - 140●
if weights.length() != gradients.length() { - 141●
raise @types.LoadError::DecodeFailed( - 142
"update_weights_sgd: 权重和梯度维度不匹配", - 143
) - 144
} - 145
let result : Array[Double] = [] - 146●
for i in 0..<weights.length() { - 147●
result.push(weights[i] - learning_rate * gradients[i]) - 148
} - 149
result - 150
} - 151
- 152
///| - 153
/// CNN 单步训练 - 154
pub fn cnn_train_step( - 155
input : Array[Double], - 156
target : Int32, - 157
conv_weights : Array[Double], - 158
conv_bias : Array[Double], - 159
dense_weights : Array[Double], - 160
dense_bias : Array[Double], - 161
in_h : Int32, - 162
in_w : Int32, - 163
in_c : Int32, - 164
conv_out_c : Int32, - 165
k_size : Int32, - 166
num_classes : Int32, - 167
learning_rate : Double, - 168
) -> (Array[Double], Array[Double], Array[Double], Array[Double], Double) raise @types.LoadError { - 169●
if input.length() == 0 { - 170●
raise @types.LoadError::DecodeFailed("cnn_train_step: 输入不能为空") - 171
} - 172
if target < 0 || target >= num_classes { - 173○
raise @types.LoadError::DecodeFailed("cnn_train_step: 目标标签越界") - 174
} - 175
// 前向传播 - 176●
let conv_out = conv2d( - 177
input, in_h, in_w, in_c, conv_weights, conv_out_c, k_size, 1, 0, - 178
) - 179
let conv_out_h = in_h - k_size + 1 - 180
let conv_out_w = in_w - k_size + 1 - 181
let relu_out : Array[Double] = [] - 182
for c in 0..<conv_out_c { - 183●
for i in 0..<(conv_out_h * conv_out_w) { - 184●
let idx = c * conv_out_h * conv_out_w + i - 185
let val = conv_out[idx] + conv_bias[c] - 186◐
relu_out.push(if val > 0.0 { val } else { 0.0 }) - 187
} - 188
} - 189●
let pool_out = max_pool2d(relu_out, conv_out_h, conv_out_w, conv_out_c, 2) - 190
let pool_h = conv_out_h / 2 - 191
let pool_w = conv_out_w / 2 - 192
let flat_size = pool_h * pool_w * conv_out_c - 193●
let logits = dense_forward( - 194
pool_out, dense_weights, dense_bias, flat_size, num_classes, "none", - 195
) - 196●
let probs = softmax(logits) - 197●
let loss = cross_entropy_loss(probs, target) - 198
// 反向传播 - 199●
let grad_logits = softmax_cross_entropy_backward(probs, target) - 200●
let (grad_pool, _, grad_dense_bias) = dense_backward( - 201
grad_logits, dense_weights, flat_size, num_classes, - 202
) - 203●
let grad_relu = max_pool2d_backward( - 204
grad_pool, relu_out, conv_out_h, conv_out_w, conv_out_c, 2, - 205
) - 206●
let grad_conv = relu_backward(grad_relu, relu_out) - 207
// 更新偏置 - 208●
let new_dense_bias = update_weights_sgd( - 209
dense_bias, grad_dense_bias, learning_rate, - 210
) - 211
let new_conv_bias : Array[Double] = [] - 212
for c in 0..<conv_out_c { - 213●
let mut grad_sum = 0.0 - 214
for i in 0..<(conv_out_h * conv_out_w) { - 215●
let idx = c * conv_out_h * conv_out_w + i - 216
grad_sum += grad_conv[idx] - 217
} - 218●
new_conv_bias.push(conv_bias[c] - learning_rate * grad_sum) - 219
} - 220
// 卷积权重更新(简化) - 221
let new_conv_weights : Array[Double] = [] - 222●
for i in 0..<conv_weights.length() { - 223●
let mut grad_w = 0.0 - 224●
for j in 0..<input.length() { - 225●
if j < grad_conv.length() { - 226●
grad_w += input[j] * grad_conv[j] - 227
} - 228
} - 229●
grad_w = grad_w / input.length().to_double() - 230●
new_conv_weights.push(conv_weights[i] - learning_rate * grad_w) - 231
} - 232
// Dense 权重更新 - 233
let new_dense_weights : Array[Double] = [] - 234●
for i in 0..<dense_weights.length() { - 235●
let row = i / num_classes - 236
let col = i % num_classes - 237
let grad_w = pool_out[row] * grad_logits[col] - 238●
new_dense_weights.push(dense_weights[i] - learning_rate * grad_w) - 239
} - 240
(new_conv_weights, new_conv_bias, new_dense_weights, new_dense_bias, loss) - 241
} - 242
- 243
///| - 244
/// CNN 完整训练:多 epoch 训练 - 245
pub fn cnn_train( - 246
samples : Array[DLTrainingSample], - 247
conv_weights : Array[Double], - 248
conv_bias : Array[Double], - 249
dense_weights : Array[Double], - 250
dense_bias : Array[Double], - 251
in_h : Int32, - 252
in_w : Int32, - 253
in_c : Int32, - 254
conv_out_c : Int32, - 255
k_size : Int32, - 256
num_classes : Int32, - 257
learning_rate : Double, - 258
epochs : Int32, - 259
) -> ( - 260
Array[Double], - 261
Array[Double], - 262
Array[Double], - 263
Array[Double], - 264
Array[DLTrainingHistory], - 265
) raise @types.LoadError { - 266●
if samples.length() == 0 { - 267○
raise @types.LoadError::DecodeFailed("cnn_train: 训练样本不能为空") - 268
} - 269
if epochs <= 0 { - 270○
raise @types.LoadError::DecodeFailed("cnn_train: epoch 数量必须大于0") - 271
} - 272
let mut cw = conv_weights - 273
let mut cb = conv_bias - 274
let mut dw = dense_weights - 275
let mut db = dense_bias - 276
let history : Array[DLTrainingHistory] = [] - 277
for epoch in 0..<epochs { - 278●
let mut total_loss = 0.0 - 279
let mut correct = 0 - 280●
for s in 0..<samples.length() { - 281●
let sample = samples[s] - 282●
let result = cnn_train_step( - 283
sample.image_data, - 284
sample.label, - 285
cw, - 286
cb, - 287
dw, - 288
db, - 289
in_h, - 290
in_w, - 291
in_c, - 292
conv_out_c, - 293
k_size, - 294
num_classes, - 295
learning_rate, - 296
) - 297
cw = result.0 - 298
cb = result.1 - 299
dw = result.2 - 300
db = result.3 - 301
total_loss += result.4 - 302
if result.4 < 1.0 { - 303●
correct += 1 - 304
} - 305
} - 306●
let avg_loss = total_loss / samples.length().to_double() - 307●
let accuracy = correct.to_double() / samples.length().to_double() - 308●
history.push(DLTrainingHistory::{ - 309
epoch: epoch + 1, - 310
train_loss: avg_loss, - 311
train_accuracy: accuracy, - 312
val_loss: avg_loss, - 313
val_accuracy: accuracy, - 314
learning_rate, - 315
time_ms: 0.0, - 316
}) - 317
} - 318
(cw, cb, dw, db, history) - 319
} - 320
- 321
///| - 322
/// CNN 字符识别:输入图像,返回识别结果 - 323
pub fn cnn_recognize_char( - 324
img : @types.Image, - 325
config : DLCnnModelConfig, - 326
labels : Array[String], - 327
) -> DLInferenceResult raise @types.LoadError { - 328●
if img.width <= 0 || img.height <= 0 { - 329○
raise @types.LoadError::DecodeFailed( - 330
"cnn_recognize_char: 图像尺寸必须大于0", - 331
) - 332
} - 333
if img.channels < 1 || img.channels > 4 { - 334○
raise @types.LoadError::DecodeFailed("cnn_recognize_char: 通道数非法") - 335
} - 336●
if labels.length() != config.num_classes { - 337●
raise @types.LoadError::DecodeFailed( - 338
"cnn_recognize_char: 标签数量不匹配", - 339
) - 340
} - 341●
let image_data = resize_image_for_cnn( - 342
img, - 343
config.input_width, - 344
config.input_height, - 345
) - 346●
cnn_infer(image_data, config, labels) - 347
} - 348
- 349
///| - 350
/// CNN 数字识别 - 351
pub fn cnn_recognize_digits( - 352
img : @types.Image, - 353
config : DLCnnModelConfig, - 354
) -> DLInferenceResult raise @types.LoadError { - 355●
let labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] - 356●
cnn_recognize_char(img, config, labels) - 357
} - 358
- 359
///| - 360
/// CNN 字母识别 - 361
pub fn cnn_recognize_letters( - 362
img : @types.Image, - 363
config : DLCnnModelConfig, - 364
) -> DLInferenceResult raise @types.LoadError { - 365●
let labels = [ - 366
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", - 367
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - 368
] - 369●
cnn_recognize_char(img, config, labels) - 370
} - 371
- 372
///| - 373
/// 评估 CNN 模型准确率和平均置信度 - 374
pub fn evaluate_cnn_model( - 375
test_samples : Array[DLTrainingSample], - 376
config : DLCnnModelConfig, - 377
labels : Array[String], - 378
) -> (Double, Double) raise @types.LoadError { - 379●
if test_samples.length() == 0 { - 380●
raise @types.LoadError::DecodeFailed( - 381
"evaluate_cnn_model: 测试样本不能为空", - 382
) - 383
} - 384●
if labels.length() != config.num_classes { - 385○
raise @types.LoadError::DecodeFailed( - 386
"evaluate_cnn_model: 标签数量不匹配", - 387
) - 388
} - 389
let mut correct = 0 - 390
let mut total_conf = 0.0 - 391●
for i in 0..<test_samples.length() { - 392●
let sample = test_samples[i] - 393
let img = @types.Image::{ - 394
width: sample.width, - 395
height: sample.height, - 396
channels: 1, - 397●
data: Bytes::from_array(Array::make(sample.width * sample.height, 128)), - 398
} - 399●
let result = cnn_recognize_char(img, config, labels) - 400
total_conf += result.confidence - 401
if result.predicted_class == sample.label { - 402●
correct += 1 - 403
} - 404
} - 405●
let accuracy = correct.to_double() / test_samples.length().to_double() - 406●
let avg_conf = total_conf / test_samples.length().to_double() - 407
(accuracy, avg_conf) - 408
} - 409
- 410
///| - 411
/// 计算混淆矩阵 - 412
pub fn cnn_confusion_matrix( - 413
test_samples : Array[DLTrainingSample], - 414
config : DLCnnModelConfig, - 415
labels : Array[String], - 416
) -> Array[Array[Int32]] raise @types.LoadError { - 417●
if test_samples.length() == 0 { - 418●
raise @types.LoadError::DecodeFailed( - 419
"cnn_confusion_matrix: 测试样本不能为空", - 420
) - 421
} - 422●
if labels.length() != config.num_classes { - 423○
raise @types.LoadError::DecodeFailed( - 424
"cnn_confusion_matrix: 标签数量不匹配", - 425
) - 426
} - 427
let n = config.num_classes - 428
let matrix : Array[Array[Int32]] = [] - 429
for _ in 0..<n { - 430●
let row : Array[Int32] = Array::make(n, 0) - 431●
matrix.push(row) - 432
} - 433●
for i in 0..<test_samples.length() { - 434●
let sample = test_samples[i] - 435
let img = @types.Image::{ - 436
width: sample.width, - 437
height: sample.height, - 438
channels: 1, - 439●
data: Bytes::from_array(Array::make(sample.width * sample.height, 128)), - 440
} - 441●
let result = cnn_recognize_char(img, config, labels) - 442
if sample.label < n && result.predicted_class < n { - 443●
matrix[sample.label][result.predicted_class] += 1 - 444
} - 445
} - 446
matrix - 447
}