AI Wiki中文/EN

OCR:认出文字,也要保住文档原意

Optical character recognition

实现完整小CNN/BiRNN及CTC梯度,检查重复字符和束解码,并区分文字识别与文档解析。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

认对字,不等于读对整页

假设一张发票有两栏,每个字都识别正确,但右栏的金额被接到了左栏错误的商品上。字符准确率完美,提取出的文档仍然错了。

光学字符识别,即OCR,把可见文字转换成机器可读的符号。实际文档流程还可能需要定位文字区域、判断方向、恢复阅读顺序、组合表格单元格和提取字段。这些环节的目标与失败方式不同,行识别器不会自动变成整页解析器。PaddleOCR在2025年的报告中,也把文字识别、结构解析和关键信息提取明确分为不同方案。任务分工

将PDF栅格化之前,先检查它是否已有可用文本。提取并核对文本层可以避免不必要的识别步骤,但顺序和编码仍要检查。扫描页或照片则需要从像素识别。应保留原页与坐标,让读者能把提取出的值追溯到图像证据。

本篇实现一个小型图像到序列识别器:读取合成A/B字形,包含完整前向与反向计算,并展示它仍然存在的错误。文本检测与整页结构另行解释,没有暗藏在例子中。

实际计算的重复字符折叠、最佳路径与标签概率,以及训练后仍然错误的合成AA转录。
原创计算图:blank保住重复字符,整串概率需要累加路径,训练损失下降也可能仍读错。概率反例与合成训练分开计算。

先定位文字,再表示一行,最后解码序列

检测器回答在哪里,不回答写了什么

检测器可以在文字周围输出矩形、四边形或多边形,识别器接收裁剪图并预测符号。旋转或弯曲文字会使裁剪更困难;多个裁剪区域按什么顺序排列,又需要另外的规则或模型。

DBNet预测文字概率图P和学习得到的阈值图T,以正数k控制二值化近似的陡峭程度:

B^ij=11+exp⁡[−k(Pij−Tij)].\widehat B_{ij}=\frac{1}{1+\exp[-k(P_{ij}-T_{ij})]}.

其局部导数为:

∂B^∂P=kB^(1−B^),∂B^∂T=−kB^(1−B^).\frac{\partial\widehat B}{\partial P}=k\widehat B(1-\widehat B),\qquad \frac{\partial\widehat B}{\partial T}=-k\widehat B(1-\widehat B).

P=T时输出0.5;使用论文中的k=50时,导数为12.5。训练信号因此可以穿过软阈值。原论文允许推理时直接使用概率图,不必保留学习阈值的分支。DB方法

所读固定PaddleOCR后处理器对概率图使用严格大于阈值的判断,再生成多边形或四边形,还包含基于面积和周长的扩张步骤。它与可微sigmoid不是同一段计算。本例只实现后者的局部算子,没有实现训练后的文字检测器或多边形流程。固定后处理

把图像宽度变成序列长度

CRNN结合卷积特征、双向循环网络与转录。特征图按列读取,因此变宽图像可以变成变长序列。原模型采用双向LSTM,训练目标是文字串,不需要逐字符框;这并没有免除更大系统中取得文字裁剪图的工作。原始CRNN

本例缩小模型:一层卷积、沿特征高度取平均、两个方向相反的tanh RNN、拼接状态,再投影到字符logit。平均池化替代论文的列拼接,tanh单元替代LSTM。完整教学网络有93个参数,保留图像宽度,因此7×11的合成“AA”产生11个输出帧,而不是两个预先分割的字符槽位。

本例假定水平、从左到右的裁剪图。竖排、从右到左以及混合顺序文字,需要明确的排序与规范化策略。

两个循环方向能够利用模糊笔画两侧的上下文。这与CTC的输出分解并不矛盾:帧概率以输入及网络表示为条件,并不意味着图像帧之间独立,CTC输出层也不会因此成为自回归语言模型。CTC假设

CTC把不同对齐方式加起来

连接时序分类CTC在字符表中加入一个blank空白标签。它表示“不输出标签”;若要识别真正的空格,需要单独的字符标签。路径π给每个输出帧分配字符或blank。折叠时先合并连续重复,再删除blank。所以A A blank A变成AA,而A A A变成A,顺序不能颠倒。转录规则

对于目标串y和各帧概率pt,CTC把所有折叠后等于y的路径概率相加:

