Abstract
Handwritten text recognition, i.e., the conversion of scanned handwritten documents into machinereadable text, is a complex exercise due to the variability and complexity of handwriting. A common approach in handwritten text recognition consists of a feature extraction step followed by a recognizer. In this paper, we propose a novel DNN architecture for handwritten text recognition that extracts discrete representation from the input textline image. The proposed model is constructed of an encoder–decoder network with an added quantization layer which applies a dictionary of representative vectors to discretize the latent variables. The dictionary and the network parameters are trained jointly through the kmeans algorithm and back propagation, respectively. The performance of the suggested model is evaluated through conducting extensive experiments on five datasets, analyzing the effect of discrete representation on handwriting recognition. The results demonstrate that the use of feature discretization improves the performance of deep handwriting text recognition models when compared to the conventional DNN models with continuous representation. Specifically, the character error rate is decreased by \(22\%\) and \(21.1\%\) on IAM and ICFHR18 datasets, respectively.
Similar content being viewed by others
1 Introduction
While automatic transcription of characters from printed documents has significantly improved in the past decade [1,2,3], transcription of handwritten documents (or handwritten text recognition—HTR) is still a rather challenging exercise and current models are still far from satisfactory performance. This is due, among other reasons, to the large variations caused by the existence of various writing styles as well as the multiple noise factors introduced during the scanning phase. It is even more difficult with historical documents where the writing supports are highly degraded and present a high level of noise. However challenging, automatic transcription of handwritten documents provides a gateway to the content of a large volume of notyettranscribed books and offers experts the ability to accelerate the analysis of such content to extract meaningful information and to facilitate the search for information across vast repositories of historical manuscripts.
Extracting a proper representation of the input image that mitigates the irrelevant variations in document images while preserving the important information is a key step in automatic text recognition. Handcrafted features, such as statistical attributes or shape descriptors, have been widely used in handwriting recognition models [4,5,6]. However, specifying a proper set of features compensating for all document variations while being compatible with the subsequent recognizer is an expensive and timeconsuming task. An alternative approach is to apply learning methods to extract representations automatically in a supervised or unsupervised mode [7,8,9,10]. Deep neural networks (DNNs) have been extensively applied to text image recognition [11, 12], so that the most common architecture for handwriting recognition utilizes convolutional neural network (CNN) layers to compute a feature map representing the input image to be fed to the subsequent neural recognizer (usually a stack of recurrent neural networks (RNNs)) which recognizes the sequence of constituent letters [13]. The representation network and the recognizer are trained jointly to minimize the cost function. Despite their improved performance compared to conventional methods, current DNNbased models, however, have some weaknesses:

They apply the common deep architectures introduced for general images directly into document images, not considering the characteristics of text images. While some modifications have been applied to adapt the recognizer (e.g., developing sequential models) and loss function (applying a connectionist temporal classification—CTC), not much has been done to adapt the representation network. This is while the significance that proper representation plays in handwriting recognition has been widely demonstrated in previous studies [14, 15].

They are limited to learning a “continuous” representation of the input image to be trainable by the backpropagation algorithm. While many conventional handwriting recognition models take advantage of intrinsically discretized visual components of the text image, e.g., primitive shapes [14, 16], existing deep models are not adapted correspondingly.
In this paper, we introduce a novel method for neural handwritten text recognition that utilizes discrete representation. The main motivation is to develop a representation network that matches the configuration of scripts where a limited set of basic components (e.g., signs or drawing strokes) are combined to construct the words and sentences. Depending on the handwriting style, writing tools, and type of image noises, these basic components can deform and appear differently, while still referring to a component in the set. Inspired by this characteristic of text images, the proposed model utilizes a set of primitive representation vectors, i.e., a dictionary, to represent the input text image.
The model includes a CNNbased encoder that maps the input image to the continuous feature space. The computed features are passed to a “quantization” layer where the feature vectors are discretized using a dictionary. Discrete features are then pushed to an RNNbased decoder to generate the output text. The quantization layer performs the vector quantization on the latent vectors comparing their values with the dictionary atoms and selecting the closest one. During the training, the dictionary is trained jointly with the encoder–decoder networks in order to be consistent with the recognition model. To tackle the nondiferentiability imposed by the quantization layer, we develop a hybrid training algorithm that updates the dictionary and the network weights with kmeans algorithm and back propagation iteratively. The experimental results demonstrate the effectiveness of utilizing discrete representation in handwriting recognition, as the model achieves promising results on both modern and historical documents, outperforming the stateoftheart results.
In summary, the main contributions of this work are the following:

a novel deep neural network architecture for handwriting recognition is proposed. This architecture builds upon the conventional CNN+RNN architectures but utilizes discrete representation instead of continuous representation.

a novel method for handwriting recognition that combines a dictionarybased model with a deep neural network is proposed. The dictionary and network parameters are trained together using a combination of batch Kmeans and backpropagation iteratively.

