Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create gaussian_discriminant_analysis.py #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions generative_models/gaussian_discriminant_analysis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import numpy as np
import pandas as pd
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that you did not use pandas package in your code. So I think you could remove this line.



class GaussianDiscriminantAnalysis(): ## requires data as a pandas dataframe in the format [atribute, atribute, ....., class]
def __init__(self, df):
self.data = df
self.N = self.data.shape[0]
self.classes = list(set(self.data.iloc[:, -1]))
self.splits = []
self.means = []
self.covariances = []
for label in self.classes:
split = self.data.loc[self.data.iloc[:, -1] == label].iloc[:, 0:-1].astype(float)
self.splits.append(split)
self.means.append((np.mean(np.asarray(split),axis=0)))
self.covariances.append(np.cov(np.asarray(split), rowvar=False))

def gaussian_Probability(self, x, mean, covariance):
n = np.shape(x)[0]
nominator = np.exp((-0.5) * (np.dot(np.transpose(x - mean), np.matmul(np.linalg.inv(covariance), (x - mean)))))
denominator = (((2.0 * np.pi) ** (n / 2.0)) * np.sqrt(np.linalg.norm(covariance)))
return np.divide(nominator, denominator)

def classify(self, datapoint):
# print("-------------------\n")
# print(datapoint)
classification = {}
p_of_x_given_y = []
P_of_Y = []
P_of_Y_given_X = []
for index, label in enumerate(self.classes):
split = self.data.loc[self.data.iloc[:, -1] == label].iloc[:, 0:-1]
# print(index,label)
P_of_Y.append(len(split) / (self.N))
p_of_x_given_y.append(self.gaussian_Probability(datapoint, self.means[index], self.covariances[index]))
P_of_X = sum([p_of_x_given_y[i] * P_of_Y[i] for i in range(len(self.classes))])
# print(P_of_Y,"P(Y)")
# print(p_of_x_given_y,"P(X|Y)")
# print(P_of_X, "P(X)")#
for index, label in enumerate(self.classes):
P_of_Y_given_X.append((p_of_x_given_y[index] * P_of_Y[index]) / P_of_X)
classification.update({str(label): (p_of_x_given_y[index] * P_of_Y[index]) / P_of_X})

return classification