P(y∣x)=∑π:B(π)=y∏t=0T−1pt(πt).P(y\mid x)=\sum_{\pi:\mathcal B(\pi)=y}\prod_{t=0}^{T-1}p_t(\pi_t).

一个字符可以占据多个帧,不必告诉模型每个字符从哪里开始。这是有监督的序列学习,不是没有文字标签的学习。直接枚举路径随帧数指数增长,动态规划则复用共同的部分对齐。CTC构造

在目标符号前后及相邻符号之间插入blank,得到长度S=2U+1的扩展序列z。令αt(s)表示第t帧结束于状态s的路径概率之和,包含该帧的发射概率。只有当s≥2、zs不是blank且不同于zs−2时,δs才为1。于是:

αt(s)=pt(zs)[αt−1(s)+αt−1(s−1)+δsαt−1(s−2)].\alpha_t(s)=p_t(z_s)\left[\alpha_{t-1}(s)+\alpha_{t-1}(s-1)+\delta_s\alpha_{t-1}(s-2)\right].

越界状态贡献为零。第一帧只允许初始blank,以及非空目标的第一个字符。原地停留表示重复当前状态;前进一步跨过blank/字符边界;有条件的两步跳转可以越过不同字符之间的blank,却不能越过相同目标字符之间的blank。

对非空目标,最终允许停在最后一个字符或最后一个blank:

P(y∣x)=αT−1(S−2)+αT−1(S−1),L=−log⁡P(y∣x).P(y\mid x)=\alpha_{T-1}(S-2)+\alpha_{T-1}(S-1),\qquad L=-\log P(y\mid x).

程序在对数空间使用log-sum-exp计算,不直接连乘大量小概率。空目标只有blank状态;空输入配空目标时损失为零,空输入配非空目标则不可能。

本例反向变量βt(s)描述第t帧之后剩余发射的概率,不包含当前帧。这与原论文包含当前帧的β约定不同,两者只要前后一致都可使用。第t帧符号k的后验占用概率与logit梯度为:

γt(k)=∑s:zs=kαt(s)βt(s)P(y∣x),∂L∂at(k)=pt(k)−γt(k).\gamma_t(k)=\frac{\sum_{s:z_s=k}\alpha_t(s)\beta_t(s)}{P(y\mid x)},\qquad \frac{\partial L}{\partial a_t(k)}=p_t(k)-\gamma_t(k).

at(k)是softmax之前的logit。减去后验占用概率,就得到投影层、两个RNN及CNN接收的误差信号。测试独立枚举小规模路径,将占用概率与动态规划对照,再用有限差分检查全部模型梯度。

重复标签决定最少需要多少帧。若R为相邻相同目标符号对的数量:

Tmin⁡=U+R.T_{\min}=U+R.

“AA”至少需要三帧,例如A blank A。若下采样后只剩两帧,再训练也无法产生合法对齐。本例对不可行目标返回无穷损失、不返回梯度,而不是悄悄把它当成零损失样本。批量填充时要说明长度策略;所读PaddleOCR封装把共同预测长度传给每个样本。损失封装

最佳路径可能不是最佳文字串

假设两个帧的概率都是blank=0.4、A=0.35、B=0.25。贪心解码选择两个blank,得到概率0.16的空串。标签“A”却有三条路径:A A、A blank、blank A,概率合计0.4025,比贪心结果更高。

本例前缀束分别保存以blank和非blank结尾的前缀概率质量。这样既能保留由blank隔开的重复字母,又能合并连续重复。有限束宽会剪掉候选,不能保证全局最优;这个例子中束宽为1时仍返回空串。程序没有使用词典或语言模型。解码区别

词典或语言模型可以消除歧义,也可能把陌生姓名、标识符改成常见但错误的词。应分别评估原始识别器与受约束解码器。CRNN原文也明确区分无词典和有词典的评测条件。词典条件

不要把接口中的“置信度”与整串转录的概率混淆。所读PaddleOCR贪心解码器对保留下来的token最大值取平均,若一个也没保留则使用零;这个统计量不是CTC对完整对齐路径的求和。解码与分数计算

文字和结构分开测量

若替换、删除、插入次数分别为S、D、I,参考字符总数为N,微平均字符错误率为:

CER⁡=S+D+IN.\operatorname{CER}=\frac{S+D+I}{N}.

