Goal is to create a next word prediction model using Markov chain.
Text was obtained from 3 sources Twitter, Blogs and News.
The texted was tokenized into sentences and loaded into SQLite using
Text2SQLite.R
this allowed to maintain a relational link from the sentence to it's source for
balanced sampling.
Sampling random sentences proved slow so I dropped sentences I was filtering out
with a WHERE clause, such as short sentences (> 5) and long sentences (< 50).
DROP_short_and_long_sentences.R
Probably the hardest part of this project. Prediction were hard to get before these things happened:
- I unit test
test_normalize.Rthe normalizing function and found many of it's failures. - I excluded stopwords from being counted as ngrams but included them in context words.
- Using
textclean::replace_contraction()andlemmatize_strings()was a game changer. this stablized the process and I was able to generate ngrams databases with up to 500,000 sentences. I settled on 100,000 sentence (about 90MB) for portability. Used Kneser-Ney smoothing to calculate probability and store it along the words and frequncy.generate_ngrams.R
predict_next_word <- function(input_text, n_top = 5) {..}
a function that takes in a sentences and returns a next words prediction
along with it's probability and source n-gram. it returns 5 predictions by default but
can be set to any number of prediction. the prediction is done by backing off from
higher order grams to lower ones with fall back to bigrams.
calculate_perplexity <- function(input_text) {..}
calculates the perplexity of input text against the ngrams dataset.
Shiny app with prediction UI, stats, details about the data set generated by
generate_top_ngrams.R which creates top_ngrams.RData. this helps with loading time.