Naive bayes classifier 파이썬 구현

양현준·2022년 10월 4일
0

Naive bayes classifier 은, 특정 input xx = (x1x_1, x2x_2, ... xnx_n) 이 어떤 class에 속할 확률이 가장 높은지를 classify 해주는 머신러닝 학습 방법이며, 우리는 각각의 feature 들이 서로 독립적이라는 가정 하에 각각의 feature 에 해당하는 xix_i 값 들이 가능한 class에 속

#1. log likelihood probability 계산 함수 작성
from collections import Counter


def log_likelihood_probability(df, cx, cy):
  df = df.copy()
  prob = np.zeros((len(df[cy].unique()), len(df[cx].unique())))
  
  for label in range(len(df[cy].unique())):
    length = len(df[df[cy]==label])
    count = dict(Counter(df[df[cy] == label][cx]))

    for i in count.keys():
      prob[label][i]=count[i] / length
  
  log_prob = np.log(prob)
  return log_prob

#2. log class prior probability 계산 함수 작성

def log_class_prior_probability(df, cy):
  prob = np.zeros((len(df[cy].unique())))
  length = len(df[cy])
  for label in df[cy].unique():
    count = dict(Counter(df[df[cy]==label][cy]))
    prob[label]=count[label]/length

  log_prob = np.log(prob)
  return log_prob

#3. log posterior probability을 사용하여 예측하는 Naive Bayes Classifier 함수 작성

def naive_bayes_classifier(df, x):
  
  columns = df.columns[:-1]
  matrix = []
  i=0
  for col in columns:
    p = list(log_likelihood_probability(df, columns[0], df.columns[-1])[:,x[i]])
    matrix.append(p)

  matrix.append(list(log_class_prior_probability(df, df.columns[-1])))
  matrix = np.array(matrix)
  sum = np.sum(matrix, axis=0)

  index = np.argmax(sum)
  return index
profile
2022.08.13~

0개의 댓글