for i in range(len(test)): y_test.append(test[i][0]) X_test.append(test[i][1:]) # Instantiate the Naive Bayes classifier model made from scratch model = NaiveBayesClassifier() # Fit the model model.fit(X_train, y_train) # Make predictions y_pred = model.predict(X_test) # Print the accuracy of the model print("NaiveBayesClassifier accuracy: {0:.3f}".format(model.accuracy(y_test, y_pred))) # Instantiate the Gaussian Naive Bayes classifier model from Scikit-learn model = GaussianNB() # Fit the model model.fit(X_train, y_train) # Make predictions
import pandas from naive_bayes_classifier import NaiveBayesClassifier df = pandas.read_csv("weather.csv", sep=";") naive_bayes = NaiveBayesClassifier(df, 0.6) naive_bayes.train_algorithm() accuracy = naive_bayes.test_algorithm() print("Algorithm Accuracy : " + str(accuracy) + " %") tuple_data = ('Overcast', 'Hot', 'Normal', True) prediction = naive_bayes.predict(tuple_data) print("Prediction for " + str(tuple_data) + " is " + prediction)
NB_classifier = NaiveBayesClassifier() spam_train = spam_data[:int(len(spam_data) * 2 / 3)] spam_test = spam_data[int(len(spam_data) * 2 / 3):] legit_train = legit_data[:int(len(legit_data) * 2 / 3)] legit_test = legit_data[int(len(legit_data) * 2 / 3):] NB_classifier.train(spam_train, legit_train) spam_accuracy = 0 legit_accuracy = 0 for text in spam_test: prediction = NB_classifier.predict(text) spam_accuracy += prediction spam_accuracy /= len(spam_test) for text in legit_test: prediction = NB_classifier.predict(text) legit_accuracy += 1 - prediction legit_accuracy /= len(legit_test) print("Spam Text prediction accuracy:", spam_accuracy) print("Legit Text prediction accuracy:", legit_accuracy) text_spam = "Win Free Money now! Apply today and get cash!" text_legit = "A usual day without anything interesting" print(text_spam, NB_classifier.predict(text_spam))