先在整个语料上累计编辑次数,再除以字符数。book→bok需要一次删除,A→ABC需要两次插入,合计CER=3/5=0.6。若先计算每行错误率再平均,会得到另一个结果。插入可以使CER超过1。参考分母为空时,即使模型输出了错误文字,错误率也未定义,需要另报插入次数。原CTC研究就采用了编辑距离式序列评测。序列错误衡量

词错误率WER使用词token而非字符。本例把字符定义为Python Unicode码点,把词定义为按空白分隔的token;NFC归一化是明确的可选项,不悄悄删除大小写、标点或空格。这不是字素簇切分,按空白切分也不是通用中文分词。报告分数时应一起报告这些规则。

文字正确但顺序错误、表格单元格错位、漏掉一块文字,都需要另外的端到端检查。检测召回、裁剪图识别、字段精确匹配,以及阅读顺序/表格测试应分别保留,否则准确的识别器会掩盖坏掉的文档流程。

让像素经过完整的CTC更新

使用Python 3.12和NumPy 1.26.4。将代码保存为ocr_sequence.py,运行python ocr_sequence.py。程序生成两种原创位图字形,构造合成文本行,计算CNN/BiRNN logit、累加CTC路径、向所有参数反传,再更新一次,不需要下载数据或预训练权重。

DB sigmoid、编辑指标和解码反例是独立计算。本例不声称完整复现CRNN、整页检测器、文档解析器或OCR服务。tanh循环单元和高度平均是明确的简化,不是原论文架构。

"""Original tiny image-to-sequence CNN/BiRNN with complete CTC gradients.

Synthetic A/B glyphs only. Tanh recurrent units replace the original CRNN's
LSTMs. No text detector, layout parser, language model or pretrained OCR engine.
"""
import json
import unicodedata
import numpy as np


def finite(value, rank):
    x=np.asarray(value,float)
    if x.ndim!=rank or not np.isfinite(x).all():raise ValueError('finite array of specified rank required')
    return x


def logsum(values):
    values=np.asarray(values,float)
    if values.size==0:return -np.inf
    maximum=values.max()
    if maximum==-np.inf:return -np.inf
    return float(maximum+np.log(np.exp(values-maximum).sum()))


def log_softmax(logits):
    z=finite(logits,2)
    if z.shape[1]<2:raise ValueError('at least blank and one label required')
    shifted=z-z.max(axis=1,keepdims=True)
    return shifted-np.log(np.exp(shifted).sum(axis=1,keepdims=True))


def validate_blank(blank,classes):
    if type(blank) is not int or not 0<=blank<classes:raise ValueError('valid integer blank index required')


def collapse(path,blank=0):
    """Merge consecutive repeats BEFORE removing blanks."""
    labels=np.asarray(path)
    if labels.ndim!=1 or (len(labels) and (labels.dtype.kind not in 'iu' or np.any(labels<0))):
        raise ValueError('nonnegative integer path required')
    if type(blank) is not int or blank<0:raise ValueError('nonnegative blank index required')
    out=[];previous=None
    for symbol in labels:
        if symbol!=previous and symbol!=blank:out.append(int(symbol))
        previous=symbol
    return tuple(out)


def ctc(logits,target,blank=0):
    """Log-space single-sequence CTC; beta EXCLUDES the current emission.

    Returns loss, logit gradient, diagnostics. Infeasible targets have infinite
    loss and gradient=None, never a silent zero gradient. Empty/empty is valid.
    """
    lp=log_softmax(logits);time,classes=lp.shape;validate_blank(blank,classes)
    target=np.asarray(target)
    if target.ndim!=1 or (len(target) and (target.dtype.kind not in 'iu' or np.any(target<0) or np.any(target>=classes) or np.any(target==blank))):
        raise ValueError('target labels must be valid nonblank integers')
    target=target.astype(int);length=len(target)
    minimum=length+int((target[1:]==target[:-1]).sum())
    if time<minimum:
        return float('inf'),None,{'feasible':False,'minimumFrames':minimum,'logProbability':-float('inf')}
    if time==0:
        return 0.,np.empty_like(lp),{'feasible':True,'minimumFrames':0,'logProbability':0.,'posterior':np.empty_like(lp)}
    states=np.full(2*length+1,blank,int);states[1::2]=target;size=len(states)
    incoming=[]
    for s in range(size):
        prior=[s]
        if s>=1:prior.append(s-1)
        if s>=2 and states[s]!=blank and states[s]!=states[s-2]:prior.append(s-2)
        incoming.append(prior)
    outgoing=[[] for _ in range(size)]
    for s,prior in enumerate(incoming):
        for previous in prior:outgoing[previous].append(s)
    alpha=np.full((time,size),-np.inf);alpha[0,0]=lp[0,blank]
    if length:alpha[0,1]=lp[0,target[0]]
    for t in range(1,time):
        for s in range(size):alpha[t,s]=lp[t,states[s]]+logsum(alpha[t-1,incoming[s]])
    ends=[size-1] if length==0 else [size-2,size-1]
    log_probability=logsum(alpha[-1,ends])
    beta=np.full_like(alpha,-np.inf);beta[-1,ends]=0
    for t in range(time-2,-1,-1):
        for s in range(size):
            following=outgoing[s]
            beta[t,s]=logsum(lp[t+1,states[following]]+beta[t+1,following])
    posterior=np.zeros_like(lp)
    state_posterior=np.exp(alpha+beta-log_probability)
    for s,symbol in enumerate(states):posterior[:,symbol]+=state_posterior[:,s]
    gradient=np.exp(lp)-posterior
    return -log_probability,gradient,{'feasible':True,'minimumFrames':minimum,
            'logProbability':log_probability,'posterior':posterior}


def greedy_decode(logits,blank=0):
    lp=log_softmax(logits);validate_blank(blank,lp.shape[1])
    return collapse(lp.argmax(axis=1),blank)


def prefix_beam(logits,beam_size=32,blank=0):
    """Pruned prefix beam with separate blank/nonblank ending masses; no LM.

    Returned scores retain only paths surviving pruning; finite beams do not
    guarantee the global most probable transcription. Ties sort lexicographically.
    """
    lp=log_softmax(logits);validate_blank(blank,lp.shape[1])
    if type(beam_size) is not int or not 1<=beam_size<=1024:raise ValueError('beam size1..1024 required')
    beam={():[0.,-np.inf]}
    for row in lp:
        updated={}
        def add(prefix,kind,value):
            masses=updated.setdefault(prefix,[-np.inf,-np.inf]);masses[kind]=np.logaddexp(masses[kind],value)
        for prefix,(pb,pn) in beam.items():
            total=np.logaddexp(pb,pn);add(prefix,0,total+row[blank])
            for symbol in range(len(row)):
                if symbol==blank:continue
                if prefix and prefix[-1]==symbol:
                    add(prefix,1,pn+row[symbol])
                    add(prefix+(symbol,),1,pb+row[symbol])
                else:add(prefix+(symbol,),1,total+row[symbol])
        ranked=sorted(updated.items(),key=lambda item:(-np.logaddexp(*item[1]),item[0]))
        beam=dict(ranked[:beam_size])
    return [(prefix,float(np.logaddexp(*mass))) for prefix,mass in sorted(beam.items(),key=lambda item:(-np.logaddexp(*item[1]),item[0]))]


def edit_counts(reference,hypothesis):
    """Token edit DP. Equal-cost paths prefer diagonal, then deletion, insertion."""
    a,b=list(reference),list(hypothesis);n,m=len(a),len(b)
    cost=np.zeros((n+1,m+1),int);trace=np.zeros_like(cost)
    cost[:,0]=np.arange(n+1);cost[0,:]=np.arange(m+1);trace[1:,0]=1;trace[0,1:]=2
    for i in range(1,n+1):
        for j in range(1,m+1):
            candidates=[cost[i-1,j-1]+(a[i-1]!=b[j-1]),cost[i-1,j]+1,cost[i,j-1]+1]
            trace[i,j]=int(np.argmin(candidates));cost[i,j]=candidates[trace[i,j]]
    substitutions=deletions=insertions=0;i,j=n,m
    while i or j:
        if trace[i,j]==0:
            substitutions+=int(a[i-1]!=b[j-1]);i-=1;j-=1
        elif trace[i,j]==1:deletions+=1;i-=1
        else:insertions+=1;j-=1
    return {'substitutions':substitutions,'deletions':deletions,'insertions':insertions,
            'distance':int(cost[n,m]),'referenceLength':n}