a comprehensive evaluation of the proposed model using modern and historical manuscript pages from benchmark databases. The results show that the proposed approach using discrete representation surpasses previous deep handwriting recognition models.
2 Related works
2.1 Handwriting recognition
Traditional handwritten text recognition models extract representative features, like scaleinvariant feature transform (SIFT) and histogram of gradients (HOG), from the segmented input image and apply classical machine learning to recognize constitutive characters [4]. To mitigate the segmentation errors, holistic descriptors have been applied to represent the word image as a whole and classify the words as inseparable entities [17]. The problem with this approach is the large number of classes to be recognized which requires highly discriminative features [18]. Hence, some lexicon reduction approaches were used to reduce the number of word hypotheses [19, 20], which are still prone to propagating errors of the elimination step to the recognition step. Later on, hidden Markov model (HMM) became popular for HTR as it merges the segmentation and recognition steps by modeling the word image as a sequence generated from the set of characters [21]. The advent of long shortterm memory (LSTM) networks prompted their application to endtoend textline recognition. The LSTM network and its variants were successfully applied for text recognition, thanks to the introduction of the CTC loss [22]. Minimizing the CTC loss function over the LSTM network built on top of the CNN features gained the stateoftheart result on most benchmarks [1, 23]. Encoder–Decoder architectures combined with the attention mechanism have also been applied to HTR, modeling the problem as a sequencetosequence conversion [24]. Despite their progress, RNN networks’ performance is limited by the available memory size. Sequential modeling with attention gates, as an alternative to recurrent units, has demonstrated significant improvements in modeling longer dependencies. The same approach applied on Handwriting recognition [12] has achieved promising results using fully convolutional models. However, this approach is computationally expensive, as it requires multiple attention layers to model the input dependencies, therefore increasing the size of the network with respect to the size of the input image. Due to the high capability of deep learning methods in processing high dimensional images, some studies have started to apply them for endtoend paragraph and page recognition as well [12, 25]. In this paper, we evaluate the performance of the model running experiments on textline images.
2.2 Neural discrete representation models
The success of deep learning methods is mainly due to their ability to learn proper representations. Autoencoders are the main deep network architecture widely used for computing data representation [26]. By applying a bottleneck in the network architecture, they learn the continuous representation vectors for the input data. Deep embedding models, like triplet network [27] and Siamese network [28], are commonly used in contentbased image retrieval (CBIR) to learn a compact and meaningful representation of images for similarity comparisons. These models typically consist of an encoder network that maps an input image to a highdimensional feature space and a similarity metric, such as a cosine similarity, that is used to compare feature vectors.
Most of the existing neural representation models learn continuous features. However, exerting a discrete representation, as we desire in this paper, creates difficulties in training as the gradients cannot backpropagate through the sampling layer. To solve this issue, one possibility is to estimate the gradient of the categorical distribution by a differentiable sampling from a GumbelSoftmax distribution [29]. Another approach is to use vector quantization, VQVAE, [30] which enforces discretization through a nearest neighbor lookup procedure. In this paper, we use vector quantization for discretizing the latent variables.
3 Problem statement
The majority of deep learningbased models for handwriting recognition use continuous variables to represent the input image. This is mainly due to the complexity of training neural networks with discrete variables and computational considerations. However, discrete representation has been widely used in traditional HTR models and has shown promising performance in representing the fundamental elements of text images. The goal of this paper is to explore the possibility of using discrete representation for deep neural network (DNN)based handwritten text recognition and to assess its impact on the performance of standard architectures.
More specifically, our objective is to develop a discretization layer for the CNN+RNN architecture commonly used in handwriting text recognition (HTR) to discretize the features from the CNN output. We also plan to devise a training procedure to address the nondifferentiability imposed by the added discretization layer, allowing the entire model to be trained with backpropagation. The new HTR model should follow the standard inference process in deep handwriting recognition, where it takes an image of a handwritten text line as input and outputs a sequence of individual characters. In the following, we will present our approach to this research problem in more detail and discuss the results.
4 Proposed approach
This section describes the proposed method for handwriting recognition using discrete representation. The proposed HTR model consists of an encoder–decoder network with an added quantization layer in the bottleneck that is responsible for quantizing the latent vectors (Fig. 1).
In the next subsections, we first illustrate the mechanism of the quantization layer explaining the process of dictionary learning. Then, a detailed architecture of the proposed HTR model is explained.
4.1 Quantization layer
To learn the discrete representation, we are inspired by the work presented in [30], VQVAE. Relying on the main idea of VQVAE, we compute discrete latent variables by applying a vector quantization technique with a dictionary D. The encoder and decoder networks apply this dictionary to find the representation of a given input and generate the output from it, respectively. The dictionary is trained simultaneously with the encoder–decoder networks. This allows for learning a dictionary compatible with the encoding/decoding functions.
Figure 1 provides a simple visualization of the vector quantization process that takes place in the quantization layer. Given the input x, the encoder computes the continuous feature vector \(z_e\) which is passed to the quantization layer to be quantized to \(z_q\). To this end, a dictionary D of size \(N\times K\) is used, where N is the dimensionality of each vector and K denotes the total number of vectors in the dictionary. \(z_e\) is quantized to be equal to the closest element of the dictionary.
More formally, the model can be considered as a conditional VAE with a discrete latent variable z, where the probability distribution over z, i.e., \(p_{\theta }(zx)\), is considered to be a categorical distribution over K dictionary atoms. This categorical distribution is restricted to get nonzero value just on one element selected based on the encoder output (Fig. 1). More precisely, the probability distribution over z, \(p_{\theta }(zx)\) is defined as in Eq. 1.
where \(z_e(x)\) denote the output of the encoder network and \(e_j\) is the jth element of the dictionary. Accordingly, in the forward pass, the model takes the input x and passes it through the encoder to compute \(z_e(x)\). The computed value is used in Eq. 1 to determine the distribution over the discrete latent variables z. Sampling from this distribution is equivalent to performing a nearest neighbor lookup through the dictionary and picking the dictionary atom closest to the \(z_e\), i.e., \({\text {argmin}}_j \Vert z_e(x) e_j\Vert ^2\). The drawn sample, \(z_q\), then passes through the decoder network to compute the output.
4.1.1 Training
The parameters of the model to be trained include the weights of the encoder network, the weights of the decoder network and the dictionary atoms. The model is trained by maximizing the likelihood function. Embracing the common approach in deep learning base handwriting recognition, we apply the CTC algorithm to compute the likelihood function. However, training the network by the backpropagation is not straightforward due to the nondifferentiability imposed by the argmin function in Eq. (1), which prevents the gradient from backpropagating toward the encoder. On the other hand, as the discrete latent variable has the categorical distribution, the reparameterization trick is not applicable either. To solve this problem, we use the trick proposed in [30] and approximate the gradient at the output of the encoder to be equal to the gradient at the input of the decoder [30], i.e., bypassing the argmin function (Fig. 1). This is practically feasible as the dimensions of the two vectors are equal. Thus, in the forward pass, the input image passes normally through the model while in the backward pass the vector quantization layer is skipped. This approach, however, prevents the gradient from reaching the dictionary, hence the dictionary cannot be updated. To address this issue, we modify the learning algorithm (as in Algorithm 1), in which the dictionary is trained separately through the kmeans clustering algorithm. Proceeding further in this section, we will delve into the details of this hybrid training method.
For simultaneous training of the dictionary and the network, one way is to iteratively train the dictionary and the network weights by alternating between kmeans clustering and a full run of backpropagation optimization. This approach is computationally expensive and requires a long time to converge. To reduce the computational costs, we utilize the batch Kmeans algorithm instead and integrate the clustering iterations with the optimization iterations. In each training iteration, the current batch samples are used to update the dictionary by running one single iteration of Kmeans clustering and to update the network weights by running one step of backpropagation. Given a batch of samples at iteration i, the samples are encoded passing through the encoder network and their corresponding \(z_e\)s are computed. Applying the batch Kmeans algorithm, the new cluster centers are computed and applied to update the dictionary. The new dictionary is then used for updating the network weights through back propagation (with the argmin bypass technique). The procedure continues for a fixed number of iterations or until convergence. Simultaneous training of dictionary and the network weights leads the encoder to learn a representation that takes into account the set of elements provided in the dictionary, while the dictionary is also built to be a descriptive set of quantized vectors.
In accordance with [30], another loss function is also added to CTC loss for training the network. This loss, given in. Equation (2), attempts to keep the encoder output and the dictionary elements close together. sg in Eq. (2) stands for the stop gradient operator, which prevents the gradient from backpropagation through its argument, and \(\alpha\) is a constant to be set empirically. This loss function, which is called “embedding loss” from now on, computes the Euclidean distance between the encoder output and its closest dictionary element e, and its gradient is backpropagated toward the encoder and dictionary proportional to the value of \(\alpha\). The value of e is used as the quantized value of latent variable, i.e., \(z_q\).
The first term in Eq. (2) is to pull the dictionary atoms toward the encoder output, while the second term aims to keep the output of encoder close to the dictionary atoms avoiding its arbitrary growth. As we apply the kmeans algorithm to train the dictionary, this additional loss is not necessary for training. However, according to our experiments, adding this term improves the performance of the model. On this basis, the total loss function for optimization is specified as in Eq. 3.
where
\(\beta\) in Eq. (3) is a coefficient that adjusts the weight of each term in the total loss. The initial value of \(\beta\) is set to G which gradually increases by training iteration i. T is a constant that is set to \(\) 1, empirically (Sect. 5.5). The intuition is to lessen the impact of embedding loss in the beginning, hence relying mostly on the kmeans clustering to find a descriptive dictionary. As training progress, the encoder network and the dictionary get aligned through the embedding loss.
The details of the training procedure are provided in Algorithm 1. The encoder and decoder weights are initialized by pretraining a baseline model made of the same encoderdecoder architecture, without a quantization layer. The experimental results, provided in Sect. 5.4, demonstrate that this initialization improves the performance.
4.2 Handwriting recognition model
Figure 2 illustrates the detailed architecture of the proposed HTR model. The encoder network consists of a stack of CNN networks with LeakyRelu activation functions and several maxpooling layers. All CNN networks are with stride 1. The feature map computed in the output of the encoder network is passed to the quantization layer to be discretized. The quantization is performed on the patches extracted from the feature map computing their distances with the dictionary elements. For each patch, the closest element of the dictionary is selected as its quantized value. The quantized patches are flattened over the channel dimension to become a sequence of 2D vectors to be fed to LSTM network. An FC layer is then applied to the flattened vectors to reduce their dimension. Through quantization, the representative vectors get redundant values; this dimensionality reduction is useful to compresses the information stored in the quantized vectors. The sequence of feature vectors is then passed to the decoder network where two layers of bidirectional LSTM networks are applied. The output of the BLSTMs is passed through some FC layers to project its height dimension to be equal to the size of the target alphabet (plus one for the blank character). Finally, a softmax layer is applied on the output.
5 Experiments and results
This section describes the multiple sets of experiments undertaken to analyze the performance of the proposed model for handwritten text recognition. In the first set of experiments, the model is tested on 5 different benchmark datasets of handwritten text lines, comparing its recognition result with the stateoftheart models. Another set of experiments is performed to analyze the effect of the pretraining step and hyperparameters values on the model performance. Some other experiments are also performed for ablation analysis. Finally, we provide visualizations of the quantized feature and present sample outputs of the model.
5.1 Implementation details
The model’s hyperparameters are set empirically and can be finetuned for each dataset separately. However, in our experiments, except mentioned otherwise, the following default values are used: The number of dictionary elements K is set to 128, and the size of patches extracted from the feature map is set to \(H \times 1 \times 1\), where H denotes the height of the feature map. The constants G, \(\alpha\), and T used for loss computation in Eq. 3 are set to 15, 1, and \(\) 1, respectively. The batch Kmeans learning rate, \(lr_{km}\) is set to 0.1. The network is trained using the ADAM optimizer [31] with a learning rate of 1e−3 and batch size of 64 for 20K iterations.
To improve the generalization, similar to [12], augmentation techniques are applied on the input image during training, including random projection and elastic distortion. The models are implemented in Pytorch and trained on 4 NVIDIA Tesla V100 GPUs.
The performance of the model is evaluated by two metrics: character error rate (CER) and word error rate (WER). CER (WER) is the Levenstein distance computed on the character (word) level normalized by the length of the ground truth.
5.2 Datasets
The experiments are performed on 3 datasets: IAM, ICFHR18 and IAMHistDB, where the latter itself is divided into three sets, taken from three different medieval manuscripts, called Saint Gall, Parzival and Washington.
The IAM database [32] contains 1539 English text line images, written by 657 different writers that are partitioned into 6161 training, 966 validation and 1861 test lines. There are 79 different character classes in the dataset.
The ICFHR 2018 is associated with a competition on automated text recognition [13]. The dataset consists of text images from 22 heterogeneous documents, divided into a general set (17 documents) and a documentspecific set (5 documents). At the time of writing this paper, the online evaluation engine is not accessible through the competition website. Therefore, we performed the experiments using the general set to train our model and the documentspecific set as the test set. The samples are written in modern and medieval Italian and German. The dataset provides the extracted textline images with their annotations using a 98character alphabet. The training and the test set consist of 11925 and 2878 line images, respectively.
The Washington database [33] contains 565 text line images extracted from 20 pages of George Washington letters. The dataset provides the binarized and normalized textline images, together with their annotations by an 83character length alphabet.
The Saint Gall dataset [34] has been created from a ninth century hagiography manuscript in the Latin language, from which 60 pages are extracted and segmented into 1,410 text line images. The processed and binarized textline images are provided in the dataset together with their annotations by 49 characters.
The Parzival database [33] contains 4477 text line images of gothic scripts extracted from 47 pages of a thirteenth century manuscript compiled by three copyists in medieval German language. Similar to Washington and Saint Gall, the text line images are binarized and divided into three parts of training, validation, and test set, each containing 2237, 912, and 1328, respectively. Each text line is annotated using the alphabet of 96 different characters in the database.
5.3 Performance evaluation
To evaluate the performance of the proposed discrete representation for HTR, the recognition is performed using two models: the “VQHTR” which has the same architecture as described in Sect. 4.2, and the “Baseline” model, which has the similar architecture as VQHTR without the quantization layer. The main difference between the baseline model and the VQHTR is in their continuous and discrete latent representation. The experiments are performed by applying both models on all the datasets and comparing their results with each other, as well as with other stateoftheart models. For a fair comparison, we only consider the methods that do not utilize any language models or postprocessing as part of their transcription pipeline.
Table 1 reports the results of the experiment on IAM dataset. As evident in the table, applying vector quantization significantly improves the performance of the baseline architecture, reducing its character error rate by 22%. It also outperforms the prevalent architectures in the stateoftheart methods including CNN+BLSTM, fully CNN and sequence to sequence models. Note that the performance improvement of the VQHTR model is achieved solely by embedding the quantization layer into the baseline model which has the canonical CNN+LSTM architecture. While, for instance, [35] and [36] use attention mechanism in their proposed architecture, or [37] and [38] use large networks with many layers, VQHTR is constructed of a 6layerCNN encoder, a quantization layer with a dictionary of size \(11 \times 128\), and a 2layerBLSTM decoder (see Sect. 4.2). We opted for a simple model, in order to focus more on the potential of discrete representation in handwritten text recognition. The table purposely does not include recently developed architectures based on deformable convolutions [39, 40] as they use completely different architectures, not comparable with the baseline architecture.
The baseline and VQHTR models are also tested using the ICFHR18 dataset and their recognition results are reported in Table 2, along with the results of the participants of the ICFHR2018 competition and of [38] which has an architecture similar to our baseline. Like for the IAM dataset, discrete representation significantly improves the performance of the baseline model. VQHTR outperforms the OSU system, the winner of the competition, and the RPPDI system which gained the best result for the case where images of the same document are not provided in the training. Moreover, our model achieves a lower character error rate in comparison with [38] which has a more complicated decoder compared to our model, 5 vs 2 layers BLSTM.
Table 3 shows the results of the proposed model evaluated on three datasets of IAMHistDB. Similar to the previous results on other datasets, discrete representation improves the performance of the baseline method in all three. Compared to other methods in the literature, our model has the best performance for Washington and Saint Gall. On Parzival dataset, VQHTR has a higher character error rate compared to [38]. In the ground truth of Parzival dataset, the special characters are encoded with a long sequence of digits (see Fig. 5). We use the exact same labeling, without any modifications, to train and test our model. This can explain the relatively higher performance of [38], as it uses a larger decoder, which is basically more capable of capturing these dependencies.
5.4 Effect of pretraining
The proper initialization of the encoder and decoder weights in our model has an effective role in its performance. This is mainly due to the mutual interaction between the dictionary and the encoder during training, as if the encoder outputs precise representation vectors, the dictionary computed by clustering these vectors would be precise as well. As mentioned before, we initialize the encoder and decoder networks with the trained baseline model.
To evaluate the effect of pretraining, we perform an experiment where the pretraining step is removed completely and all network parameters are initialized randomly. The model is trained starting from these randomly initialized weights. The performance of the obtained model is reported in Table 4, under “Randomly Initialized” column, along with the results of the baseline model and the pretrained VQHTR model. The results are provided for all datasets, computed on the corresponding test set.
According to the results reported, removing the pretraining step significantly reduces the performance of the model in all datasets, which does not even reach the performance of the baseline model. This implies that the added quantization layer makes the network more vulnerable to the local minima, making it critical to start from proper initial weights. Interestingly, the largest performance drop happened for IAM dataset where the CER increases more than eighteen times. This can be related to the relatively large number of writers participating in IAM dataset collection, as the style variations can make the training optimization more prone to local minima. By pretraining, the encoder computes meaningful representations, up to some tolerable precision, making it easier to optimize the dictionary while fine tuning the encoder weights.
Overall, the results of these experiments demonstrate the fact that, in the proposed model, the feature learning and dictionary learning are highly intertwined, and pretraining can be effectively used to tune the training procedure.
5.5 Effect of costs weights
\(\alpha\) and G are two of the main hyperparameters of the model that play an effective role in training the model. Here, we provide a detailed analysis of their values in order to gain a better understanding of the dynamics of the training. Recall that \(\alpha\) is a parameter that determines the weights of two terms in the embedding loss (Eq. 2), while G is a coefficient controlling the weights of the embedding loss versus CTC loss (Eq. 3). To analyze how the value of \(\alpha\) affects the model performance, we perform an experiment in which the model is trained multiple times changing the value of \(\alpha\) from 0 to 1. More specifically, we set \(\alpha\) to 0, 0.25, 0.5, 0.75 and 1 and train the model for each value separately. The experiment is performed on IAM and ICFHR18 datasets and their corresponding results are shown in Fig. 3a and b, where the character error rates obtained by each model is plotted versus the corresponding \(\alpha\) value.
The zero value of \(\alpha\) corresponds to the case where the first term of Eq. 2 has no effect on the embedding loss, and increasing its value toward one increases the contribution of this term against the second term. Recall that the first term of Eq. 2 drives the output of the encoder toward the dictionary atoms, while its second term moves the dictionary atoms toward the encoder output. Hence, \(\alpha =0\) is equivalent to the case where the encoder network is kept fix during the training and only the dictionary is updated in each iteration (together with the decoder network). On the other hand, \(\alpha = 1\) refers to the case that the encoder is updated in each back propagation step whereas the dictionary is not. Note that this does not imply the dictionary is not updated at all, since it is updated through kmeans algorithm. According to Fig. 3, for both datasets, \(\alpha = 0\) has a poorer performance compared to other cases. This is not unexpected as, in this case, the gradient does not reach the encoder network, so it is not trained. The other end of the spectrum, i.e., \(\alpha = 1\), has a low error rate indicating that the gradientbased updating of the dictionary has no much effect. \(\alpha = 0.25\) has the best performance in both datasets. However, we set \(\alpha =1\) for better understanding of the model dynamics.
In a second experiment, the effect of hyperparameter G on the model performance is evaluated. In the proposed model, hyperparameter G is a constant determining the weight of the embedding loss compared to the CTC loss. In this experiment, similar to the previous one, the model is trained multiple times using different values for G while the rest of hyperparameters are set to their default values. The experiment is performed on IAM and ICFHR18 datasets and the results are reported in Fig. 3c and d. According to these figures, by increasing the value of G from zero, the error rate decreases first and then remains constant or increases for higher values of G. We set the value of G to be equal to 15 in the final models for all datasets.
As mentioned in Sect. 4.1, we also employ an exponential decay technique to gradually increase the value of \(\beta\) during training. Figure 3e and f, demonstrates how the decay parameter, \(\tau\) in Eq. 4, affects the model performance on IAM and ICFHR18. We also test for \(\tau\) with positive values, i.e., increasing \(\beta\) by iteration. According to the presented curves, the best performance is achieved for \(\tau = 1\), which we take as its default value for training the models in this paper.
5.6 Ablation study
Compared to the baseline model, VQHTR employs a dictionary to quantize the encoder output and a fully connected network to reduce the dimension of the quantized feature map to be fed to LSTM (see Sect. 4.2). To examine the effect of these two added parts separately, in two separate experiments, we remove each part one at a time, train the reduced model, and compute their recognition results on the validation set. For each of the experiments, we also made the necessary changes in the reduced model to make it work properly. The results of these experiments are reported in Table 5, marked as “Only FC” and “Only Quantization,” respectively. For comparison, the result of our model, employing both parts together is also provided.
In another experiment, we investigate the proposed training strategy. Compared to the quantization algorithm introduced in [30], where the dictionary is trained only through backpropagation, here we utilize the kmeans algorithm as well. To clarify the effect of kmeans clustering, Table 5 also provides the result for the case where the kmeansbased update of the dictionary is eliminated, and the model is trained solely via backpropagation. According to the table, our algorithm improves the performance of the model considerably.
5.7 Visualization and sample results
To gain a better understanding of the procedure taking place in the quantization layer, a visualization of feature vector discretization is provided in Fig. 4b for two samples taken from IAM and ICFHR18 datasets. For each sample, the input textline image is shown along with two other images representing the feature vectors in one channel of the feature map, before and after discretization, i.e., input and output of the quantization layer. For a better display, instead of the full images, cropped pieces of them are shown here. Each column in feature images corresponds to one vector in the feature map which is discretized in the quantization layer. Analyzing feature images before and after discretization provides a view on how the quantization layer changes the feature vectors. As expected, the discretized feature map contains a number of patterns repeated along the sequence, reducing large pixel variations in the continuous feature map. To check the effect of this discretization on the recognition result, the final output of the model computed using each feature map is also provided in the image. Each column of the feature maps is assigned a character, written on top of it, which shows the model output in the corresponding position. In the case of a continuous feature map, the recognition result is computed by directly feeding the feature map to the decoder, i.e., bypassing the quantization layer. Comparing the recognition results of the discrete and continuous feature maps, some correct and false predictions are specified with green and red boxes, respectively. “ _ ” denotes the blank. The final recognition results after CTC decoding, i.e., “predictions”s, are also provided. In addition, Fig. 5 provides more samples taken from all datasets with their corresponding recognition results computed by both VQHTR and baseline models. The words colored in red are the ones with at least one character transcribed wrongly.
6 Discussion
The experimental results on various datasets demonstrate that discretizing the latent variables can improve the accuracy of conventional CNN+RNN architectures when applied for a handwritten text recognition. This improvement is significant enough that in some databases, the model outperforms larger and more advanced models. It is noteworthy that this improvement is achieved by adding extra constraints to the latent variables, forcing them to take on a limited number of dictionary atoms. This highlights that the fact that handwritten symbols can be represented by a limited set of vectors can be leveraged to regularize the network training.
However, the proposed approach also has some limitations compared to conventional methods. Firstly, it introduces additional hyperparameters that need to be finetuned for each dataset. These hyperparameters include the cost coefficients and the number of dictionary atoms, which need to be determined through experimentation. The number of vectors used for constituting the dictionary is an effective hyperparameter that controls its capability in representing the input images. The number of elements should be large enough to provide the model with enough flexibility to represent main variations, but not so large that it increases trainable parameters unnecessarily. We observed that increasing the number of dictionary atoms improves the performance to some point, after which performance remains constant and then decreases with further increases. This can be attributed to the fact that when the dictionary is too small, it does not have enough elements to construct an adequate representation of the input images. Conversely, overly large dictionaries provide the model with excessive flexibility, making it more prone to overfitting. An optimal number of dictionary atoms is between these two extremes. In our experiments, we finetuned this value for one dataset and used the same value for other datasets. Finetuning this hyperparameter for each dataset can improve the results reported.
Secondly, our model necessitates a pretraining stage before the main training. This warmingup step has a significant impact on the model’s performance and cannot be skipped. An important aspect to consider here is that the main training phase begins with a set of parameters that have already been trained for a similar architecture (excluding the quantization layer), on the same task and same data. The only difference is the constraint imposed by the quantization layer, forcing the latent variables to take on one of the dictionary atoms. This restriction finetunes the encoder–decoder parameters, resulting in improved accuracy.
7 Conclusion
Finding an appropriate representation is a crucial step in handwritten text recognition. In this paper, we used a discrete image representation in place of the prevalent continuous representation in DNNbased HTR models. A novel encoder–decoderbased architecture has been created where a quantization layer has been embedded to discretize the latent variables. The results of multiple experiments performed have indicated an effectiveness of discrete representations improving modern and historical handwriting text recognition models.
The discretization layer is applied on the latent vector of the encoder–decoder architecture. Similarly, it can be utilized in other layers of the network to analyze the quantization effect on various representation levels. In the current model, the discretization is applied over the patches of rectangular shapes extracted from the encoder output, whereas the primitive components of a text image can have flexible shapes extended differently over the image.
Data availibility statement
The IAM and IAM HisDB datasets are available in https://fki.tic.heiafr.ch/databases. The ICFHR2018 dataset is available in Zenodo with the identifier https://doi.org/10.5281/zenodo.1442182.
References
Breuel TM (2017) High performance text recognition using a hybrid convolutionallstm implementation. In: 2017 14th IAPR international conference on document analysis and recognition (ICDAR), IEEE, vol 1, pp 11–16
Bluche T, Louradour J, Messina R (2017) Scan, attend and read: Endtoend handwritten paragraph recognition with mdlstm attention. In: 2017 14th IAPR international conference on document analysis and recognition (ICDAR), IEEE, Vol 1, pp 1050–1055
Poulos J, Valle R (2021) Characterbased handwritten text transcription with attention networks, Neural Computing and Applications, pp 1–11
Vinciarelli A (2002) A survey on offline cursive word recognition. Pattern Recognit 35(7):1433–1446
Surinta O, Karaaba MF, Schomaker LR, Wiering MA (2015) Recognition of handwritten characters using local gradient feature descriptors. Eng Appl Artif Intell 45:405–414
Bolelli F, Borghi G, Grana C (2017) Historical handwritten text images word spotting through sliding window hog features. In: International conference on image analysis and processing, Springer, pp 729–738
Zhou MK, Zhang XY, Yin F, Liu CL (2016) Discriminative quadratic feature learning for handwritten CHinese character recognition. Pattern Recognit 49:7–18
Shaikh MA, Chauhan M, Chu J, Srihari S (2018) Hybrid feature learning for handwriting verification. In: 2018 16th international conference on frontiers in handwriting recognition (ICFHR), IEEE, pp 187–192
Hafemann LG, Oliveira LS, Sabourin R (2018) Fixedsized representation learning from offline handwritten signatures of different sizes. Int J Doc Anal Recogn (IJDAR) 21(3):219–232
Davoudi H, Fiorucci M, Traviglia A (2021) Ancient document layout analysis: autoencoders meet sparse coding. In: 2020 25th international conference on pattern recognition (ICPR), IEEE, pp 5936–5942
Voigtlaender P, Doetsch P, Ney H (2016) Handwriting recognition with large multidimensional long shortterm memory recurrent neural networks. In: 2016 15th international conference on frontiers in handwriting recognition (ICFHR), IEEE, pp 228–233
Yousef M, Hussain KF, Mohammed US (2020) Accurate, dataefficient, unconstrained text recognition with convolutional neural networks. Pattern Recogn 108:107482
Strauß T, Leifert G, Labahn R, Hodel T, Mühlberger G (2018) Icfhr2018 competition on automated text recognition on a read dataset. In: 2018 16th international conference on frontiers in handwriting recognition (ICFHR), IEEE, pp 477–482
Artieres T, Marukatat S, Gallinari P (2007) Online handwritten shape recognition using segmental hidden Markov models. IEEE Trans Pattern Anal Mach Intell 29(2):205–217
Chherawala Y, Roy PP, Cheriet M (2015) Feature set evaluation for offline handwriting recognition systems: application to the recurrent neural network model. IEEE Trans Cybern 46(12):2825–2836
Shi CZ, Gao S, Liu MT, Qi CZ, Wang CH, Xiao BH (2015) Stroke detector and structure based models for character recognition: a comparative study. IEEE Trans Image Process 24(12):4952–4964
Madhvanath S, Govindaraju V (2001) The role of holistic paradigms in handwritten word recognition. IEEE Trans Pattern Anal Mach Intell 23(2):149–164
Davoudi H, Cheriet M, Kabir E (2016) Lexicon reduction of handwritten Arabic subwords based on the prominent shape regions. Int J Doc Anal Recogn (IJDAR) 19(2):139–153
Koerich AL, Sabourin R, Suen CY (2005) Recognition and verification of unconstrained handwritten words. IEEE Trans Pattern Anal Mach Intell 27(10):1509–1522
Davoudi H, Kabir E (2014) Lexicon reduction for printed Farsi subwords using pictorial and textual dictionaries. Int J Doc Anal Recogn (IJDAR) 17(4):359–374
Plötz T, Fink GA (2009) Markov models for offline handwriting recognition: a survey. Int J Doc Anal Recogn (IJDAR) 12(4):269
Graves A, Fernández S, Gomez F, Schmidhuber J (2006) Connectionist temporal classification: labelling unsegmented sequence data with recurrent neural networks. In: Proceedings of the 23rd international conference on Machine learning, pp 369–376
Shi B, Bai X, Yao C (2016) An endtoend trainable neural network for imagebased sequence recognition and its application to scene text recognition. IEEE Trans Pattern Anal Mach Intell 39(11):2298–2304
Li H, Wang P, Shen C, Zhang G (2019) Show, attend and read: a simple and strong baseline for irregular text recognition. In: Proceedings of the AAAI conference on artificial intelligence, vol 33, pp 8610–8617
Wigington C, Tensmeyer C, Davis B, Barrett W, Price B, Cohen S (2018) Start, follow, read: Endtoend fullpage handwriting recognition, in: Proceedings of the European conference on computer vision (ECCV), pp 367–383
Hinton GE, Salakhutdinov RR (2006) Reducing the dimensionality of data with neural networks. Science 313(5786):504–507
Hoffer E, Ailon N (2015) Deep metric learning using triplet network. In: International workshop on similaritybased pattern recognition, Springer, pp 84–92
Koch G, Zemel R, Salakhutdinov R, et al (2015) Siamese neural networks for oneshot image recognition. In: ICML deep learning workshop, vol 2, Lille
Jang E, Gu S, Poole B (2016) Categorical reparameterization with GumbelSoftmax, Preprint arXiv:1611.01144
Oord Avd, Vinyals O, Kavukcuoglu K (2017) Neural discrete representation learning. Preprint arXiv:1711.00937
Kingma DP, Ba J (2014) Adam: a method for stochastic optimization. Preprint arXiv:1412.6980
Marti UV, Bunke H (2002) The IAMdatabase: an English sentence database for offline handwriting recognition. Int J Doc Anal Recogn 5(1):39–46
Fischer A, Keller A, Frinken V, Bunke H (2012) Lexiconfree handwritten word spotting using character HMMs. Pattern Recogn Lett 33(7):934–942
Fischer A, Frinken V, Fornés A, Bunke H (2011) Transcription alignment of latin manuscripts using hidden Markov models. In: Proceedings of the 2011 workshop on historical document imaging and processing, pp 29–36
Sueiras J, Ruiz V, Sanchez A, Velez JF (2018) Offline continuous handwriting recognition using sequence to sequence neural networks. Neurocomputing 289:119–128
Wang T, Zhu Y, Jin L, Luo C, Chen X, Wu Y, Wang Q, Cai M (2020) Decoupled attention network for text recognition. In: Proceedings of the AAAI conference on artificial intelligence, vol 34, pp 12216–12224
Yousef M, Bishop T. E (2020) Origaminet: weaklysupervised, segmentationfree, onestep, full page text recognition by learning to unfold. In: Proceedings of the IEEE/CVF conference on computer vision and pattern recognition, pp 14710–14719
Aradillas JC, MurilloFuentes JJ, Olmos PM (2021) Boosting offline handwritten text recognition in historical documents with few labeled lines, IEEE Access
Retsinas G, Sfikas G, Nikou C, Maragos P (2021) Deformationinvariant networks for handwritten text recognition. In: 2021 IEEE international conference on image processing (ICIP), IEEE, pp 949–953
Cojocaru I, Cascianelli S, Baraldi L, Corsini M, Cucchiara R (2021) Watch your strokes: improving handwritten text recognition with deformable convolutions. In: 2020 25th international conference on pattern recognition (ICPR), IEEE, pp 6096–6103
Pham V, Bluche T, Kermorvant C, Louradour J (2014) Dropout improves recurrent neural networks for handwriting recognition. In; 2014 14th international conference on frontiers in handwriting recognition, IEEE, pp 285–290
Bluche T (2016) Joint line segmentation and transcription for endtoend handwritten paragraph recognition. Adv Neural Inf Process Syst 29:838–846
Puigcerver J (2017) Are multidimensional recurrent layers really necessary for handwritten text recognition? In: 2017 14th IAPR international conference on document analysis and recognition (ICDAR), vol 1, IEEE, pp 67–72
Wigington C, Stewart S, Davis B, Barrett B, Price B, Cohen S (2017) Data augmentation for recognition of handwritten words and lines using a CNNLSTM network. In: 2017 14th IAPR international conference on document analysis and recognition (ICDAR), IEEE, vol 1, pp 639–645
Dutta K, Krishnan P, Mathew M, Jawahar C (2018) Improving CNNRNN hybrid networks for handwriting recognition. In: 2018 16th international conference on frontiers in handwriting recognition (ICFHR), IEEE, pp 80–85
Zhang Y, Nie S, Liu W, Xu X, Zhang D, Shen HT (2019) Sequencetosequence domain adaptation network for robust text image recognition. In: Proceedings of the IEEE/CVF conference on computer vision and pattern recognition, pp 2740–2749
Grieggs S, Shen B, Rauch G, Li P, Ma J, Chiang D, Price B, Scheirer W (2021) Measuring human perception to improve handwritten document transcription, IEEE Transactions on Pattern Analysis and Machine Intelligence
Tassopoulou V, Retsinas G, Maragos P (2021) Enhancing handwritten text recognition with ngram sequence decomposition and multitask learning. In: 2020 25th international conference on pattern recognition (ICPR), IEEE, pp 10555–10560
Abdallah A, Hamada M, Nurseitov D (2020) Attentionbased fully gated CNNBGRU for Russian handwritten text. J Imaging 6(12):141
Acknowledgements
We gratefully acknowledge the Support Team of the ‘Franklin’ HPC infrastructure of the Istituto Italiano di Tecnologia for its assistance. We also take this opportunity to thank Stephen A. White for his constructive criticism on the manuscript draft.
Funding
Open access funding provided by Istituto Italiano di Tecnologia within the CRUICARE Agreement.
Author information
Authors and Affiliations
Corresponding author
Ethics declarations
Conflicts of interest
The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.
Additional information
Publisher's Note
Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.
Rights and permissions
Open Access This article is licensed under a Creative Commons Attribution 4.0 International License, which permits use, sharing, adaptation, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons licence, and indicate if changes were made. The images or other third party material in this article are included in the article's Creative Commons licence, unless indicated otherwise in a credit line to the material. If material is not included in the article's Creative Commons licence and your intended use is not permitted by statutory regulation or exceeds the permitted use, you will need to obtain permission directly from the copyright holder. To view a copy of this licence, visit http://creativecommons.org/licenses/by/4.0/.
About this article
Cite this article
Davoudi, H., Traviglia, A. Discrete representation learning for handwritten text recognition. Neural Comput & Applic 35, 15759–15773 (2023). https://doi.org/10.1007/s00521023084459
Received:
Accepted:
Published:
Issue Date:
DOI: https://doi.org/10.1007/s00521023084459