C OMPACT E NCODING OF W ORDS FOR E FFICIENT C HARACTER - LEVEL C ONVOLUTIONAL N EURAL N ETWORK T EXT C LASSIFICATION
Anonymous authors
Paper under double-blind review
A BSTRACT
This paper reports the empirical exploration of a novel approach to encode words using compressing inspired techniques for use on convolutional neural networks at character-level.
This approach reduces drastically the number of parameters to be optimized using deep learning, resulting in competitive classiﬁcation accuracy values in only a fraction of the time spent by characters level convolutional neural networks, enabling training in simpler hardware.
I NTRODUCTION
Document classiﬁcation is one of the principal tasks addressed in the context of natural language processing (Sebastiani, 2002).
It implies associating a document —or any text fragment, for that matter— with a category or label relying on their content.
The increasing availability of texts in digital form, especially through the Internet, has called for the development of statistical and artiﬁcial intelligence tools for automating this process.
Spam detectors, sentiment analysis, news archiving, among many others, demand high-quality text classiﬁers.
Work on document classiﬁcation encompasses a broad range of approaches (see (Sebastiani, 2002;
Aggarwal & Zhai, 2012; Hotho et al., 2005; Kosala & Blockeel, 2000)).
An important portion of those approaches relies on a representation that handles words as the atomic element of text.
Consequently, those methods carry out their analysis through statistics of words occurrence (Zhang et al., 2015).
However, the variability of words and structures belonging to a language makes this task difﬁcult.
That is why, such models have a superior performance in speciﬁc domains, where the vocabulary can be restricted to a relatively small number of words, possibly chosen by a specialist.
Furthermore, such modeling becomes speciﬁc to a language, causing the replication process in another language to be carried out from scratch (Zhang et al., 2015).
In recent years, we have experienced a revolution in the machine learning with the advent of deep learning methods (Goodfellow et al., 2016).
The development of convolutional neural networks (CNNs) (LeCun et al., 1998) coupled with the popularization of parallel computing libraries (e. g. Theano (Bergstra et al., 2010), Tensorﬂow (Abadi et al., 2015), Keras (Chollet et al., 2015), etc.)
that simplify general-purpose computing on graphics processing units (GPGPU) (Mittal & Vetter, 2015) has been successful in tackling image classiﬁcation problem (Krizhevsky et al., 2012) quickly becoming the state of the art of the ﬁeld.
The success of CNNs in the image classiﬁcation domain has prompted the interest to extend the deep learning principles to the document classiﬁcation domain.
Some existing methods have been updated but the clear majority are still based on the tokenization of words and the inference of their statistics.
Bag of Words (BOW) (Johnson & Zhang, 2014) and word2vec (Mikolov et al., 2013) are some of the most popular strategies.
The replication of image classiﬁcation success in the documents domain faces as main challenge the difﬁculty of representing text as numerical tensors.
In a groundbreaking paper, Zhang et al. (2015) suggested an approach that considers the characters as the atomic elements of a text. This representation provides a robust, language-independent representation of texts as matrices, that were used as inputs of different CNNs.
Their experimental results showed that this approach was able to attain and, in some cases, improve the state of the art results in complex text classiﬁcation problems. In spite of that, the impact of this idea was hampered by the large computational demands of the approach, since its training can took days per epoch in complex problems.
In this paper, we propose an efﬁcient character-level encoding of text derived from the tagged Huffman (Silva de Moura et al., 2000) information compression technique that takes into account the character frequency to assign shorter codes to the most frequently used ones. This novel text encoding makes the idea put forward by Zhang et al. (2015) more computationally accessible by reducing its training requirements in terms of time and memory.
The proposed encoding makes possible to represent larger portions of texts in a less sparse form while preserving the ability to encode any word, even those not present in the training dataset ones. In order to study the impact of this encoding, we coupled it with two convolutional neural networks architectures. The experimental studies performed showed that we managed to achieve a performance similar or in some cases better than the state of the art at a fraction of the training time even if we employed a simpler hardware setup.
Our main contribution is to show that this novel character-level text encoding produces a reduced input matrix, leading to a substantial reduction in training times while producing comparable or better results in terms of accuracy than the original approach by Zhang et al. This opens the door to more complex applications, the use of devices with lower computational power and the exploration of other approaches that can be coupled with input representation. The rest of the paper is structured as follows.
In the next section, we deal with the theoretical foundations and motivation that are required for the ensuing discussions. There we also analyze the alternatives to character-level text compression that were taken into account for producing our proposal. After that, in Section 3, we describe the encoding procedure and the neural network architectures that will take part of the experiments. Subsequently, in Section 4, we replicate the experiments of Zhang et al.
(2015) in order to contrast our proposal with theirs under comparable conditions.
Finally, in Section 5, we provide some ﬁnal remarks, conclusive comments and outline our future work directions.
The success in using Convolutional Neural Networks (CNNs) (LeCun et al., 1998) in image classiﬁcation (Krizhevsky et al., 2012) ﬂourish with the development of many libraries (Chetlur et al., 2014;
Chollet et al., 2015; Bergstra et al., 2010), techniques and hardware.
The effort to use CNNs for text classiﬁcation tasks is justiﬁed by the possibility of appropriating these tools for obtaining better results and more robust algorithms, facilitating the use of the same approach for several applications.
There are two usual approaches to use CNNs for handling textual information: the (i) bag of words (BoW) (Johnson & Zhang, 2014) and (ii) word2vec (Mikolov et al., 2013) approaches.
In the case of BoW and some of its variants, for representing each word in a vocabulary of size N , a digit 1 is placed in the correspondent position of that word in a 1 × N vector, all others positions remaining with digit 0.
Since natural languages usually have a large vocabulary, a limited subset of the vocabulary must be used in order to make viable to perform the necessary computations in terms of memory requirements.
The chosen subset of the vocabulary must be representative of the texts.
Therefore, in practical problems, a great deal of attention is devoted to this matter.
In particular, it is common to involve an application domain specialist or use some kind of word frequency statistic or relevance metric, where the most frequent and rare words are excluded.
In the word2vec approach, each word is projected via a metric embedding of ﬁxed size, representing its co-occurrence in a large corpus of text in the same language of the texts of interest.
It is possible to use pretrained vectors or readjust the representation with new words.
The main problem with both strategies is that it does not allows to represent words that are not in the training dataset.
Typos, spelling errors, mixed up letters and text written in languages with a complex structure (declensions, conjugations, etc.) are completely ignored.
Establishing the character as the basic unit of text formation provides a better opportunity to be robust to typos, acceptance of neologisms, and other textual forms as equations and chemical formulas, abbreviations and idiosyncrasies of written language on the internet, such as emoticons, slang and dialects of the online world, etc.
Assuming the word as a base item, much of this ability is lost, especially when models assume that text producers use a formal language.
Zhang et al. (2015) put forward an important innovation in this regard.
They represent text as a sequence of characters, not words.
Consequently, they are capable of reducing the vocabulary of symbols to the size of the alphabet (69 in the case of the paper) and thus allowing the use of one-hot encoding (Harris & Harris, 2012).In the paper, they represented a text as a matrix of size 1014 ×where each row corresponds to a position in the text sequence and columns with the presence or not of a given character.
Therefore, a row with a 1 in a given column indicates that the presence of the corresponding character in that point of the text.
With this representation on hand, they applied a CNN and obtained results competitive with other techniques, and in some cases improving the state of the art. However, the main drawback of its large computational requirements, that in some cases called for one or two days per training epoch. The results obtained by them suggest that language, and therefore, text, can be treated as a sequence of signals, like any other (Zhang et al., 2015).
However, the training times and the dimension of the matrices to be computed are still obstacles to the most effective use of the method.
That is why a better encoding of text could be a right path towards a substantial improvement if this issue.
Searching for a way to reduce these training time while retaining the ﬂexibility and power of character-level convolutional to classify text, we found a way to better encode texts.
Our approach, with competitive accuracy, achieve a signiﬁcant reduction in time execution from hours to minutes and from days to hours, by epoch.
To achieve this performance in execution, our approach consisted of two elements:
• Obtaining a shorter representation : At ﬁrst, we though of using some form of encoding each character, and use the same approach of Zhang et
al. (2015) but we realize that using a variable length encoding for each word could be more efﬁcient.
To do this we need a way to encode each char, generating distinct concatenated code for representing each word and that words with the same preﬁx were near each other, especially to respond well to declensions.
• Obtaining a sparse representation :
To take full advantage of libraries of tensor multiplications like NVidia CuDNN (Chetlur et al., 2014), we need a representation that was sparse, so our code should be composed of many 0s and a few 1s. 3. C OMPRESSED R EPRESENTATIONS
Although the Huffman encoding (Huffman, 1952) yields shortest possible, it does not generate unique representations once we concatenate encoded characters to form a word.
We investigated encoding of Brisaboa et al.
and found promising alternatives.
Our approach is based on the Tagged Huffman encoding (Silva de Moura et al., 2000), where a pair of ‘0’ digits is the signal and the digit ‘1’ is the tag of beginning and end code, the only difference is that for our approach, we need a shorter version to reduce the size of input matrix, so we choose to use only one digit 0 instead of two for each char, marking the beginning and the end of each char code with a digit 1, the same way.
As in the approach by Silva de Moura et al.
, the coding we employ has the following advantages (Brisaboa et al., 2003):
No character code is a preﬁx of another, that is, the match is one-to-one. 2.
It allows a direct search, that is, to search for a word in an encoded document, just encode the word and use traditional methods of comparing strings with the encoded document.
This encoding approach is a compression technique, so it also allows saving already encoded text documents permanently using a binary system, requiring less storage space. [Table]
These advantages become attractive especially if the goal is to extract knowledge about ﬁles in a repository to perform various classiﬁcations on different dimensions with the same ﬁles.
A possible advantage of this encoding over others strategies that use a word as an atomic representation of text is better respond to unseen words on training data, once that the network at least have some preﬁx to guess the meaning of the word, the same way we humans do.
This is especially interesting in languages where there are a lot of declensions like Portuguese, Spanish, Italian, French,
Russian, German, Arabic and Turkish, for example.
The coding procedure is not restricted to any size of vocabulary, the only problem is that less frequent characters will generate bigger codes, consequently, bigger encoding matrix.
If your database has a lot of them, you could use a higher word code size.
Our main contribution is demonstrate that such approach reduces the dimensionality of the encoded matrix, substantially reducing training time and allow the use of devices with lower computational power, remaining with competitive accuracy.
3. E NCODING P ROCEDURE
In all of our experiments, we used the following procedure to encode words:
• Obtaining a character frequency rank : We read the text database and count the frequency of each character, generating a list sorted by frequency of occurrence.
Then we create a rank with only the relative positions of the characters.
For a given language, this rank is quite stable since only the order of the rank is used.
This means that if all documents are in the same idiom, this procedure can be replaced by a list with the characters rank of frequency for that language.
• Creating a mapping from character to compress code : To encode each character, we insert the digit 0 in the same amount of the rank position of the character, between a 1 digit to signal the begin and another 1 digit to signal the end of the code.
Table 1 have some examples of encoded characters.
To encode each word, we just concatenate the codes of each character.
As an example, we provide in Table 2 some examples of plain text words and their corresponding encoding.
Given a document, we consider that it is composed of words, being those any set of characters limited by the space character.
This means ‘word’ could be math equations, web addresses, L A TEX code, computer programming commands, etc.
In Table 2 we can see that this encoding could represent words with the same preﬁx in vectors that have same initial coordinates.
Slangs like tl;dr : too long, TEXT ENCODED TEXT science scientist art artist tl;dr u  e a did not read and u2 : you too as well mathematical expressions like e a could be manipulated.
In the matrix representation of the document, each row represents a properly encoded word.
The code for each word is then embedded in a matrix of number of words × code size with its ﬁrst symbol in column 1.
Columns that were not occupied are padded with 0, larger codes are represented up to the chosen limit.
Unoccupied lines are ﬁlled with 0 and larger documents are represented only up to the chosen maximum number of words, ignoring the last remaining ones.
As an example, we represent a document in an 8 × 65 matrix in Figure 1.
In the example in Figure 1 we used a 8 × 65 matrix (520 elements) to encode the text with a certain amount of slack.
At the very least, we would need 7 × 64 (448 elements).
In contrast, the approach of Zhang et al. (2015) would employ at least 69 × 32 (2208) elements to represent the same sentence.
In our experiments, 256 coordinates were enough to represent 99.5% of the words from one of the databases studied.
In all datasets studied in this paper, we choose 128 as a limit of words to represent a document, encoding each text in a 128 × 256 matrix. 3.2. C ONVOLUTIONAL N ETWORK M ODEL
As mentioned before, this work was prompted by the results of Zhang et al.
In their original approach, they encode each character using one-hot encoding in a vocabulary of 69 elements.
The non-space characters are letters, numbers and punctuation. The model is composed of 9 layers, 6 of convolutions and 3 fully connected. Their architecture is described in Table 3. They used stochastic gradient descent (SGD) with a minibatch of size 128, using momentum 0.
and initial step size 0.01 which is halved every 3 epochs for 10 times.
So, their results were obtained in at least 30 epochs.
3. N EURAL N ETWORK A RCHITECTURES
To verify the efﬁciency of the encoding procedure, we realized 2 experiments, named CNN1 and
CNN2:
[Table]
[Figure]
3. CNN1 TOPOLOGY
At ﬁrst, we choose a network architecture that we usually use to classify text using an embedding created by word2vec (Mikolov et al., 2013), the only difference is that instead of 300 features, we reduce the input size to 256.
This architecture we named CNN1.
It is based on concatenation of convolutions in a shallow way, inspired by work of Kim (2014), who achieve state of the art results for some databases.
We trained this model for 5 epochs.
The neural network architecture is summarized in Figure 2a as a diagram.
3. CNN2 TOPOLOGY
Prompted by the positive outcome of CNN1, we decided to investigate others possible architectures.
We created another shallow but wide convolution architecture following the recommendations of
[Table]
Depends on the problem
Zhang & Wallace (2015) for choosing parameters, executing training on dataset ag news, for being the smallest of our test datasets.
This architecture is composed by:
• Convolution width ﬁlter : a combination of region sizes near the optimal single best region size outperforms using multiple region sizes far from the optimal single region size (Zhang & Wallace, 2015).
We scan the width from 1 to 7 comparing accuracy performance.
In these evaluations, the convolution of width 1 was a better option.
• Pooling size : max pooling consistently performs better than alternative strategies for the task of sentence classiﬁcation (Zhang & Wallace, 2015).
E XPERIMENTAL S TUDY
An essential part of this work is to contrast our proposal both within the context of character-level text classiﬁcation and with other state-of-the-art approaches.
The databases used were the same as those cited in an article by Zhang et al.
(2015), where there is an extensive description of them.
1 A detailed analysis of these datasets is out of the scope of this paper, instead, we will only summarize the main characteristics:
• Ag news : categorized news articles from more than 2000 news sources.
Four classes (World, Sports, Business, SciTech).The dataset contains 120k train samples and 7.6k test samples equally distributed (Zhang et al., 2015).
• Sogou news : categorized news articles originally in Chinese.
Zhang et al.
(2015) applied a pypinyin package combined with jieba Chinese segmentation system to produce Pinyin – a phonetic romanization of Chinese.
Five classes (sports, ﬁnance, entertainment, automobile and technology).
The dataset contains 450k train samples and 60k test samples equally distributed (Zhang et al., 2015).
• DBpedia : title and abstract from Wikipedia articles available in DBpedia crowd-sourced community (Lehmann et al., 2015).
Fourteen 14 nonoverlapping classes from DBpedia [-
-]2014.
The dataset contains 560k train samples and 70k test samples equally distributed (Zhang et al., 2015).
• Yelp full : sentiment analysis from the Yelp Dataset Challenge in 2015 2 .
Five classes representing the number of stars a user has given.
The dataset contains 560k train samples and 38k test samples equally distributed.
(Zhang et al., 2015).
• Yelp full : sentiment analysis from the Yelp Dataset Challenge in 2015 2 .
Rating of 1 andstars are represented as Bad and 4 and 5 as Good.
The dataset contains 560k train samples and 50k test samples equally distributed.
(Zhang et al., 2015).
• Yahoo answers : questions and their answers from Yahoo Answers.
Ten classes (Society & Culture, Science & Mathematics, Health, Education & Reference, Computers & Internet, Sports, Business & Finance, Entertainment & Music, Family & Relationships, Politics & Government).
Each sample contains question title, question content and best answer.
The dataset contains 1400k train samples and 60k test samples (Zhang et al., 2015).
• Amazon full : sentiment analysis from Amazon review dataset from the Stanford Network Analysis Project (SNAP) (McAuley & Leskovec, 2013).
Five classes representing the number of stars a user has given.
The dataset contains 3000k train samples and 650k test samples.(Zhang et al., 2015).
• Amazon polarity : sentiment analysis from Amazon review dataset from the Stanford Network Analysis Project (SNAP) (McAuley & Leskovec, 2013).
Two classes, rating of 1 and 2 stars are represented as Bad and 4 and 5 as Good.
Dataset contains 3000k train samples and 650k test samples.(Zhang et al., 2015).
The dataset contains 3600k train samples and 400k test samples equally distributed.(Zhang et al., 2015).
The baseline comparison models are the same of Zhang et al.
(2015) where there is an extensive description of them, we just reproduce their results, the only difference is that they report loss error and for better comprehension, we translated it to accuracy.
In Zhang et al.
(2015) there is an extensive description of them.
In this paper, we just summarize the main information:
• Bag of Words (BoW) and its term-frequency inverse-document-frequency (BoW TFIDF) :
For each dataset, they selected 50,000 most frequent words from the training subset.
For the normal bag-of-words, they used the counts of each word as the features and for the TFIDF they used the counts as the term-frequency (Zhang et al., 2015).
• Bag-of-ngrams (Ngrams) and its TFIDF (Ngrams TFIDF) :
The bag-of-ngrams models were constructed by selecting the 500,000 most frequent n-grams (up to 5-grams) from the training subset for each dataset.
The feature values were computed the same way as in the bag-of-words model (Zhang et al., 2015).
• Bag-of-means on word embedding : an experimental model that uses k -means on word2vec (Mikolov et al., 2013) learned from the training subset of each dataset, and then used these learned means as representatives of the clustered words.
Took into consideration all the words that appeared more than 5 times in the training subset.
The dimension of the embedding is 300.
The bag-of-means features are computed the same way as in the bag-of-words model.
The number of means is 5000 (Zhang et al., 2015).
• Long Short Term Memory (LSTM) : The LSTM (Mikolov et al., 2013) model used in our case is word-based, using pretrained word2vec embedding of size 300.
The model is formed by taking a mean of the outputs of all LSTM cells to form a feature vector, and then using multinomial logistic regression on this feature vector.
The output dimension is(Zhang
et al., 2015).
For all the experiments, we used the environment and parameters settings listed in Table 4.
Besides the encoding procedure, we do not use any preprocessing strategy except the use of lowercase letters.
No data enhancement technique was employed.
All the results and comparison with traditional models and the approach of Zhang et al.
(2015) is shown in Table 5.
On Table 6, we did a time execution comparison, based on reports available by
Zhang et al. (2015).
The main objective of this research was to evaluate the possibility of using a coding approach that contemplated the construction of words using characters as basic tokens. Our main contribution is [Table] [Table]
Small 84.
Ours CNN 87. CNN 91. demonstrate that such approach allows reducing the dimensionality of the encoding matrix, allowing substantial shorter optimization times and the use of devices with lower computational power.
Some datasets of text have peculiarities that were not addressed by word frequency methods (i.e. BoW and word2vec), like declensions and new vocabulary.
The article of Zhang et al. (2015) was a great innovation in this regard.
However, the training times are still obstacles to the most effective use of the technique.
We thought of a better representation should be a solution.
To make a comparison, perform the training of architecture CNN1 with an output of 4 classes make necessary to optimize 1,837,188 parameters.
As a comparison, in the architecture suggested by
Zhang et al. (2015) it is necessary to optimize 11,337,988 parameters (Zhang et al., 2015).
As one of our concerns was to make our proposal usable on commodity hardware we focused our studies in that hardware conﬁguration.
The major bottleneck for analyzing this large amount of matrix-encoded text is the need for intensive use of RAM.
Our approach generates a 128 ×matrix, smaller than the 1014 × 69 generated by Zhang et al. In spite of that, a large set of them quickly occupies the available RAM memory on a regular computer.
On the machine we used, there were 16 GB available, which is not uncommon in modern personal computers.
Therefore, the use of generators to control the number of matrices generated and sent to GPU is an important detail in the implementation of this optimization algorithm.
If your computer has only 8 GB of RAM or less, you should reduce the number of superbatch to ﬁt the memory.
The results that we obtained are very competitive with the approach o Zhang et al.
(2015) and traditional techniques.
Observing our results, we see even that we could ﬁnd parameters that result [Table] in excellent performance on ag news dataset [Table]
following the suggestions of Zhang & Wallace (2015).
One of advantage of a faster algorithm is that if your dataset is not so big, you could scan the feature width to ﬁnd a solution that optimizes accuracy.
Another advantage is the possibility to realize kfolds validation [Table] to have a better perspective on how well it will perform for your speciﬁc dataset on real life.
We are certain that our algorithm implementation could be even faster.
For our inability, we could not ﬁnd a way to make CPU and GPU working in parallel.
Using a GPU Geforce 1080ti, each of the superbatch of 10000 arrays have its weights updated in 30 seconds.
Only 6 seconds is consumed by GPU, another 24 seconds is spent in encoding all the matrix and delivery it on GPU.
Using a multithread strategy could help in this regard [Table]
The results obtained strongly indicate that the use of this coding is a possibility.
We emphasize that we used is a fairly simple network, enough to demonstrate the feasibility of the encoding approach with the time and computational resources that we have.
Possibly there are several architectures that can generate better results.
In addition, the dimensionality reduction provided enables several architectures to be veriﬁed in a reasonable time.
F INAL R EMARKS
In this paper, we proposed an efﬁcient character-level encoding of text derived from the tagged
Huffman (Silva de Moura et al., 2000) information compression method and applied it as input transformation step for character-level CNN text classiﬁcation. This novel text encoding dramatically reduces the time required for training CNNs and, therefore, makes the application of this novel approach more accessible. The proposed encoding makes possible to represent larger portions of texts in a compact form while preserving the ability to encode any word, even those not present in the training dataset ones. The experimental studies carried out as part of the paper coupled the encoding with two convolutional neural networks architectures.
These experiments showed that we managed to achieve a performance similar to the one achieved by Zhang et al.
(2015) a fraction of the training time even if we employed a simpler hardware setup.
This novel character-level text encoding produces a reduced input matrix, leading to a substantial reduction in training times while producing comparable or better results in terms of accuracy than the original approach by Zhang et al.
This opens the door to more complex applications, the use of devices with lower computational power and the exploration of other approaches that can be coupled with input representation.
Using a compressing technique is a convenient possibility to represent words for use in Convolutional Neural Networks to classify text.
Encoding words using characters could be relevant especially on less curated texts datasets, being robust to typos, slangs, and others usual characteristics of internet texts.
With our results, we reinforce Zhang et al.
(2015) conclusions, which states that language could be treated as a signal, no different from any other.
We demonstrated that using the approach suggested reduce the dimensionality of the matrix representation of texts and allow the use of simpler hardware than character level one hot encoding, allowing a drastic reduction of training time.
We performed a comparative test with the approach of Zhang et al.
and others traditional techniques and found competitive results.
It should be noted that the main objective of the paper was to show the viability of the text encoding, not producing better results per se .
Consequently, we have focused our efforts on the comparative study. Probably, custom neural network architectures should be devised to this new encoding, perhaps combining it with LSTMs to make overcome the ﬁxed matrix size limitation. In the near future, we will focus on devising these new architectures that may further favor this strategy. This study also opens a door to other information-theoretic-based methods for information representation to be used to create a numerical representation of texts.
It must be outlined the fact that this compact numeric representation of text is not limited to the domain of CNN or neural networks, for that matter.
It could be interesting to assess its impact as a preprocessing step, perhaps with a minor modiﬁcation, for other classiﬁcation algorithms.