-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmy_NB.py
38 lines (30 loc) · 1.29 KB
/
my_NB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import pandas as pd
import numpy as np
from collections import Counter
class my_NB:
def __init__(self, alpha=1):
# alpha: smoothing factor
# P(xi = t | y = c) = (N(t,c) + alpha) / (N(c) + n(i)*alpha)
# where n(i) is the number of available categories (values) of feature i
# Setting alpha = 1 is called Laplace smoothing
self.alpha = alpha
def fit(self, X, y):
# X: pd.DataFrame, independent variables, str
# y: list, np.array or pd.Series, dependent variables, int or str
self.classes_ = list(set(list(y)))
# Calculate P(yj) and P(xi|yj)
# make sure to use self.alpha in the __init__() function as the smoothing factor when calculating P(xi|yj)
# write your code below
return
def predict(self, X):
# X: pd.DataFrame, independent variables, str
# return predictions: list
# write your code below
return predictions
def predict_proba(self, X):
# X: pd.DataFrame, independent variables, str
# prob is a dict of prediction probabilities belonging to each categories
# return probs = pd.DataFrame(list of prob, columns = self.classes_)
# P(yj|x) = P(x|yj)P(yj)/P(x)
# write your code below
return probs