def error_rate(references,hypotheses,unit='character',normalization=None):
    """Micro edit rate: Python Unicode code points or whitespace-delimited words.

    Optional NFC only. No punctuation/case/space removal, grapheme segmentation,
    Chinese word segmentation, or silently defined rate for an empty denominator.
    """
    if len(references)!=len(hypotheses) or unit not in ['character','word'] or normalization not in [None,'NFC']:
        raise ValueError('paired strings, declared unit and optional NFC required')
    total={'substitutions':0,'deletions':0,'insertions':0,'distance':0,'referenceLength':0}
    exact=0
    for reference,hypothesis in zip(references,hypotheses):
        if not isinstance(reference,str) or not isinstance(hypothesis,str):raise ValueError('string samples required')
        if normalization:
            reference=unicodedata.normalize(normalization,reference);hypothesis=unicodedata.normalize(normalization,hypothesis)
        a,b=(list(reference),list(hypothesis)) if unit=='character' else (reference.split(),hypothesis.split())
        counts=edit_counts(a,b)
        for key in total:total[key]+=counts[key]
        exact+=int(a==b)
    total['rate']=total['distance']/total['referenceLength'] if total['referenceLength'] else None
    total['exactMatch']=exact/len(references) if len(references) else None
    return total


def differentiable_binary(probability,threshold,k=50.):
    """Local DB sigmoid operator, not a text detector or polygon postprocessor."""
    p,t=finite(probability,2),finite(threshold,2)
    if p.shape!=t.shape or min(p.shape)<1 or np.any((p<0)|(p>1)|(t<0)|(t>1)) or not np.isfinite(k) or k<=0:
        raise ValueError('matching probability/threshold maps in[0,1] and positive k required')
    z=k*(p-t);out=np.exp(-np.logaddexp(0,-z));derivative=k*out*(1-out)
    return out,derivative,-derivative


def conv(image,k,b):
    h,w,_=image.shape;size=k.shape[0];pad=size//2
    padded=np.pad(image,((pad,pad),(pad,pad),(0,0)));out=np.broadcast_to(b,(h,w,len(b))).copy()
    for y in range(size):
        for x in range(size):out+=padded[y:y+h,x:x+w] @ k[y,x]
    return out


def conv_backward(image,k,gradient):
    h,w,_=image.shape;size=k.shape[0];pad=size//2
    padded=np.pad(image,((pad,pad),(pad,pad),(0,0)));dx=np.zeros_like(padded);dk=np.zeros_like(k)
    for y in range(size):
        for x in range(size):
            dk[y,x]=np.einsum('hwc,hwf->cf',padded[y:y+h,x:x+w],gradient)
            dx[y:y+h,x:x+w]+=gradient @ k[y,x].T
    return dx[pad:pad+h,pad:pad+w],dk,gradient.sum(axis=(0,1))


def rnn(sequence,parameters):
    wx,wh,b=parameters;hidden=np.zeros((len(sequence),len(b)));previous=np.zeros(len(b))
    for t,x in enumerate(sequence):hidden[t]=np.tanh(x @ wx+previous @ wh+b);previous=hidden[t]
    return hidden


def rnn_backward(sequence,hidden,parameters,gradient):
    wx,wh,b=parameters;dx=np.zeros_like(sequence);dwx=np.zeros_like(wx);dwh=np.zeros_like(wh);db=np.zeros_like(b);carry=np.zeros_like(b)
    for t in range(len(sequence)-1,-1,-1):
        dz=(gradient[t]+carry)*(1-hidden[t]**2);previous=hidden[t-1] if t else np.zeros_like(b)
        dwx+=np.outer(sequence[t],dz);dwh+=np.outer(previous,dz);db+=dz
        dx[t]=dz @ wx.T;carry=dz @ wh.T
    return dx,[dwx,dwh,db]


def parameters(seed=17):
    rng=np.random.default_rng(seed)
    return [rng.normal(0,.2,(3,3,1,3)),np.full(3,.1),
            rng.normal(0,.2,(3,3)),rng.normal(0,.2,(3,3)),np.zeros(3),
            rng.normal(0,.2,(3,3)),rng.normal(0,.2,(3,3)),np.zeros(3),
            rng.normal(0,.2,(6,3)),np.zeros(3)]


def forward(image,p):
    image=finite(image,3)
    if min(image.shape)<1 or image.shape[2]!=1:raise ValueError('nonempty H,W,1 image required')
    feature=np.tanh(conv(image,p[0],p[1]));sequence=feature.mean(axis=0)
    left=rnn(sequence,p[2:5]);right_reversed=rnn(sequence[::-1],p[5:8])
    joined=np.concatenate([left,right_reversed[::-1]],axis=1)
    return joined @ p[8]+p[9],(image,feature,sequence,left,right_reversed,joined)


