<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/naive-bayes-a-generative-model-and-big-data-classifier/"></div></div><div><a data-url="https://www.r-bloggers.com/naive-bayes-a-generative-model-and-big-data-classifier/" data-counturl="https://www.r-bloggers.com/naive-bayes-a-generative-model-and-big-data-classifier/" data-count="horizontal" data-text="Naive Bayes: A Generative Model and Big Data Classifier" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.rstudio.com/rviews/2016/11/02/naive-bayes-a-generative-model-and-big-data-classifier/"> RStudio</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>

<div>
<div>
<div>
<p>by Joseph Rickert</p>
<p>I found my way into data science and machine learning relatively late in my career. When I began reading papers on supervised learning I was delighted to find that good old logistic regression was considered a “<a target="_blank" rel="nofollow" href="http://repository.cmu.edu/robotics/218/">go to</a>” classifier. This was like learning that an old friend was admired for an achievement I didn’t know anything about. After a couple of comfortable experiences like this, I thought I would fit in quite nicely with this new (to me) tribe of data analysts studying pattern recognition and natural language processing. It took some time however, before I realized that they were working with a conceptual framework that was a little different from my statistics worldview. You might say it’s all probabilistic and statistical reasoning, but different problems and different tools lead to mindsets that shape and bias a person’s thinking.</p>
<p>For example, consider the following list of classifiers: Decision Trees, Generalized Boosted Models, Logistic Regression, Naive Bayes, Neural Networks, Random Forests and Support Vector Machine.</p>
<p>Some of these are base classifiers, and others are ensemble models, but one of them is conceptually different from the others. The odd duck here Naive Bayes. It’s the only generative model in the list. The others are examples of discriminative models. This is not a distinction that is easy to stumble across in the statistics literature, but it is fundamental to the machine-learning mindset, and a helpful modeling idea.</p>
<p>The basic conceptual difference between generative and discriminative models hinges on the underlying probability inference structure. Discriminative models learn P(Y | X), the conditional relationship between the target variable, Y, and the features, X, directly from the data. This is exactly the way ordinary least squares regression works, and it is the kind of inference pattern that gets fixed in the mind of statistics students very early on in their training. It is a direct approach to sorting out the relationship among variables. Some (usually one) variables are the dependent variables, or target variables, and other variables are the independent variables, or features. These latter variables are given or fixed, at least for the purposes of the analysis.</p>
<p>Generative models, on the other hand, aim for a complete probabilistic description of the data. With these models, the goal is to construct the joint probability distribution P(X, Y) – either directly or by first computing P(X | Y) and P(Y) – and then inferring the conditional probabilities required to classify new data. This approach generally requires more sophisticated probabilistic thinking than a regression mentality demands, but it provides a complete model of the probabilistic structure of the data. Knowing the joint distribution enables you to generate the data; hence, Naive Bayes is a generative model.</p>
<p>Once you know what you are looking for, it is not difficult to find excellent online tutorials demonstrating the differences between generative and discriminative models. For example, Stanford professors <a target="_blank" rel="nofollow" href="https://www.youtube.com/watch?v=qCA1Dk_Ih_c">Christopher Manning</a> and <a target="_blank" rel="nofollow" href="https://www.youtube.com/watch?v=z5UQyCESW64">Andrew Ng</a> have both produced short videos that nicely characterize these models. And for a simple explanation of the Naive Bayes algorithm and how it unfolds as a generative model, I very much enjoyed mathematicalmonk’s <a target="_blank" rel="nofollow" href="https://www.youtube.com/watch?v=8yvBqhm92xA">colored marker video</a>.</p>
<div>
<div><iframe title="YouTube video player" height="350" width="600" allowfullscreen src="https://www.youtube.com/embed/8yvBqhm92xA?wmode=transparent&autoplay=0"></iframe></div>
</div>
<div></div>
<div></div>
<p>In his Eight to Late blog, Kalish Awati thoroughly develops <a target="_blank" rel="nofollow" href="https://eight2late.wordpress.com/2015/11/06/a-gentle-introduction-to-naive-bayes-classification-using-r/">a classification example</a> using Naive Bayes that is worth a look not only because of the details on data preparation and model building he provides, but also because of the care he takes to explain the underlying theory. Kalish uses the Naive Bayes classifier in the <a target="_blank" rel="nofollow" href="https://rdrr.io/cran/e1071/">mysteriously</a> named <a target="_blank" rel="nofollow" href="https://mran.revolutionanalytics.com/package/e1071/">e1071 package</a> and the HouseVotes data set from the <a target="_blank" rel="nofollow" href="https://mran.revolutionanalytics.com/package/mlbench/">mlbench package</a>. (The <a target="_blank" rel="nofollow" href="https://mran.revolutionanalytics.com/package/klaR/">klar package</a> from the University of Dortmund also provides a Naive Bayes classifier.) I won’t reproduce Kalish’s example here, but I will use his imputation function later in this post.</p>
<p>First however, let’s follow up on the idea of using a Naive Bayes model to produce synthetic data.</p>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<div>
<div>
<pre><span>library(mlbench)</span>
<span>library(e1071)</span>
<span>data(&quot;HouseVotes84&quot;)</span>
<span>model &lt;- naiveBayes(Class ~ ., data = HouseVotes84)</span>
<span>print(model)</span></pre>
<div></div>
</div>
</div>
</div>
</div>
<div></div>
<div>
<div>
<div></div>
<div></div>
<p>The model object produced by the naiveBayes() function includes a contingency table for each vote, which is displayed by the print statement above. Here is an example of just one of the tables displayed by the print statement:</p>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<pre><code>model$tables$V2
# V2
# Y             n           y
# democrat   0.4979079 0.5020921
# republican 0.4932432 0.5067568
</code></pre>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<div></div>
<div></div>
<p>Creating new, synthetic data is just a matter of using this table to drive a simulation. Suppose that we wanted to simulate data for 25 new Democratic members of the House of Representatives. This is particularly easy for our example, because we are dealing with categorical data.</p>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<pre><code># Use the model object to create a vector of probabilities for
# a No vote for each of the 16 variables


