Path: blob/master/Part 3 - Classification/Naive Bayes/naive_bayes.py
1009 views
# Naive Bayes12# Importing the libraries3import numpy as np4import matplotlib.pyplot as plt5import pandas as pd67# Importing the dataset8dataset = pd.read_csv('Social_Network_Ads.csv')9X = dataset.iloc[:, [2, 3]].values10y = dataset.iloc[:, 4].values1112# Splitting the dataset into the Training set and Test set13from sklearn.cross_validation import train_test_split14X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)1516# Feature Scaling17from sklearn.preprocessing import StandardScaler18sc = StandardScaler()19X_train = sc.fit_transform(X_train)20X_test = sc.transform(X_test)2122# Fitting Naive Bayes to the Training set23from sklearn.naive_bayes import GaussianNB24classifier = GaussianNB()25classifier.fit(X_train, y_train)2627# Predicting the Test set results28y_pred = classifier.predict(X_test)2930# Making the Confusion Matrix31from sklearn.metrics import confusion_matrix32cm = confusion_matrix(y_test, y_pred)3334# Visualising the Training set results35from matplotlib.colors import ListedColormap36X_set, y_set = X_train, y_train37X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),38np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))39plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),40alpha = 0.75, cmap = ListedColormap(('red', 'green')))41plt.xlim(X1.min(), X1.max())42plt.ylim(X2.min(), X2.max())43for i, j in enumerate(np.unique(y_set)):44plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],45c = ListedColormap(('red', 'green'))(i), label = j)46plt.title('Naive Bayes (Training set)')47plt.xlabel('Age')48plt.ylabel('Estimated Salary')49plt.legend()50plt.show()5152# Visualising the Test set results53from matplotlib.colors import ListedColormap54X_set, y_set = X_test, y_test55X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),56np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))57plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),58alpha = 0.75, cmap = ListedColormap(('red', 'green')))59plt.xlim(X1.min(), X1.max())60plt.ylim(X2.min(), X2.max())61for i, j in enumerate(np.unique(y_set)):62plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],63c = ListedColormap(('red', 'green'))(i), label = j)64plt.title('Naive Bayes (Test set)')65plt.xlabel('Age')66plt.ylabel('Estimated Salary')67plt.legend()68plt.show()6970