def backward(p,cache,gradient):
    image,feature,sequence,left,right_reversed,joined=cache;gradient=finite(gradient,2)
    if gradient.shape!=(image.shape[1],3):raise ValueError('matching time,class gradient required')
    dw=joined.T @ gradient;db=gradient.sum(axis=0);dh=gradient @ p[8].T
    dx_left,dp_left=rnn_backward(sequence,left,p[2:5],dh[:,:3])
    dx_reverse,dp_right=rnn_backward(sequence[::-1],right_reversed,p[5:8],dh[:,3:][::-1])
    ds=dx_left+dx_reverse[::-1]
    df=np.broadcast_to(ds[None]/image.shape[0],feature.shape)*(1-feature**2)
    dx,dk,dc=conv_backward(image,p[0],df)
    return [dk,dc]+dp_left+dp_right+[dw,db],dx


def glyph_line(text):
    glyphs={'A':['01110','10001','10001','11111','10001','10001','10001'],
            'B':['11110','10001','10001','11110','10001','10001','11110']}
    if not isinstance(text,str) or not text or any(c not in glyphs for c in text):raise ValueError('nonempty synthetic A/B string required')
    pieces=[]
    for i,c in enumerate(text):
        if i:pieces.append(np.zeros((7,1)))
        pieces.append(np.array([[float(v) for v in row] for row in glyphs[c]]))
    return np.concatenate(pieces,axis=1)[...,None]


def demo():
    image=glyph_line('AA');p=parameters();logits,cache=forward(image,p)
    before,gradient,diagnostic=ctc(logits,[1,1]);dp,dx=backward(p,cache,gradient)
    for value,derivative in zip(p,dp):value-=.05*derivative
    after_logits,_=forward(image,p);after=ctc(after_logits,[1,1])[0];assert after<before
    ambiguous=np.log([[.4,.35,.25],[.4,.35,.25]])
    beams=prefix_beam(ambiguous,32)
    db,dprob,dthreshold=differentiable_binary([[.4,.5,.6]],[[.5,.5,.5]])
    return {'parameters':sum(v.size for v in p),'inputShape':list(image.shape),'frames':len(logits),
            'target':[1,1],'minimumFrames':diagnostic['minimumFrames'],'lossBefore':before,'lossAfterOneStep':after,
            'inputGradientNorm':float(np.linalg.norm(dx)),'networkGreedyAfter':list(greedy_decode(after_logits)),
            'blankSeparatedRepeat':list(collapse([1,1,0,1])),'greedyCounterexample':list(greedy_decode(ambiguous)),
            'bestPrefixCounterexample':list(beams[0][0]),'bestLabelProbability':float(np.exp(beams[0][1])),
            'emptyLabelProbability':float(np.exp(-ctc(ambiguous,[])[0])),
            'cerExample':error_rate(['book','A'],['bok','ABC']),
            'dbValues':db.tolist(),'dbProbabilityGradient':dprob.tolist(),
            'scope':'one synthetic AA update; separate decoding/metric/DB fixtures; not a pretrained or page-level OCR result'}


if __name__=='__main__':print(json.dumps(demo(),indent=2))

已检查环境的输出如下,浮点末位可能随平台略有差别:

{
  "parameters": 93,
  "inputShape": [
    7,
    11,
    1
  ],
  "frames": 11,
  "target": [
    1,
    1
  ],
  "minimumFrames": 3,
  "lossBefore": 5.859007152446334,
  "lossAfterOneStep": 4.692159498168067,
  "inputGradientNorm": 0.024114785000749216,
  "networkGreedyAfter": [
    1,
    1,
    1,
    1
  ],
  "blankSeparatedRepeat": [
    1,
    1
  ],
  "greedyCounterexample": [],
  "bestPrefixCounterexample": [
    1
  ],
  "bestLabelProbability": 0.4024999999999999,
  "emptyLabelProbability": 0.15999999999999998,
  "cerExample": {
    "substitutions": 0,
    "deletions": 1,
    "insertions": 2,
    "distance": 3,
    "referenceLength": 5,
    "rate": 0.6,
    "exactMatch": 0.0
  },
  "dbValues": [
    [
      0.006692850924284861,
      0.5,
      0.9933071490757152
    ]
  ],
  "dbProbabilityGradient": [
    [
      0.332402833539508,
      12.5,
      0.33240283353950717
    ]
  ],
  "scope": "one synthetic AA update; separate decoding/metric/DB fixtures; not a pretrained or page-level OCR result"
}