pn &lt;- vector(mode=&quot;numeric&quot;,length=16)
for (i in 1:16) {
  pn[i] &lt;- model$tables[[i]][1,1]
} 


# Create new democratic voting data
dem_data &lt;- matrix(data = NA, nrow = 25, ncol = 17)


for( i in 1:25){
  dem_data[i,] &lt;- c(&quot;democrat&quot;,rbinom(16,1,pn))
}


# Coerce the data into a data frame
dem_data &lt;- data.frame(dem_data)


# Set the levels to match the original data
levels(dem_data[,1]) &lt;- c(&quot;democrat&quot;,&quot;republican&quot;)
dem_data[,1] &lt;- factor(dem_data[,1],levels=c(&quot;democrat&quot;,&quot;republican&quot;))


for(i in 2:17){
    levels(dem_data[,i]) &lt;- c(&quot;y&quot;,&quot;n&quot;)
  }
# Set the column names to match the real data
names(dem_data) &lt;- c(&quot;Class&quot;,&quot;V1&quot;,&quot;V2&quot;,&quot;V3&quot;,&quot;V4&quot;,&quot;V5&quot;,&quot;V6&quot;,&quot;V7&quot;,&quot;V8&quot;,
                              &quot;V9&quot;,&quot;V10&quot;,&quot;V11&quot;,&quot;V12&quot;,&quot;V13&quot;,&quot;V14&quot;,&quot;V15&quot;,&quot;V16&quot;)


head(dem_data,2)
dim(dem_data)
</code></pre>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<div></div>
<div></div>
<p>A very nice, maybe even ironic feature of the the Naive Bayes algorithm, is that while it is extremely useful in generating synthetic data when there is not enough real data at hand, it is also of considerable importance in the world of big data and machine learning. Almost every industrial-strength big data platform, including <a target="_blank" rel="nofollow" href="http://mahout.apache.org/">Apache Mahout</a>, <a target="_blank" rel="nofollow" href="http://spark.apache.org/docs/latest/mllib-naive-bayes.html">Spark’s MLlib</a>, <a target="_blank" rel="nofollow" href="https://spark.apache.org/docs/latest/sparkr.html#naive-bayes-model">SparkR package</a>, <a target="_blank" rel="nofollow" href="https://msdn.microsoft.com/en-us/microsoft-r/scaler-user-guide-naive-bayes">Microsoft R Server</a>, and <a target="_blank" rel="nofollow" href="https://rdrr.io/cran/h2o/man/h2o.naiveBayes.html">H2O</a>, has an implementation of Naive Bayes. The are several reasons for this including: (1) the empirical observation that Naive Bayes performs remarkably well, in spite of the unrealistic assumption of independent conditional probabilities (For example see <a target="_blank" rel="nofollow" href="http://web.cs.iastate.edu/~honavar/rish-bayes.pdf">Rist et al</a>.); (2) the fact that the number of parameters required to fit a Naive Bayes model scales linearly with the number of variables, and (3) maximum likelihood training can be done via closed form expressions. So it is not necessary to grind through several iterations of a calculation waiting for the convergence.</p>
<p>An easy way for an R user to run a Naive Bayes model on very large data set is via the <a target="_blank" rel="nofollow" href="http://spark.rstudio.com/">sparklyr</a> package that connects R to Spark. The following code, which makes use of the HouseVotes84 dataframe and Kalish’s imputation function, shows how to fit a Naive Bayes model on Spark data.</p>
<p>The first bit of code loads the data into my local R session and imputes the missing values.</p>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<pre><code>library(mlbench)
library(e1071)
#load HouseVotes84 dataset
data(&quot;HouseVotes84&quot;)
head(HouseVotes84,2)


