{'fraction_non_alphanumeric': 0.03074691805656273, 'fraction_numerical': 0.007722987672226251, 'mean_word_length': 4.615024429967427, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 0, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Hybrid Model For Word Prediction Using Naive Bayes and Latent Information

Historically, the Natural Language Processing area has been given too much attention by many researchers. One of the main motivation beyond this interest is related to the word prediction problem, which states that given a set words in a sentence, one can recommend the next word. In literature, this problem is solved by methods based on syntactic or semantic analysis. Solely, each of these analysis cannot achieve practical results for end-user applications. For instance, the Latent Semantic Analysis can handle semantic features of text, but cannot suggest words considering syntactical rules. On the other hand, there are models that treat both methods together and achieve state-of-the-art results, e.g. Deep Learning. These models can demand high computational effort, which can make the model infeasible for certain types of applications. With the advance of the technology and mathematical models, it is possible to develop faster systems with more accuracy. This work proposes a hybrid word suggestion model, based on Naive Bayes and Latent Semantic Analysis, considering neighbouring words around unfilled gaps. Results show that this model could achieve 44.2% of accuracy in the MSR Sentence Completion Challenge.


INTRODUCTION
In present days, there is a increasing demand by impaired people to use computer programs, mainly for social interaction. Most of these interactions are made by textual messages, which makes a difficult task for physical impaired people to communicate with others. Thereby, one technique which treats this problem that got attention by researchers is called word prediction.
Word prediction is a word processing feature that aims reduce the number of keystrokes necessary for typing words [2]. Usually, these models predict the next word given a set of words based on a context. Because of that, the Natural Language Processing (NLP) area, which performs tasks such word prediction through understanding and interpretation of texts and speeches, became popular.
One of the first NLP approaches in the computer science field is the n-gram model. In this model, each gram is a word in a known set of given words (also known as history). It performs a training in a text database in order to extract information about its language and create a set of features [3]. This approach uses the joint probability table, which increases the hit rate, but that demands too much data knownledge and, many times, it uses unfeasable computer resources [4]. For that reason, in order to use less resources, approaches as the Naive Bayes has been developed.
The Naive Bayes is an approach that assumes the conditional independence of its variables. It requires less memory and processing than approaches that consider this dependence. However, the Naive Bayes accuracy tends to be worst than those because of its knowledge loss during the independence assumption [5].
The NLP area still has researches for an accurate method that could be implemented and predict in an applicable time. In this context, the latent semantic analysis (LSA) was created. This technique is used to semantically analyze texts through the relationship between the words in different text levels, as phrases, paragraphs, among others [6]. Besides the high accuracy of the LSA technique, its inferences still are based only on the text frequency, which means that it does not consider word orders and consequently the text syntax.
With the advances of technology, in terms of memory space and processing time, other methods could be developed and consequently implemented, such as the Deep Learning [1]. Basically, it consists in a set of artificial neurons which is trained from a database through a multi-layer neural network with the aim of minimize an error function [7]. The Deep Learning process achieves a great precision in sentences completion challenges, however, it has some issues. The computational cost and time to train the amount of data needed is higher compared to other approaches. Beside this, since the learned knowledge is in the weights of neurons connections, it is not possible to interpret what was learned, which means that this is a black box model.
There are many Word prediction models in the NLP area, however, as far as we know none of them can accomplish the task of predict a word with precision in an applicable time, as a human being would do. Therefore, the area still demands development, and a hybrid model might help researches to explore new approaches. This paper proposes a new hybrid model to predict words using two well-known models: the Naive Bayes and the LSA. In addition, to this we optimize parameters used to improve the prediction precision through the Gradient Descent technique.
This paper is organized as following. In the next section, will be presented the relevant areas backgrounds. Then, in the third section, the methodology used to the model development and its optimization is explained. Next, in the fourth section, the tests performed to qualify the results that prove the model precision are presented. Then, in the fifth section, the benefits and issues are discussed in the paper conclusion. At last, in the sixth section, some issues that can be improved in future works are presented.

BACKGROUND
In NLP area, many models were proposed to predict a word, the Table 1 shows a list with some related models.

Naive Bayes
The Naive Bayes is a probabilistic model used in Natural Language Processing (NLP) as a n-gram, developed through Bayesian networks that are vastly used in the machine learning area, as stated in [5].
Usually, full n-gram models are not feasible to be implemented due to its complexity, because they require a joint probability table. Those tables grow exponentially with the insertion of new variables.
This model states that its variables can be divided in to cause and effect behaviors; thereby, it can be assumed that the effects are conditionally independent between themselves, which reduces the computational cost of the model. This model is mathematically represented in Equation (1), in which, the effect and the cause are represented by e and c i respectively. Thus, using this model it is not necessary to build a joint probability table.
The normalization factor γ is calculated by the Equation (2), in which k represents the number of words learned in the train.

Latent Semantic Analysis
The latent semantic analysis (LSA) has been vastly used in systems that analyze textual contents [18], since it performs a comparison between words to infer.
The LSA can use any cohesive textual level, such as phrases, paragraphs, entire documents in its traning set [19]. The information (text) of this textual levels contains the semantic relationship between the words in it. To store these relations, a table is constructed (relationship table) containing the frequency (f i,j ) that any word i appeared in a textual level j.
With the relationship table, comparisons between words can be performed to discover similar words. Therefore, it is necessary to compute the distance between the relationship table lines using some metrics [20].
Thereby, the LSA is a technique that is used to extract and infer the words contextual usage relationship in a vector space, as stated in [6].
A common problem of the LSA is the dimension of the relationship table, that is usually sparse and consumes unnecessary memory space. A solution used in the area for this issue [14] [19] is the usage of the Singular Value Decomposition (SVD) technique. With it, it is possible to reduce the relationship table size without losing all the original information, keeping it dense. In this work, the reduced table is noted as Semantic Reduced Table (SRT ).

Gradient Descent
The gradient descent is a mathematical optimization algorithm used to modify variables values based on their contribution to minimize an error function [21]. Often, this technique is used in prediction models such as: neural networks, deep learning, bayesian learning, among many others.
To perform the optimization, the error function has to be differentiable, because the gradient descent algorithm uses derivatives. The most used error function is the squared-error [21], modeled as Equation (3), in which f (x) is the model prediction, y is the ideal value of the prediction (usually 0 or 1) and the number 1 2 is used to simplify the further derivatives calculus, as it will be dropped in the next processes.
The variables values changes are proportional to the error function gradient [22]. Thereby, to minimize the error, the variables have to be updated proportionally in the opposite direction of gradient function. To smooth the optimization updates, a factor η is often used to control and keep the current knowledge of the model, compared with the recent information acquired.

PROPOSED MODEL
This paper proposes a hybrid word prediction model, that performs inferences based on Naive Bayes and Latent Semantic Analysis (LSA) theories. The methodology used to develop the proposed model is divided into three stages: Training, Optimization and Inferences, illustrated in Figure 1. Those steps are described and analyzed in this section.

Training
To perform probabilistic inferences, it is necessary to create and train the LSA and Naive Bayes sub-models. These submodels are trained in order to represent two types of information. The former, Naive Bayes, is used to store co-occurrences patterns of words; the later, LSA, is used to model the language semantics.
In order to train this model, a textual database is required. Therefore, the Project Gutenberg database [23] was used to accomplish this pre-requisite as it is used vastly in literature such as in [14] [24] [11]. A set composed by 522 19th Century literature books was used in this paper.

Naive Bayes Graph
The co-occurrences patterns which represents the Naive Bayes network can be stored in a set of graphs G = (g 0 , g 1 , ..., g d−1 ), where nodes represent words and edges represent the number of times that each pair of words co-occurred in a same textual level. Each graph g i with 0 <= i <= n − 1 represents the connections of the words that appear in the text with i words between them. This distances are illustrated in the Figures 2 and 3, taking the phrases "The sky is blue" and "The blue is a color" as example. The blue is a color The G set is constructed from many different graphs g i for all i. Each g i is constructed taking every co-occurrences of distance i in a text. The weight of edges will be higher as many co-occurrences appear in it, this is represented by w d i,j , where d is the graph and i, j represents the edge which connects words i and j; the value of these edges is the number of times that words i and j occurred in the database, establishing this approach as a frequentist model. Take as example the Figures 4 and 5 that represents the g 0 and g 1 respectively which was constructed using the same sentences used previously: "The sky is blue" and "The blue is a color".

Latent Semantic Analysis (LSA)
This step consists of building the relationship table. Firstly, it is necessary to adopt the textual level to be used in the LSA. In this paper, only sentences with more than 4 nonstop-words are used. This measure was established to gather only the most semantic relevant phrases 1 .
To construct the relationship table, each different word in the database is represented as a row and each textual level as a column. The value of each table cell c word,t is defined by the number of times that the word is present in the textual level t.
As stated before in Section 2.2, the ST R is obtained from relationship table, where the inferences can be performed using acceptable computer resources.

Inferences
Based on the n previously used words in a text, inferences can be performed in the constructed models to predict a word usage probability in the analyzed context. This section will describe these inferences using the notation prev 0:n−1 to represent all the n previous words.

Naive Bayes inference
The bayesian inferences are computed to establish the P (sugg j |prev 0 , ..., prev n−1 ), in which sugg j is a possible word recommendation (suggestion) from prev 0 , ..., prev n−1 history. Thereby, the Equation (4) represents the probability of the sugg j be used just after the other prev 0:n−1 words in the same sentence. This probability is represented by the notation B j . Furthermore, each P i (prev i |sugg j ) is a probability created by a normalization of w d previ,suggj (explained in Section 3.1.1) illustrated in Equation (5). The prior probability P (sugg j ) was gathered directly from database, which is represented in Equation (6).
1. The source-code used as part of implementation of this sub-model can be found in following link: https://github.com/chiawen/sentencecompletion P (i) = number of occurrences of i total of word occurrences in database (6) Therefore, all the previously used words have the same relevance to the model, as the Naive Bayes considers the events independently, which decreases the model precision, because as explained previously, the Naive Bayes not considers all probabilities involved in inference. In order to minimize this issue, variables responsible to weight this relevance were inserted in the model, noted as λ i , in which i refers to the distance between the weighted and the analyzed words.
The equation B j now represents the weighted model, Figure 7, in which P (prev 0 |sugg j ) is inversely weighted by the λ 1,...,n−1 . Thereby, the value of λ 1,...,n−1 are normalized between themselves, and the equation energy is preserved.

Latent Information Inference
In order to use the knowledge of the prev 0:n−1 words, n inferences have to be computed in the SRT , which directly impacts the computational cost of the model. Those are executed by calculating the semantic similarity of each prev i word, 0 <= i < n − 1, with all SRT words in vocabulary. Those similarities are calculated by the second norm distance, in which, each vector represents a word.
Therefore, each of the n SRT cells represents the distance between each candidate word j and prev i . Thus, to obtain the similarity of j to all prev words, the inverse of the distance vector values are summed, as the distance is inversely proportional to the semantic similarity of the words. Thus, the semantic distance d j between j and prev 0:n−1 is represented by Equation (8).
After calculating d j , it is necessary to normalize the results based in n, as in Equation (9). Therefore, L j represents the normalized semantic similarity of the word j based on the n previous known words.

Hybrid Inference
The trained networks achieved through the Naive Bayes and LSA models, and their respective inferences, Equations (7) and (9), output different pattern results, which affects the hybrid model development. The probability variance of the Naive Bayes inferences is much larger than the LSA ones.
To successfully merge the models, it is necessary to establish an output pattern to equalized them. Therefore, the probability values of the next word to be inferred, from both models, are sorted in ascending order crescent in two vectors. Thereby, those probabilities are replaced by their vector index and normalized by the sum of all indexes, as illustrated below. Thus, the Naive Bayes and LSA inferences are weighted, which creates the hybrid model, that is represented in Equation (10).
The proposed model uses a weighting constant alpha, that aims to improve the inferences precision. This constant represents the Naive Bayes percentage relevance in comparison with the LSA. For example, if α = 1 all the inference will be done through the Naive Bayes else, if α = 0, through the LSA.

Optimization
Once Naive Bayes and LSA networks are trained, the inferences can be performed. However, those models provide a different set of probabilities (B j and L j ). Considering the hybrid model of Equation (10), there is a set parameters that can be optimized in order to provide an ideal weight between the models, improving the recommendation precision. Moreover, the values of λ parameters can also be optimized, achieving a better weight between the partial probabilities of Naive Bayes. Therefore, optimization through supervised training was performed. The set of optimized parameters was composed by α, that represents the relevant percentage of the Naive Bayes compared to the LSA; and λ 1 , ..., λ n−1 , that express the weight/relevance relation between the words distances in the Naive Bayes inference.
As the inference goal is to predict the correct word with the maximum precision, it is desired that the correct inferred value be as close as possible to 100%. Thus, the Equation (11) can be determined, in which E represents the system error. The optimization proposed in this work is performed using only the probability output of the correct suggestion sugg c (thus, B c and L c are used for optimization).
After expanding the equation of error, the Equation (12) is obtained.

Alpha (α)
The gradient descent optimization technique was used to find the ideal value of α. In this case, its value was updated using the error function through an iterative process. Using Equation (12), the α update is performed using its derivative over the α itself represented by Equation (13). Therefore, the error value will tend to decrease.
Equations (14) and (15) add a new term to the optimization, in which η α represents the learning rate of each iteration, regarding the current knowledge of the model.

Lambda (λ)
The λ 1 , ..., λ n−1 values were optimized similarly to the α one. A supervised training was performed with thousands of iterations in which, each λ 1 , ..., λ n−1 was updated regarding it respective error in each iteration.
The error, Equation (12), can be expanded to Equation (16), in which the equalized P (prev i |sugg j ), as explained in Section 3.2.3, and the P (sugg j ) have been replaced by t i and t respectively.
Therefore, with the derivative of the E over each λ, an individual error rate value is obtained. The Equations (17) and (18) represent the derivative of the E regarding λ 1 and λ 2 respectively, in a model that considers only three previous words.
With the derivative of the E over each λ x , 1 <= x <= n − 1, the λ x value is updated over each iteration, Equation (19), in which η λ represents the learning rate of each iteration, regarding the current knowledge of the model.

RESULTS
In order to validate the proposed model, it was applied the experiment MSR Sentence Completion Challenge [25], this experiment consists of the 1040 sentences with a missing word. Moreover, it is provided 5 options to choose a word for complete the sentence.
In the MSR Sentence Completion Challenge, it is possible that the missing word is in the middle of sentence. For this case, the bayesian model also considers the posterior words from the gap. This case is illustrated in Figure 6 using as example the following sentence: Lorem ipsum dolor amet vitae elit. Thereby, the LSA also consider all words it was considered by Naive Bayes. Thus, the Naive Bayes inference was described by Equation (20).
To guarantee cross-validation on experiments, the MSR Sentence Completion Challenge was separated into 5 groups. Therefore, one of these groups was used for test and the others for optimization, this is illustrated in Figure 7. Furthermore, is possible to have 5 different and independent configurations for experiments.

Error Variation
In order to validate the proposed optimization, it was created a scenario where the parameters λ and α were initialized randomly in the range 0 and 1 for each configuration. Furthermore, the optimization groups were disposed in a cyclic loop (i.e. epochs), thus extending the optimization. In this scenario, it was used a 3-gram history.
The Figure 8 shows the error variation in each configuration. It is possible to observe that the error is minimized for all configurations. This error metric is obtained through the sum of all individual sentences errors.

Alpha Variation
Following the same scenario, the Figure 9 illustrates the variation of alpha value over epochs. Note that α lies between ∼0.2 and ∼0.4. Therefore it can be stated that LSA is more relevant than Naive Bayes, since this value is lower than 0.5.

Lambda Optimization
In the scenario described above, it is possible to visualize the values of parameters λ in each configuration over the optimization sentences, as illustrated in Figures 10, 11, 12, 13, 14 and 15.
Results show that λ values converge to the same region even with the initial random values and configurations. Therefore, it is feasible to state that in this scenario the word about distance 0 is the most relevant for inference and the words about distance 2 and -2 are the least important for inference.         In order to understand how the size of history can influence the final result, it was created a scenario where the history was tuned between 2-gram and 15-gram using configuration 1. Furthermore, the proposed model was tested using only Naive Bayes, only LSA and weighing both models (i.e. α optimized), as illustrated in Figure 16.

Size of History Influence
As observed, up to 4-gram there are a weighing between both models that provide better results than these models individually. From that point, LSA provides better results alone. This probably happens because the bayesian model tries to detect patterns which were not present in training.

Influence of Each Word for the Naive Bayes
Through the Naive Bayes it is possible to determine which distances are more or less important for inference, observing the parameters λ. Thereby, it was created a scenario where a 15-gram history is used and only Naive Bayes is considered (i.e. α = 0) as illustrated in Figure 17. Thereby, both sides of inference have a similar pattern, where the distance 0 words are more relevant.

Tests and Comparative
As explained previously, the proposed model in this work was tested in each configuration using a 3-gram history. The Figure 18 shows the performance of model optimized and non-optimized. Furthermore, it is compared with the state-of-the-art [1] and related models.
As observed, the proposed model in this work is superior to another n-gram model which considers history between 5-gram; but it is worse than LSA model, which considers all words in the sentence for inference; also it is worse than neural network model. However, the proposed model provides recommendations considering syntactic and semantic features using less training data than a neural network model.

CONCLUSION
In this work, it was developed a hybrid model to complete sentences employing Naive Bayes and LSA models. This hybrid model uses a set words to infer the next word considering each sub-model individually.
In order to validate the proposed hybrid model, it was conducted an experiment in which it is composed by sentences with a missing word. Therefore, there were proposed the parameters λ 1 , ..., λ n−1 to optimize the inferences of Naive Bayes and another parameter α to improve their integration with the LSA. To optimize the values of these parameters, it was applied the Gradient Descent technique, where these values are adjusted based on an error function.
Results show that lambda values converge to same values. That is, for each lambda λ, different experiments result to similar final values. This is a strong evidence that the optimization technique is working. Furthermore, results show that   [24]. the most relevant history information for the suggestion are the previous and posterior neighboring words, as illustrated in Figure 17.
Within the optimization experiment, the α parameter was also trained. Results show that α tends to give more importance to LSA model than Naive Bayes, since its value converged to the region between ∼0.2 and ∼0.4. Another useful result is that the size of history words affects the convergence value of α. That is, if the size of history is less than 4, alpha lies between 0 and 1. However, if the size of history is higher than 4, alpha tends to 0, which means that LSA model is the unique model used to suggest the next word. Maybe, this is a evidence that the Naive Bayes model could not find suitable conditional probabilities in the Naive Bayes graph. This behavior could happen if the train database is small and does not contains some relations between words.
One important regard about the experiments is that it was used the cross-validation in order to validate the convergence values. It was found that, for different sets of train samples, the λ and α parameters did not change the final optimized value.
During tests, the proposed model proved to be relevant to other related models. Even not providing better results than actual state-of-the-art, the proposed model brought relevant results, considering syntactic/semantic rules among words and consuming a fraction of training required by a model based on Deep Learning.
Thereby, the proposed model in this work achieved the objectives providing a great time × accuracy relation which can be improved, thus creating new perspectives in NLP as also different applications such: a better word prediction model for mobile platforms, improve the conversation ability of robots, enhance search engines and improve the social interaction of impaired people.

FUTURE WORK
The proposed model has several features which were not investigated. One of these features is to use a bigger database for optimization since the MSR Sentence Completion Challenge has a few supervised examples to do this task.
In this work it was used a fixed number for learning rate η α and η λ . In case of those number were changed over the epochs, could provide better results.
It was proposed a minimal conditional probability for the Naive Bayes inferences whenever a co-occurrence is not present in the words graph. This gives a minimal chance for a word to be recommended, instead of zeroed product in the bayesian inference. In case of this value is optimized, maybe the bayesian model provides greater results.
The database from Project Gutenberg gives a set of full books (where are included meta-information such as: chapter indicator, paragraphs indicators, publisher notes, etc). In this work, we used a simple regular expression rule to extract useful information from this database. However, much information was lost during this process. It would be better to use text mining algorithms to extract more information in order to get a bigger dataset.
Over the optimization, only the correct option was considered for error minimization. Also, it is possible to consider wrong words to compute the error function. This could bring more precision to the inference process.
To fairly compare the Naive Bayes and LSA, it was proposed a equalization procedure of output probabilities for each model. This technique worsens the optimization of parameters λ when giving normalized values instead of the original. Thereby, another technique that avoids this problem could improve the proposed model.
In Naive Bayes, it was added many parameters λ to enhance the bayesian performance. However, the prior probability does not have one of these parameters. In case of implementing this new λ term, it would be possible to observe not only the influence of previous words than posterior but also the prior probability term.