损失从5.85901降到4.69216,但networkGreedyAfter中有四个A,目标只有两个。程序展示这个错误,没有把演示结果偷偷替换为真值。训练目标降低,不保证一步更新后贪心转录就正确。

卷积计算量为O(HWk²CinCout)。特征宽度D、隐藏宽度H的单向tanh循环网络计算量为O(T(DH+H²)),双向模型运行两个方向。对于C个类别、长度U的目标,本例CTC计算量为O(TC+TU),保留logit/后验和对齐状态的存储为O(T(C+U))。如果只求前向概率,可以减少对齐状态存储,但本例为求梯度保留它们。

束宽B时,前缀扩展在整个序列上合计考虑O(TBC)个符号扩展,再进行排序。Python元组复制和排序还会增加开销;这是透明的小解码器,不是生产速度保证。编辑对齐对长度N、M的序列使用O(NM)时间和空间,因为保留了回溯路径,而不只计算最终距离。

重建得很通顺,也可能改掉证据

好的语言先验不能恢复已经丢失的像素。 模糊、倾斜、压缩和低对比度可能抹去小数点等区别。语言模型可以给出合理重建,但合理不等于忠实转录。数值重要时,应保留原始输出、候选或拒绝状态,以及来源裁剪图。

识别系统与解析器不同。 2007年Tesseract综述描述的是历史上的二值图/连通块/文本行流程,以及两遍自适应识别。固定现代README则说明Tesseract 4加入LSTM行识别引擎,同时保留旧模式。不能把旧分类器说成当前唯一引擎。历史引擎、现代项目

大小模型都有配置边界。 PP-OCRv5的CVPR 2026论文中,“5M”指移动端的检测加识别配置,不是每一个v5模型。所述识别器采用注意力引导的CTC训练;存在训练指导,并不会使本例的普通CTC变成该系统复现。本项目没有重跑论文的比较基准。配置与方法

截至本版事实截点,固定PaddleOCR README还记录了PP-OCRv6、PaddleOCR-VL-1.6与HPD-Parsing。文字识别和文档解析家族不能压缩成同一个模型名字或同一个准确率。2025报告的三方案概览仍有参考价值,但不能据此说v5是最新可用模型。带日期的项目概览、2025报告

部署有自己的问题。 应测量实际页面尺寸下的峰值内存和延迟、支持的字符表、置信/拒绝策略,以及每份文档需要多少人工修正。必要时按文档或来源集合划分数据,避免近重复泄漏。数据和模型的权利要与仓库代码许可分开检查;所读PaddleOCR代码许可标题是Apache 2.0,并不能为每个数据集提供一揽子证明。代码许可标题

可信转录的四个检查

1. 保住重复字母

折叠A A blank A。为什么先删blank再合并重复会出错?目标“AA”最少需要几帧?

答案:先合并连续重复得到A blank A,再删除blank,得到AA。若先删blank,会错误地把所有A连成一个连续段。两个目标字符加一对相邻重复,至少需要三帧。CTC blank不是真正印在纸上的空格。

2. 累加标签,不只看峰值

两个帧的概率都是[blank:0.4, A:0.35, B:0.25],计算空串概率与标签“A”的概率。

答案:只有blank-blank折叠为空,概率为0.4²=0.16。“A”对应A-A、A-blank和blank-A,合计0.35²+0.35×0.4+0.4×0.35=0.4025。因此,贪心选出的最佳路径并没有给出最佳标签。

3. 审查错误率分母

参考为book、A,输出为bok、ABC,计算语料CER,再考虑参考为空、输出为X的情况。

答案:一次删除加两次插入,共三次编辑,参考有五个码点,CER=0.6。空参考仍贡献一次插入,但没有参考字符;若只有这一个样本,错误率未定义而非零。若它属于更大的语料,其插入仍要进入分子。

4. 诊断下降的损失和错误的文档

小网络损失下降,但对目标AA给出贪心结果AAAA。另一个解析器认对所有文字,却把金额接到错误表格行。两者应分别报告什么?

