<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by John Michael Kovachi on Medium]]></title>
        <description><![CDATA[Stories by John Michael Kovachi on Medium]]></description>
        <link>https://medium.com/@johnm.kovachi?source=rss-aabd93972973------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ohgkvf0UjBu_4y01.</url>
            <title>Stories by John Michael Kovachi on Medium</title>
            <link>https://medium.com/@johnm.kovachi?source=rss-aabd93972973------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:59:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnm.kovachi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing a Multinomial Naive Bayes Classifier from Scratch with Python]]></title>
            <link>https://medium.com/@johnm.kovachi/implementing-a-multinomial-naive-bayes-classifier-from-scratch-with-python-e70de6a3b92e?source=rss-aabd93972973------2</link>
            <guid isPermaLink="false">https://medium.com/p/e70de6a3b92e</guid>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <dc:creator><![CDATA[John Michael Kovachi]]></dc:creator>
            <pubDate>Sun, 21 Jan 2018 19:11:06 GMT</pubDate>
            <atom:updated>2018-01-21T19:11:06.020Z</atom:updated>
            <content:encoded><![CDATA[<p>For sentiment analysis, a Naive Bayes classifier is one of the easiest and most effective ways to hit the ground running for sentiment analysis. My goal of this post is to show how to implement this classifier <strong>from scratch</strong> and without help from great libraries such as <a href="http://www.nltk.org/">NLTK</a>. I will be doing an implementation of the algorithm found in Jurafsky and Martin’s <a href="https://web.stanford.edu/~jurafsky/slp3/">Speech and Natural Language Processing (3rd ed)</a>. This will be a learning experience for me as much as it will be for you. Let’s get started.</p><h4>Understanding Naive Bayes</h4><p>The Naive Bayes classification algorithm is based off of <a href="https://en.wikipedia.org/wiki/Bayes%27_theorem">Bayes’ Theorem</a>. Bayes’ Theorem is a beautiful yet simple theorem developed primitively by English statistician <a href="https://en.wikipedia.org/wiki/Thomas_Bayes">Thomas Bayes</a> in the early 1700s. At its most basic level, Bayes’ Theorem uses conditional probabilities to “predict” the outcome of later probabilities. The Bayesian concept of <em>a priori</em> probability is important: it is used as a ground truth from which we can use to obtain the outcome of other probabilities. Let’s take a look at Bayes’ theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*DdFz2o7Jt7uFzAGP8Pwdrg.png" /><figcaption>Bayes Theorem</figcaption></figure><p><em>P(c)</em> indicates the <em>a priori </em>probability of the given <strong>class</strong>, while <em>P(x)</em> represents the probability of a given <strong>predictor</strong>. Below the main formula, we can see that the theorem can be derived to show that the probability of a class given a predictor can be obtained by multiplying the probability of individual features that make up document <em>X</em> given a class<em> c</em> times the <em>a priori</em> probability of <em>c</em>. We will see this in action later in the article.</p><p>With a little thought, it is clear to see that this theorem could potentially have many applications in natural language processing, especially classification problems. With the Naive Bayes algorithm, our ultimate goal is to train our model to learn the probabilities needed in order to make a classification decision about a given document (which can be a sentence, entire corpus, etc). This leads to the problem of training our model, which we will now explore.</p><h3>Training the Naive Bayes Model</h3><p>To train our model, we will first need a training corpus. For sentiment analysis, there a plethora of suitable corpora out there, but I will personally be using the <a href="http://mpqa.cs.pitt.edu/corpora/mpqa_corpus/">Pitt MPQA opinion corpus</a> for use as a pre-annotated dataset. My ultimate goal in this sentiment analysis project is to be able to analyze sentiments from stock market news article corpora, so this news article corpora is a good starting point. This dataset can be used to train our model, as it contains a number of documents (words, phrases) that are classified as “positive”, “neutral”, and “negative”. For use in the Naive Bayes’ algorithm, these simple classifications work perfectly for our purposes.</p><p>To find the most probable class given a document <em>d</em>, we need to find the probability of <em>d</em> given <em>c</em> times the prior probability of <em>c</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*nSjjuW2SBNcGZ3cN61E4NQ.png" /></figure><p>To do this, for each class <em>c</em> in the set of available classes <em>C</em> we find the probability of each feature in <em>d</em> and multiply them together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*onKHO0N1AKcVoDyVnHE7CA.png" /></figure><p>The reason we can multiply the probability of the features together is because we assume that each feature is independent of one another: this is called <strong>Bayes’ Assumption</strong>. The Naive Bayes model is named as such because we are “naively” assuming conditional independence of features.</p><p>Deriving the prior probability of a class is rather trivial, as it is simply the sum of all words in <em>d </em>that are assigned to <em>c</em> divided by the number of words in <em>d</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*-PkUQ4n42T1YLaK-jXI9VQ.png" /></figure><p>Now, here comes the crucial question: how do we learn all of the probabilities of that make up each feature? The solution is again rather simple: for a given word <em>w</em> in words <em>W</em> from <em>d</em> we count how many of <em>w</em> belong in class <em>c</em>. We then divide this by ALL the words in <em>d</em> that belong to <em>c</em>. This gives us a probability for a word <em>w</em> given <em>c</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*179n7MYlMneiPvhhUizSIg.png" /></figure><p>We can make a minor adjustment to this formula to smooth the data (this accounts for the possibility that some words could have a zero-count for a class, which would make eliminate our work done so far):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*PB2b5dB2rHffvx_g-wcSng.png" /></figure><p>With the ideas set forth, we can now begin to train our data and calculate our probabilities.</p><h3>Working with the data</h3><p>We are almost set to train the data and build our classifier. First, however, we need to extract the data from whatever corpus we are using. The MPQA corpus can be a little challenging to extract, as the documents are presented as an XML structure. For parsing documents like this, I recommend using a Python module called <a href="https://docs.python.org/2/library/xml.etree.elementtree.html">ElementTree</a>. ElementTree does all the dirty work for you when parsing, and allows you to access individual XML tree elements with ease. Whatever you do, just DO NOT try and <a href="https://blogs.msdn.microsoft.com/jaredpar/2008/10/15/regular-expression-limitations/">parse XML with regular expressions</a>. It won’t end well. (Hint: XML is a context-free grammar, while regexes are confined to dealing with finite automata). I won’t get into my XML parsing script, as it is a little messy, but just know that I converted the XML to a list of 2-tuples (ex. (“happy”, “positive”)) containing the documents that were annotated with sentiment data.</p><p>Now that we have parsed our data, we need to build counts of each individual word and corresponding with its class. This will later be used to calculate the probabilities used in our Naive Bayes formula. I have implemented this idea below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/476da69127525368036e7d58ea8cc4ed/href">https://medium.com/media/476da69127525368036e7d58ea8cc4ed/href</a></iframe><p>I have used the Counter Python module to count the number of words that belong to each class and return them in a dictionary. Since we are employing the bag-of-words model for our Naive Bayes implementation, we are unconcerned with the ordering of the words in our documents, and thus can use an unordered dictionary to store the counts of words for each class. This code loops through our list of 2-tuples (“pol_list”) and creates a temporary dictionary holding the counts of words for each class from our two-tuple “pol”. Notice in my list comprehension I am lemmatizing each word using <a href="http://www.nltk.org/api/nltk.stem.html">NLTK’s very own lemmatizer</a> (I said I wouldn’t use NLTK at all here, but I couldn’t help myself here). I am also creating a set of stopwords and checking that each word in our document is not a stopword. If it is, I am throwing it out to improve the accuracy of our sentiment classification. Each dictionary counts positive, negative, and neutral words, and each are returned at the end of the function.</p><p>Next up, we are going to use these dictionaries to actually employ our training model. I have implemented this in a separate class called MN_NaiveBayes (Multinomial Naive Bayes). Let’s take a look it its constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72a202a4f8acb93a891b63f9811b4bd2/href">https://medium.com/media/72a202a4f8acb93a891b63f9811b4bd2/href</a></iframe><p>Keep in mind the MPQA.count() method simply is a helper method that counts the number of features in a given class. The constructor here is pretty self-explanatory.</p><p>Now, let’s get to the meat of the class: the training function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb46eb0915e2294343d41073b2124f4f/href">https://medium.com/media/fb46eb0915e2294343d41073b2124f4f/href</a></iframe><p>This function implements Jurafsky’s MN Naive Bayes training algorithm, which can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*Y3iDLGk-_8STqc3piKXD1Q.png" /></figure><p>I have modified the algorithm a little bit to fit the purposes of the implementation, but the general idea is the same. I don’t consider each word in the vocabulary <em>V</em> (all words in all classes), because I have already calculated the word counts per class. I have accounted for smoothing, though, by adding one to the numerator of the feature-given-class calculation and adding the cardinality of <em>V</em> to the denominator of the calculation. This idea is equivalent to the formula provided in this algorithm. We can see the equivalence here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*uWrDuiINGyU4iYCLf81stw.png" /></figure><p>Keep in mind that we are using the log probability to compute these calculations, because log probability generally guarantees better accuracy and speed. A more verbose explanation of log probability can be found <a href="https://en.wikipedia.org/wiki/Log_probability">here</a>.</p><h4>Testing our model</h4><p>Finally, we will move on to testing our model. Testing the model is fairly straightforward, and is done by considering our <em>a priori</em> class probabilities in conjunction with our individual feature-given-class probabilities. Remember, with Naive Bayes we are considering each respective feature-given-class probability to be independent of the other, which allows for this “naive” implementation. This idea is expressed here, where a position indicates an individual word (“feature”) in a test document:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*PBFw-heo5eXk6ETwUdiJOA.png" /></figure><p>Jurafsky refers to this classification decision algorithm as a <strong>linear classifier</strong>, because we are making a classification decision based off a linear combination of probabilities.</p><p>Here is the implementation in code of this idea:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e9f9f4c8d822c45add2b6572c54ee17/href">https://medium.com/media/6e9f9f4c8d822c45add2b6572c54ee17/href</a></iframe><p>And there we have it. We have now implemented and are able to test a fully-operational MN Naive Bayes model! A lot of work, right? Hopefully you enjoyed reading this article as much as I have writing it. In the next blog, we will focus on testing this model and checking for statistical significance. I might attempt to test the model with a different data source, as well. We will see…</p><p>A full representation of the code for this project can be viewed on my github:</p><p><a href="https://github.com/jmkovachi/sent-classifier">https://github.com/jmkovachi/sent-classifier</a></p><p>Sources:</p><p><a href="https://web.stanford.edu/~jurafsky/slp3/">Speech and Language Processing</a></p><p><a href="http://mpqa.cs.pitt.edu/corpora/mpqa_corpus/">http://mpqa.cs.pitt.edu/corpora/mpqa_corpus/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e70de6a3b92e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>