This tutorial demonstrates the implementation of Naive Bayes Classifier from Scikit Learn library.

###Importing Libraries

from sklearn import datasets
from sklearn import metrics
from sklearn import preprocessing
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split as tts

###Importing Dataset
iris = datasets.load_iris()
data = pd.DataFrame({"sl":iris.data[:,0], "sw":iris.data[:,1], "pl":iris.data[:,2], "pw":iris.data[:,3], 'species': iris.target})

###Splitting train/test data
X=data[['sl','sw','pl','pw']]
y=data["species"]
X_tr, X_ts, y_tr, y_ts = tts(X,y, test_size=30/100, random_state=None)

###Creating Naive Bayes Model
GNB = GaussianNB(var_smoothing=2e-9)

###Training the Model
GNB.fit(X_tr, y_tr)

###Making Predictions
y_pr = GNB.predict(X_ts)

###Evaluating Prediction Accuracy
print("Acc %:",metrics.accuracy_score(y_ts, y_pr)*100)

###Making Prediction with Foreign Data
print(GNB.predict([[1,1,0.5,6]]))

This tutorial aims to provide a simple, clear and reusable Naive Bayes implementation, feel free to reuse, reproduce, change this code and experiment with it.

If you need explanations here is a step by step explanation of this algorithm and all the details regarding parameters and optimization and fine tuning of Naive Bayes algorithm can be found here.

Finally, you can also see Naive Bayes history here which is a pretty curious story.