image.vision\ocr\classifier.mbt

88.3% · 159 / 180 points · 535 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/classifier
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 简单分类器
  7. 7// KNN、模板匹配、距离度量、分类结果
  8. 8
  9. 9///|
  10. 10/// 分类结果结构体
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct ClassificationResult {
  13. 13 label : String
  14. 14 confidence : Double
  15. 15 top_k : Array[(String, Double)]
  16. 16}
  17. 17
  18. 18///|
  19. 19pub extend ClassificationResult with Eq::{not_equal, equal}
  20. 20
  21. 21///|
  22. 22pub extend ClassificationResult with @debug.Debug::{to_repr}
  23. 23
  24. 24///|
  25. 25/// 训练样本结构体
  26. 26#derive(Eq, @debug.Debug)
  27. 27pub(all) struct TrainingSample {
  28. 28 features : Array[Double]
  29. 29 label : String
  30. 30}
  31. 31
  32. 32///|
  33. 33pub extend TrainingSample with Eq::{not_equal, equal}
  34. 34
  35. 35///|
  36. 36pub extend TrainingSample with @debug.Debug::{to_repr}
  37. 37
  38. 38///|
  39. 39/// KNN 分类器
  40. 40#derive(Eq, @debug.Debug)
  41. 41pub(all) struct KnnClassifier {
  42. 42 samples : Array[TrainingSample]
  43. 43 k : Int32
  44. 44 distance_metric : String
  45. 45}
  46. 46
  47. 47///|
  48. 48pub extend KnnClassifier with Eq::{not_equal, equal}
  49. 49
  50. 50///|
  51. 51pub extend KnnClassifier with @debug.Debug::{to_repr}
  52. 52
  53. 53///|
  54. 54/// 模板匹配分类器
  55. 55#derive(Eq, @debug.Debug)
  56. 56pub(all) struct TemplateMatcher {
  57. 57 templates : Array[(String, Array[Double])]
  58. 58 distance_metric : String
  59. 59}
  60. 60
  61. 61///|
  62. 62pub extend TemplateMatcher with Eq::{not_equal, equal}
  63. 63
  64. 64///|
  65. 65pub extend TemplateMatcher with @debug.Debug::{to_repr}
  66. 66
  67. 67///|
  68. 68/// 距离度量类型
  69. 69/// `#non_exhaustive` 表示未来可能添加新构造器
  70. 70#derive(Eq, @debug.Debug)
  71. 71#non_exhaustive
  72. 72pub(all) enum DistanceMetric {
  73. 73 Euclidean
  74. 74 Manhattan
  75. 75 Cosine
  76. 76 Chebyshev
  77. 77}
  78. 78
  79. 79///|
  80. 80pub extend DistanceMetric with @debug.Debug::{to_repr}
  81. 81
  82. 82///|
  83. 83pub extend DistanceMetric with Eq::{not_equal, equal}
  84. 84
  85. 85///|
  86. 86/// 计算欧氏距离
  87. 87pub fn euclidean_distance(
  88. 88 a : Array[Double],
  89. 89 b : Array[Double],
  90. 90) -> Double raise @types.LoadError {
  91. 91 // 输入验证
  92. 92● if a.length() == 0 {
  93. 93● raise @types.LoadError::DecodeFailed(
  94. 94 "euclidean_distance: 向量a不能为空",
  95. 95 )
  96. 96 }
  97. 97● if b.length() == 0 {
  98. 98● raise @types.LoadError::DecodeFailed(
  99. 99 "euclidean_distance: 向量b不能为空",
  100. 100 )
  101. 101 }
  102. 102
  103. 103◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  104. 104 let mut sum_sq = 0.0
  105. 105 for i in 0..<n {
  106. 106● let diff = a[i] - b[i]
  107. 107 sum_sq += diff * diff
  108. 108 }
  109. 109● sum_sq.sqrt()
  110. 110}
  111. 111
  112. 112///|
  113. 113/// 计算曼哈顿距离
  114. 114pub fn manhattan_distance(
  115. 115 a : Array[Double],
  116. 116 b : Array[Double],
  117. 117) -> Double raise @types.LoadError {
  118. 118 // 输入验证
  119. 119● if a.length() == 0 {
  120. 120● raise @types.LoadError::DecodeFailed(
  121. 121 "manhattan_distance: 向量a不能为空",
  122. 122 )
  123. 123 }
  124. 124● if b.length() == 0 {
  125. 125● raise @types.LoadError::DecodeFailed(
  126. 126 "manhattan_distance: 向量b不能为空",
  127. 127 )
  128. 128 }
  129. 129
  130. 130◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  131. 131 let mut sum = 0.0
  132. 132 for i in 0..<n {
  133. 133● sum += (a[i] - b[i]).abs()
  134. 134 }
  135. 135 sum
  136. 136}
  137. 137
  138. 138///|
  139. 139/// 计算余弦相似度(返回距离 = 1 - 相似度)
  140. 140pub fn cosine_distance(
  141. 141 a : Array[Double],
  142. 142 b : Array[Double],
  143. 143) -> Double raise @types.LoadError {
  144. 144 // 输入验证
  145. 145● if a.length() == 0 {
  146. 146● raise @types.LoadError::DecodeFailed("cosine_distance: 向量a不能为空")
  147. 147 }
  148. 148● if b.length() == 0 {
  149. 149● raise @types.LoadError::DecodeFailed("cosine_distance: 向量b不能为空")
  150. 150 }
  151. 151
  152. 152◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  153. 153 let mut dot = 0.0
  154. 154 let mut norm_a = 0.0
  155. 155 let mut norm_b = 0.0
  156. 156 for i in 0..<n {
  157. 157● dot += a[i] * b[i]
  158. 158 norm_a += a[i] * a[i]
  159. 159 norm_b += b[i] * b[i]
  160. 160 }
  161. 161● let denom = norm_a.sqrt() * norm_b.sqrt()
  162. 162 if denom > 0.0 {
  163. 163● 1.0 - dot / denom
  164. 164 } else {
  165. 165● 1.0
  166. 166 }
  167. 167}
  168. 168
  169. 169///|
  170. 170/// 计算切比雪夫距离
  171. 171pub fn chebyshev_distance(
  172. 172 a : Array[Double],
  173. 173 b : Array[Double],
  174. 174) -> Double raise @types.LoadError {
  175. 175 // 输入验证
  176. 176● if a.length() == 0 {
  177. 177● raise @types.LoadError::DecodeFailed(
  178. 178 "chebyshev_distance: 向量a不能为空",
  179. 179 )
  180. 180 }
  181. 181● if b.length() == 0 {
  182. 182● raise @types.LoadError::DecodeFailed(
  183. 183 "chebyshev_distance: 向量b不能为空",
  184. 184 )
  185. 185 }
  186. 186
  187. 187◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  188. 188 let mut max_diff = 0.0
  189. 189 for i in 0..<n {
  190. 190● let diff = (a[i] - b[i]).abs()
  191. 191 if diff > max_diff {
  192. 192● max_diff = diff
  193. 193 }
  194. 194 }
  195. 195 max_diff
  196. 196}
  197. 197
  198. 198///|
  199. 199/// 计算距离(根据度量类型)
  200. 200pub fn compute_distance(
  201. 201 a : Array[Double],
  202. 202 b : Array[Double],
  203. 203 metric : DistanceMetric,
  204. 204) -> Double raise @types.LoadError {
  205. 205 // 输入验证
  206. 206● if a.length() == 0 {
  207. 207● raise @types.LoadError::DecodeFailed(
  208. 208 "compute_distance: 向量a不能为空",
  209. 209 )
  210. 210 }
  211. 211● if b.length() == 0 {
  212. 212● raise @types.LoadError::DecodeFailed(
  213. 213 "compute_distance: 向量b不能为空",
  214. 214 )
  215. 215 }
  216. 216
  217. 217● match metric {
  218. 218● DistanceMetric::Euclidean => euclidean_distance(a, b)
  219. 219● DistanceMetric::Manhattan => manhattan_distance(a, b)
  220. 220● DistanceMetric::Cosine => cosine_distance(a, b)
  221. 221● DistanceMetric::Chebyshev => chebyshev_distance(a, b)
  222. 222 }
  223. 223}
  224. 224
  225. 225///|
  226. 226/// 创建 KNN 分类器
  227. 227pub fn knn_create(
  228. 228 k~ : Int32 = 3,
  229. 229 distance_metric~ : String = "euclidean",
  230. 230) -> KnnClassifier raise @types.LoadError {
  231. 231 // 输入验证
  232. 232● if k <= 0 {
  233. 233● raise @types.LoadError::DecodeFailed("knn_create: k必须大于0")
  234. 234 }
  235. 235
  236. 236 KnnClassifier::{ samples: [], k, distance_metric, }
  237. 237}
  238. 238
  239. 239///|
  240. 240/// 添加训练样本
  241. 241pub fn knn_add_sample(
  242. 242 classifier : KnnClassifier,
  243. 243 features : Array[Double],
  244. 244 label : String,
  245. 245) -> KnnClassifier raise @types.LoadError {
  246. 246 // 输入验证
  247. 247● if features.length() == 0 {
  248. 248● raise @types.LoadError::DecodeFailed(
  249. 249 "knn_add_sample: 特征向量不能为空",
  250. 250 )
  251. 251 }
  252. 252● if label.length() == 0 {
  253. 253○ raise @types.LoadError::DecodeFailed("knn_add_sample: 标签不能为空")
  254. 254 }
  255. 255
  256. 256 let new_samples = classifier.samples
  257. 257● new_samples.push(TrainingSample::{ features, label, })
  258. 258 KnnClassifier::{
  259. 259 samples: new_samples,
  260. 260 k: classifier.k,
  261. 261 distance_metric: classifier.distance_metric,
  262. 262 }
  263. 263}
  264. 264
  265. 265///|
  266. 266/// 批量添加训练样本
  267. 267pub fn knn_add_samples(
  268. 268 classifier : KnnClassifier,
  269. 269 samples : Array[(Array[Double], String)],
  270. 270) -> KnnClassifier raise @types.LoadError {
  271. 271 // 输入验证
  272. 272● if samples.length() == 0 {
  273. 273○ raise @types.LoadError::DecodeFailed(
  274. 274 "knn_add_samples: 样本列表不能为空",
  275. 275 )
  276. 276 }
  277. 277
  278. 278 let new_samples = classifier.samples
  279. 279 for _tup0 in samples {
  280. 280● let (features, label) = _tup0
  281. 281● new_samples.push(TrainingSample::{ features, label, })
  282. 282 }
  283. 283 KnnClassifier::{
  284. 284 samples: new_samples,
  285. 285 k: classifier.k,
  286. 286 distance_metric: classifier.distance_metric,
  287. 287 }
  288. 288}
  289. 289
  290. 290///|
  291. 291/// KNN 预测
  292. 292pub fn knn_predict(
  293. 293 classifier : KnnClassifier,
  294. 294 features : Array[Double],
  295. 295) -> ClassificationResult raise @types.LoadError {
  296. 296 // 输入验证
  297. 297● if features.length() == 0 {
  298. 298● raise @types.LoadError::DecodeFailed(
  299. 299 "knn_predict: 特征向量不能为空",
  300. 300 )
  301. 301 }
  302. 302● if classifier.samples.length() == 0 {
  303. 303● raise @types.LoadError::DecodeFailed(
  304. 304 "knn_predict: 分类器没有训练样本",
  305. 305 )
  306. 306 }
  307. 307
  308. 308● let metric = match classifier.distance_metric {
  309. 309○ "manhattan" => DistanceMetric::Manhattan
  310. 310○ "cosine" => DistanceMetric::Cosine
  311. 311○ "chebyshev" => DistanceMetric::Chebyshev
  312. 312● _ => DistanceMetric::Euclidean
  313. 313 }
  314. 314 // 计算所有样本的距离
  315. 315 let distances : Array[(Double, String)] = []
  316. 316 for sample in classifier.samples {
  317. 317● let dist = compute_distance(features, sample.features, metric)
  318. 318● distances.push((dist, sample.label))
  319. 319 }
  320. 320 // 按距离排序(冒泡排序,简单实现)
  321. 321● for _ in 0..<distances.length() {
  322. 322● for j in 0..<(distances.length() - 1) {
  323. 323● if distances[j].0 > distances[j + 1].0 {
  324. 324● let temp = distances[j]
  325. 325 distances[j] = distances[j + 1]
  326. 326 distances[j + 1] = temp
  327. 327 }
  328. 328 }
  329. 329 }
  330. 330 // 取前 k 个最近邻
  331. 331● let k = if classifier.k < distances.length() {
  332. 332● classifier.k
  333. 333 } else {
  334. 334● distances.length()
  335. 335 }
  336. 336 let top_k : Array[(String, Double)] = []
  337. 337 let label_votes : Array[(String, Int32)] = []
  338. 338 for i in 0..<k {
  339. 339● let (dist, label) = distances[i]
  340. 340● let confidence = if dist > 0.0 { 1.0 / (1.0 + dist) } else { 1.0 }
  341. 341● top_k.push((label, confidence))
  342. 342 // 投票
  343. 343 let mut found = false
  344. 344● for j in 0..<label_votes.length() {
  345. 345● if label_votes[j].0 == label {
  346. 346● label_votes[j] = (label, label_votes[j].1 + 1)
  347. 347 found = true
  348. 348 }
  349. 349 }
  350. 350 if !found {
  351. 351● label_votes.push((label, 1))
  352. 352 }
  353. 353 }
  354. 354 // 找得票最多的标签
  355. 355 let mut best_label = ""
  356. 356 let mut best_votes = 0
  357. 357 for _tup1 in label_votes {
  358. 358● let (label, votes) = _tup1
  359. 359 if votes > best_votes {
  360. 360● best_votes = votes
  361. 361 best_label = label
  362. 362 }
  363. 363 }
  364. 364 let confidence = if k > 0 {
  365. 365● best_votes.to_double() / k.to_double()
  366. 366 } else {
  367. 367○ 0.0
  368. 368 }
  369. 369 ClassificationResult::{ label: best_label, confidence, top_k, }
  370. 370}
  371. 371
  372. 372///|
  373. 373/// 创建模板匹配分类器
  374. 374pub fn template_matcher_create(
  375. 375 distance_metric~ : String = "euclidean",
  376. 376) -> TemplateMatcher {
  377. 377 // 输入验证:distance_metric 不做强制验证,使用默认值兜底
  378. 378● TemplateMatcher::{ templates: [], distance_metric, }
  379. 379}
  380. 380
  381. 381///|
  382. 382/// 添加模板
  383. 383pub fn template_matcher_add(
  384. 384 matcher : TemplateMatcher,
  385. 385 label : String,
  386. 386 template : Array[Double],
  387. 387) -> TemplateMatcher raise @types.LoadError {
  388. 388 // 输入验证
  389. 389● if template.length() == 0 {
  390. 390● raise @types.LoadError::DecodeFailed(
  391. 391 "template_matcher_add: 模板特征向量不能为空",
  392. 392 )
  393. 393 }
  394. 394● if label.length() == 0 {
  395. 395○ raise @types.LoadError::DecodeFailed(
  396. 396 "template_matcher_add: 标签不能为空",
  397. 397 )
  398. 398 }
  399. 399
  400. 400 let new_templates = matcher.templates
  401. 401● new_templates.push((label, template))
  402. 402 TemplateMatcher::{
  403. 403 templates: new_templates,
  404. 404 distance_metric: matcher.distance_metric,
  405. 405 }
  406. 406}
  407. 407
  408. 408///|
  409. 409/// 模板匹配预测
  410. 410pub fn template_matcher_predict(
  411. 411 matcher : TemplateMatcher,
  412. 412 features : Array[Double],
  413. 413) -> ClassificationResult raise @types.LoadError {
  414. 414 // 输入验证
  415. 415● if features.length() == 0 {
  416. 416● raise @types.LoadError::DecodeFailed(
  417. 417 "template_matcher_predict: 特征向量不能为空",
  418. 418 )
  419. 419 }
  420. 420● if matcher.templates.length() == 0 {
  421. 421● raise @types.LoadError::DecodeFailed(
  422. 422 "template_matcher_predict: 模板匹配器没有模板",
  423. 423 )
  424. 424 }
  425. 425
  426. 426● let metric = match matcher.distance_metric {
  427. 427○ "manhattan" => DistanceMetric::Manhattan
  428. 428○ "cosine" => DistanceMetric::Cosine
  429. 429● "chebyshev" => DistanceMetric::Chebyshev
  430. 430● _ => DistanceMetric::Euclidean
  431. 431 }
  432. 432 // 计算与所有模板的距离
  433. 433 let distances : Array[(Double, String)] = []
  434. 434 for _tup2 in matcher.templates {
  435. 435● let (label, template) = _tup2
  436. 436● let dist = compute_distance(features, template, metric)
  437. 437● distances.push((dist, label))
  438. 438 }
  439. 439 // 按距离排序
  440. 440● for _ in 0..<distances.length() {
  441. 441● for j in 0..<(distances.length() - 1) {
  442. 442● if distances[j].0 > distances[j + 1].0 {
  443. 443● let temp = distances[j]
  444. 444 distances[j] = distances[j + 1]
  445. 445 distances[j + 1] = temp
  446. 446 }
  447. 447 }
  448. 448 }
  449. 449 // 返回最佳匹配
  450. 450 let top_k : Array[(String, Double)] = []
  451. 451◐ let n = if 5 < distances.length() { 5 } else { distances.length() }
  452. 452 for i in 0..<n {
  453. 453● let (dist, label) = distances[i]
  454. 454● let confidence = if dist > 0.0 { 1.0 / (1.0 + dist) } else { 1.0 }
  455. 455● top_k.push((label, confidence))
  456. 456 }
  457. 457● if distances.length() > 0 {
  458. 458● let (best_dist, best_label) = distances[0]
  459. 459● let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 }
  460. 460 ClassificationResult::{ label: best_label, confidence, top_k, }
  461. 461 } else {
  462. 462○ ClassificationResult::{ label: "", confidence: 0.0, top_k: [], }
  463. 463 }
  464. 464}
  465. 465
  466. 466///|
  467. 467/// 特征归一化(Min-Max 归一化到 [0, 1])
  468. 468pub fn normalize_features(
  469. 469 features : Array[Double],
  470. 470) -> Array[Double] raise @types.LoadError {
  471. 471 // 输入验证
  472. 472● if features.length() == 0 {
  473. 473● raise @types.LoadError::DecodeFailed(
  474. 474 "normalize_features: 特征向量不能为空",
  475. 475 )
  476. 476 }
  477. 477 let mut min_val = features[0]
  478. 478 let mut max_val = features[0]
  479. 479 for v in features {
  480. 480● if v < min_val {
  481. 481○ min_val = v
  482. 482 }
  483. 483 if v > max_val {
  484. 484● max_val = v
  485. 485 }
  486. 486 }
  487. 487 let range = max_val - min_val
  488. 488 let normalized : Array[Double] = []
  489. 489 if range > 0.0 {
  490. 490● for v in features {
  491. 491● normalized.push((v - min_val) / range)
  492. 492 }
  493. 493 } else {
  494. 494● for _ in features {
  495. 495● normalized.push(0.0)
  496. 496 }
  497. 497 }
  498. 498 normalized
  499. 499}
  500. 500
  501. 501///|
  502. 502/// 特征标准化(Z-score 标准化,均值0,标准差1)
  503. 503pub fn standardize_features(
  504. 504 features : Array[Double],
  505. 505) -> Array[Double] raise @types.LoadError {
  506. 506 // 输入验证
  507. 507● if features.length() == 0 {
  508. 508● raise @types.LoadError::DecodeFailed(
  509. 509 "standardize_features: 特征向量不能为空",
  510. 510 )
  511. 511 }
  512. 512 // 计算均值
  513. 513 let mut sum = 0.0
  514. 514 for v in features {
  515. 515● sum += v
  516. 516 }
  517. 517● let mean = sum / features.length().to_double()
  518. 518 // 计算标准差
  519. 519 let mut sum_sq = 0.0
  520. 520 for v in features {
  521. 521● let diff = v - mean
  522. 522 sum_sq += diff * diff
  523. 523 }
  524. 524 let std = if sum_sq > 0.0 {
  525. 525● (sum_sq / features.length().to_double()).sqrt()
  526. 526 } else {
  527. 527○ 1.0
  528. 528 }
  529. 529 // 标准化
  530. 530 let standardized : Array[Double] = []
  531. 531 for v in features {
  532. 532● standardized.push((v - mean) / std)
  533. 533 }
  534. 534 standardized
  535. 535}