image.vision\ocr\deep_learning_v13.mbt

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