#---------------------------------------
# This function is taken from Kalish Awati's 
# post on Naive Bayes
# It imputes missing values for the 
# HouseVotes84 data set 
# function to return number of NAs by vote and class 
# (democrat or republican)
na_by_col_class &lt;- 
function (col,cls){return(sum(is.na(HouseVotes84[,col] &amp; 
                         HouseVotes84$Class==cls))}
# function to compute the conditional probability
# that a member of a party will cast
# a 'yes' vote for a particular issue. 
# The probability is based on all members of the 
# party who actually cast a vote on the issue (ignores NAs).
p_y_col_class &lt;- function(col,cls){
  sum_y&lt;-sum(HouseVotes84[,col]=='y' &amp; 
         HouseVotes84$Class==cls,na.rm = TRUE)
  sum_n&lt;-sum(HouseVotes84[,col]=='n' &amp; 
         HouseVotes84$Class==cls,na.rm = TRUE)
  return(sum_y/(sum_y+sum_n))}
#impute missing values.
for (i in 2:ncol(HouseVotes84)) {
  if(sum(is.na(HouseVotes84[,i])>0)) {
    c1 &lt;- which(is.na(HouseVotes84[,i])&amp; HouseVotes84$Class=='democrat',arr.ind = TRUE)
    c2 &lt;- which(is.na(HouseVotes84[,i])&amp; HouseVotes84$Class=='republican',arr.ind = TRUE)
    
    HouseVotes84[c1,i] &lt;-
      ifelse(runif(na_by_col_class(i,'democrat'))&lt;
             p_y_col_class(i,'democrat'),'y','n')
    HouseVotes84[c2,i] &lt;-
   ifelse(runif(na_by_col_class(i,'republican'))&lt;
            p_y_col_class(i,'republican'),'y','n')}
}
</code></pre>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<div></div>
<div></div>
<p>Next, since Spark and the MLlib functions do not have any notion of R’s factor type, I replace the factor variables with 0 /1 indicators.</p>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<pre><code># Get rid of factors
votes &lt;- HouseVotes84
votes$Class &lt;- ifelse(votes$Class == &quot;democrat&quot;, 0, 1)
votes[,2:17] &lt;- sapply(votes[,2:17],
                  function(x){ifelse(x == &quot;n&quot;, 1, 0)})
</code></pre>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<div></div>
<div></div>
<p>The sparlyr and dplyr packages are loaded and Spark is installed on the local computer. Next, the <code>spark_connect()</code> function establishes the Spark compute context. (Connecting to a remote cluster is a bit more involved, but the connection is established through the same mechanism.)</p>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<pre><code>library(sparklyr)
library(dplyr)
spark_install()


sc &lt;- spark_connect(master = &quot;local&quot;)
votes_tbl &lt;- copy_to(sc, votes,overwrite=TRUE)
head(votes_tbl)
</code></pre>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<div></div>
<div></div>
<p>Finally, we partition the data into training and test data sets and use the MLlib implementation of Naive Bayes to fit the model in Spark.</p>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<pre><code>#Partition into 'training', 'test'
partitions &lt;- votes_tbl %>%
  sdf_partition(training = 0.5, 
                test = 0.5, seed = 1099)


head(partitions$training)
# pick out the feature variables.
X_names &lt;- names(votes[,2:17]) 
# Fit model
nb_spark_model &lt;- ml_naive_bayes(partitions$training, 
                   response= &quot;Class&quot;, 
                   features = X_names)
nb_spark_model
</code></pre>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<div></div>
<div></div>
<p>From here, it would not take much more work to complete the rest of Kalish’s example in Spark.</p>
<p>In the machine learning world, Naive Bayes may be an even more popular “go to” classifier than logistic regression. It often provides predictive results that are good enough to set the bar as a baseline model. it is interesting as a simple example of a generative model, and with the help of the sparklyr package, it is easy for R users to deploy in Spark’s big data environment.</p>
<div></div>
</div>
</div>
<div></div>
</div>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/naive-bayes-a-generative-model-and-big-data-classifier/"></div></div><div><a data-url="https://www.r-bloggers.com/naive-bayes-a-generative-model-and-big-data-classifier/" data-counturl="https://www.r-bloggers.com/naive-bayes-a-generative-model-and-big-data-classifier/" data-count="vertical" data-text="Naive Bayes: A Generative Model and Big Data Classifier" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.rstudio.com/rviews/2016/11/02/naive-bayes-a-generative-model-and-big-data-classifier/"> RStudio</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/LaeSx1A2hfQ"></a></div>