答案:网络应同时报告降低的CTC目标和错误转录,按实际输出计算编辑错误。页面解析器即使字符错误为零,也需要阅读顺序、单元格归属或字段层面的评测。低损失和完美的裁剪图字符识别,都不能证明文档正确。

追踪任务变化,不只记引擎名字

Tesseract的两份来源都说HP在2005年将它开源,但对研发起点说法不同:2007论文写1984年,固定README写1985年。两者都把源头放在HP的1980年代工作;这里保留差异,不编造一个权威起始日。历史叙述、仓库历史

CTC在ICML 2006发表,用于未分段序列标注,实验任务是语音,并非一开始就是完整整页OCR系统。CRNN首个预印本提交于2015年7月21日;DBNet为2019年11月20日,与其AAAI 2020会议年份分别记录。CTC论文、CRNN历史、DBNet历史

PaddleOCR 3.0技术报告提交于2025年7月8日。固定项目README之后记录了2026年6月11日的PaddleOCR 3.7.0及PP-OCRv6;报告日期、软件发布与论文发表是不同事件。报告历史、固定发布记录

有用的复现应保留图像预处理、检测/裁剪规则、字符字典、blank索引、帧长度、训练损失归一方式、解码器和评测归一化。这些细节决定什么输出有可能出现,以及错误次数意味着什么。本篇让一个小版本可检查;完整OCR准确率与文档解析仍是另外的实证任务。

先判断,再看解释

CTC路径A A blank A应折叠为什么?

选择一个答案

学习目标

  • 区分检测、行识别、阅读顺序和文档结构。
  • 追踪CTC路径、blank/重复规则及完整神经网络梯度。
  • 比较贪心解码、前缀概率累加与有限束宽的局限。
  • 如实报告编辑次数、归一化规则和流程层面的失败。

先修与延伸

查看知识关联图 →

参考文献

  1. Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks
    Alex Graves; Santiago Fernández; Faustino Gomez; Jürgen Schmidhuber · 2006
  2. An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition
    Baoguang Shi; Xiang Bai; Cong Yao · 2015
  3. Real-time Scene Text Detection with Differentiable Binarization
    Minghui Liao; Zhaoyi Wan; Cong Yao; Kai Chen; Xiang Bai · 2019
  4. An Overview of the Tesseract OCR Engine
    Ray Smith · 2007
  5. PaddleOCR 3.0 Technical Report
    Cheng Cui et al. · 2025
  6. PP-OCRv5: A Specialized 5M-Parameter Model Rivaling Billion-Parameter Vision-Language Models on OCR Tasks
    Cheng Cui; Yubo Zhang et al. · 2026
  7. PaddleOCR fixed family overview and releases
    PaddlePaddle contributors · 2026
  8. PaddleOCR fixed Apache2.0 license heading
    PaddlePaddle contributors · 2026
  9. PaddleOCR fixed CTC decoding and score calculation
    PaddlePaddle contributors · 2026
  10. PaddleOCR fixed CTC loss wrapper
    PaddlePaddle contributors · 2026
  11. PaddleOCR fixed DB postprocessing
    PaddlePaddle contributors · 2026
  12. Tesseract fixed neural and legacy engine overview
    Tesseract contributors · 2026
  13. An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition — submission history
    Baoguang Shi; Xiang Bai; Cong Yao · 2015
  14. Real-time Scene Text Detection with Differentiable Binarization — submission history
    Minghui Liao; Zhaoyi Wan; Cong Yao; Kai Chen; Xiang Bai · 2019
  15. PaddleOCR 3.0 Technical Report — submission history
    Cheng Cui et al. · 2025

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: scoped original OCR/CTC papers and fixed PaddleOCR/Tesseract sources; exhaustive CTC paths/posteriors, full93-parameter model gradients, independent decoding/edit/DB tests, bilingual comparison and computed diagram binding. Not human peer review or OCR benchmark reproduction.

  • 二十项数值加四项双语/输出/元数据/图示检查;全部93参数和20输入经过CTC中心差分,穷举路径/占用、空/重复/不可行目标、前缀束与精确搜索、编辑计数归一化及DB导数。
  • 逐节核对完整双语、八公式、完整代码/输出、四组解释答案与十五限定来源;保留下降损失下的错误AAAA、未来型beta、文本/整页区别、新旧引擎与Tesseract日期分歧,复用已有CTC事件不重复计数。

核对的来源位置:

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。