In this we are going to see a basic example of naive bayes algorithm in Python Programming Language.
#note: need a comps.csv file in dir
import pandas as pd
data = pd.read_csv('Comps.csv')
# inp = list(map(str, input().split()))
inp = ["<=30","High","No","Fair"]
l = [x for x in data.keys()]
total = len(data.values)
cl = list(set(data[f'{l[-1]}']))
totlst = [data[data[f'{l[-1]}'] == f"{cl[i]}"].count()[0] for i in range(len(cl))]
problst = [totlst[i]/total for i in range(len(cl))]
dat = []
prob = [1]*len(cl)
for i in range(len(l)-1):
for j in range(len(cl)):
dat.append(data[data[f'{l[i]}'] == f"{inp[i]}"][data[f'{l[-1]}'] == f"{cl[j]}"].count()[0])
for k in range(len(cl)):
prob[k] *= dat[k]/totlst[k]
dat.clear()
prob = [prob[i]*problst[i] for i in range(len(cl))]
print("Prediction:",cl[prob.index(max(prob))])
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP