///|
/// # 深度学习 V13 ocr/deep_learning_v13
///
/// 图像处理库子模块
/// 图像处理库子模块 Image processing library submodule
// v13.0.0 CNN 深度学习增强:反向传播 + 训练流水线 + 字符识别集成 + 模型评估
///|
/// ReLU 反向传播
pub fn relu_backward(
grad : Array[Double],
fwd : Array[Double],
) -> Array[Double] {
let result : Array[Double] = []
for i in 0.. 0.0 { 1.0 } else { 0.0 }
result.push(grad[i] * mask)
}
result
}
///|
/// Sigmoid 反向传播:sigmoid'(x) = sigmoid(x) * (1 - sigmoid(x)) = fwd * (1 - fwd)
pub fn sigmoid_backward(
grad : Array[Double],
fwd : Array[Double],
) -> Array[Double] {
let result : Array[Double] = []
for i in 0.. Array[Double] raise @types.LoadError {
if target < 0 || target >= predicted.length() {
raise @types.LoadError::DecodeFailed(
"softmax_cross_entropy_backward: 目标标签越界",
)
}
let grad : Array[Double] = []
for i in 0.. (Array[Double], Array[Double], Array[Double]) {
// grad_input = W^T * grad_output
let grad_input : Array[Double] = Array::make(in_features, 0.0)
for i in 0.. Array[Double] {
let pool_h = in_h / pool_size
let pool_w = in_w / pool_size
let result : Array[Double] = Array::make(in_h * in_w * in_c, 0.0)
for c in 0.. max_val {
max_val = input[idx]
max_idx = idx
}
}
}
}
if max_idx >= 0 {
result[max_idx] = grad
}
}
}
}
result
}
///|
/// SGD 权重更新
pub fn update_weights_sgd(
weights : Array[Double],
gradients : Array[Double],
learning_rate : Double,
) -> Array[Double] raise @types.LoadError {
if weights.length() != gradients.length() {
raise @types.LoadError::DecodeFailed(
"update_weights_sgd: 权重和梯度维度不匹配",
)
}
let result : Array[Double] = []
for i in 0.. (Array[Double], Array[Double], Array[Double], Array[Double], Double) raise @types.LoadError {
if input.length() == 0 {
raise @types.LoadError::DecodeFailed("cnn_train_step: 输入不能为空")
}
if target < 0 || target >= num_classes {
raise @types.LoadError::DecodeFailed("cnn_train_step: 目标标签越界")
}
// 前向传播
let conv_out = conv2d(
input, in_h, in_w, in_c, conv_weights, conv_out_c, k_size, 1, 0,
)
let conv_out_h = in_h - k_size + 1
let conv_out_w = in_w - k_size + 1
let relu_out : Array[Double] = []
for c in 0.. 0.0 { val } else { 0.0 })
}
}
let pool_out = max_pool2d(relu_out, conv_out_h, conv_out_w, conv_out_c, 2)
let pool_h = conv_out_h / 2
let pool_w = conv_out_w / 2
let flat_size = pool_h * pool_w * conv_out_c
let logits = dense_forward(
pool_out, dense_weights, dense_bias, flat_size, num_classes, "none",
)
let probs = softmax(logits)
let loss = cross_entropy_loss(probs, target)
// 反向传播
let grad_logits = softmax_cross_entropy_backward(probs, target)
let (grad_pool, _, grad_dense_bias) = dense_backward(
grad_logits, dense_weights, flat_size, num_classes,
)
let grad_relu = max_pool2d_backward(
grad_pool, relu_out, conv_out_h, conv_out_w, conv_out_c, 2,
)
let grad_conv = relu_backward(grad_relu, relu_out)
// 更新偏置
let new_dense_bias = update_weights_sgd(
dense_bias, grad_dense_bias, learning_rate,
)
let new_conv_bias : Array[Double] = []
for c in 0.. (
Array[Double],
Array[Double],
Array[Double],
Array[Double],
Array[DLTrainingHistory],
) raise @types.LoadError {
if samples.length() == 0 {
raise @types.LoadError::DecodeFailed("cnn_train: 训练样本不能为空")
}
if epochs <= 0 {
raise @types.LoadError::DecodeFailed("cnn_train: epoch 数量必须大于0")
}
let mut cw = conv_weights
let mut cb = conv_bias
let mut dw = dense_weights
let mut db = dense_bias
let history : Array[DLTrainingHistory] = []
for epoch in 0.. DLInferenceResult raise @types.LoadError {
if img.width <= 0 || img.height <= 0 {
raise @types.LoadError::DecodeFailed(
"cnn_recognize_char: 图像尺寸必须大于0",
)
}
if img.channels < 1 || img.channels > 4 {
raise @types.LoadError::DecodeFailed("cnn_recognize_char: 通道数非法")
}
if labels.length() != config.num_classes {
raise @types.LoadError::DecodeFailed(
"cnn_recognize_char: 标签数量不匹配",
)
}
let image_data = resize_image_for_cnn(
img,
config.input_width,
config.input_height,
)
cnn_infer(image_data, config, labels)
}
///|
/// CNN 数字识别
pub fn cnn_recognize_digits(
img : @types.Image,
config : DLCnnModelConfig,
) -> DLInferenceResult raise @types.LoadError {
let labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
cnn_recognize_char(img, config, labels)
}
///|
/// CNN 字母识别
pub fn cnn_recognize_letters(
img : @types.Image,
config : DLCnnModelConfig,
) -> DLInferenceResult raise @types.LoadError {
let labels = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
]
cnn_recognize_char(img, config, labels)
}
///|
/// 评估 CNN 模型准确率和平均置信度
pub fn evaluate_cnn_model(
test_samples : Array[DLTrainingSample],
config : DLCnnModelConfig,
labels : Array[String],
) -> (Double, Double) raise @types.LoadError {
if test_samples.length() == 0 {
raise @types.LoadError::DecodeFailed(
"evaluate_cnn_model: 测试样本不能为空",
)
}
if labels.length() != config.num_classes {
raise @types.LoadError::DecodeFailed(
"evaluate_cnn_model: 标签数量不匹配",
)
}
let mut correct = 0
let mut total_conf = 0.0
for i in 0.. Array[Array[Int32]] raise @types.LoadError {
if test_samples.length() == 0 {
raise @types.LoadError::DecodeFailed(
"cnn_confusion_matrix: 测试样本不能为空",
)
}
if labels.length() != config.num_classes {
raise @types.LoadError::DecodeFailed(
"cnn_confusion_matrix: 标签数量不匹配",
)
}
let n = config.num_classes
let matrix : Array[Array[Int32]] = []
for _ in 0..