본문 바로가기

Study/class note

머신러닝 / 파이썬으로 나이브 베이즈 모델 생성하기

ㅇ 나이브 베이즈 코드 짜는 순서

# 1. 데이터 로드
# 2. 결측치 확인
# 3. 이상치 확인
# 4. 데이터 유형 확인
# 5. 데이터 정규화
# 6. 훈련 데이터와 테스트 데이터 분리
# 7. 나이브 베이즈 모델 생성 및 훈련
# 8. 테스트 데이터 예측
# 9. 모델 성능 평가 및 성능개선

 

46 파이썬으로 나이브 베이즈 모델 생성하기

"독버섯과 식용버섯을 분류하는 나이브 베이즈 모델 생성하기"

# python
# 1. 데이터 로드
import pandas as pd

mush = pd.read_csv("c:\\data\\mushrooms.csv")

# 2. 결측치 확인
mush.isnull().sum()

# 3. 이상치 확인 > 불필요
# 4. 데이터 유형 확인
mush.info()  # 모든 컬럼이 object인 것을 확인

R에서는 데이터를 문자형 그대로 훈련 시켰는데 파이썬에서는 데이터를 전부 숫자(0,1)로 변경해줘야함.

우선 정답컬럼(결과)을 훈련데이터/테스트데이터에서 제외시켜서 분리해야함.

x = mush.iloc[:,1:]  # 정답컬럼인 type 제외
x.head()

y = mush.iloc[:,0] # 정답컬럼인 type만 담음
y.head()

mush2 = pd.get_dummies(x)   # x에 있는 모든 데이터를 숫자로 변경시킴
mush2.head()
mush2.shape # (8124, 23)에서 (8124, 117)으로 컬럼이 늘어남
mush2.info() # 전부 숫자임을 확인함

숫자화된 mush2 데이터로 정규화 시켜서 모델링 해야함.

# 5. 데이터 정규화
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
scaler.fit(mush2)
mush2_scaled = scaler.transform(mush2)
mush2_scaled  # numpy.array 형태

y = y.to_numpy()  # 정답컬럼도 numpy.array 형태로 변환

# 6. 훈련 데이터와 테스트 데이터 분리
from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(mush2_scaled, y, test_size = 0.2, random_state = 1)

print(x_train.shape)  #(6499, 117)
print(x_test.shape)  #(1625, 117)

 

 

> 파이썬에서 나이브베이즈 모델 생성 시 3가지 방법이 있음

1. BernoulliNB : 이산형 데이터를 분류할 때 적합(정수형으로 딱 떨어지는 데이터)

2. GaussianNB : 연속형 데이터를 분류할 때 적합( 소수점이 있는 숫자형 데이터)

3. MultinominalNB : 이산형 데이터를 분류할 때 적함

# 7. 나이브 베이즈 모델 생성 및 훈련
from sklearn.naive_bayes import BernoulliNB
    # from sklearn.naive_bayes import GaussianNB
    # from sklearn.naive_bayes import MultinominalNB

model = BernoulliNB()
model.fit(x_train, y_train)

# 8. 테스트 데이터 예측
result = model.predict(x_test)
result

# 9. 모델 성능 평가
sum(result == y_test) / len(y_test)

>0.939076923076923 의 정확도가 나옴.

 

from sklearn.metrics import confusion_matrix

tn, fp, fn, tp = confusion_matrix(y_test,result).ravel()
print(tn,fp,fn,tp)  # 815 5 94 711

> FN 값 확인하기 : FN값이 94로 너무 많음 > 라플라스 값을 줘서 성능을 개선시킴

 

# 10. 모델 성능 평가 및 성능개선
from sklearn.naive_bayes import GaussianNB

model_lplc = GaussianNB(var_smoothing = 0.001)
model_lplc.fit(x_train, y_train)

result_lplc = model_lplc.predict(x_test)
result_lplc

sum(result_lplc == y_test) / len(y_test)  # 0.9950769230769231

from sklearn.metrics import confusion_matrix

tn, fp, fn, tp = confusion_matrix(y_test,result_lplc).ravel()
print(tn,fp,fn,tp)  # 814 6 2 803

> 라플라스 값을 주기 위해서는 GaussianNB 모듈을 임포트 해야함.

> 정확도는 0.9950769230769231이고 FN은 2로 정확도가 훨씬 높아짐.

 

문제252. for loop문을 이용해서 GaussianNB의 FN값을 최소화 할 수 있는 var_smoothing 값이 무엇인지 알아내시오.

# var_smoothing값 찾기
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix
import numpy as np
from tqdm import tqdm_notebook

for i in tqdm_notebook(np.arange(0.001,0.01,0.001)):
    model_lplc = GaussianNB(var_smoothing = i)
    model_lplc.fit(x_train, y_train)

    result_lplc = model_lplc.predict(x_test)
    tn, fp, fn, tp = confusion_matrix(y_test,result_lplc).ravel()
    if fn <= 1:
        print('var_smoothing = %s'%i)
        print('정확도 = %s'%(sum(result_lplc == y_test) / len(y_test)))
        print('FN = %s\n'%fn)

> 독버섯 데이터를 나이브 베이즈 모델 중에 GaussianNB로 학습 시켰을 때 정확도는 0.995까지 개선되었음. 그리고 FN값은 var_smoothing 0.001로 했을 때 2개까지 줄일 수 있음.

> random_state = 4로 설정하면 fn값이 0으로 나옴.

> random_state를 맞추면서 정확도를 높이면 train_data에만 적합한 모델이 될 수 있음. 다른 테스트 데이터에서 오버피팅일 수 있음. random_state는 웬만하면 하나로 셋팅해놓는게 좋음.

 

 

문제253. movie.csv데이터를 파이썬으로 로드하시오.

movie = pd.read_csv("c:\\data\\movie2.csv", encoding = 'cp949')
movie

문제254. 위의 데이터에서 결측치가 있는지 확인하시오.

movie.isnull().sum()

> 결측치 없음

 

문제255. 문자형 데이터를 숫자로 변경하세요.

m_x = movie.iloc[:,:5]  # 정답컬럼 제외
m_y = movie.iloc[:,5] # 정답컬럼만 담음

movie2 = pd.get_dummies(m_x)   # x에 있는 모든 데이터를 숫자로 변경시킴
m_y = m_y.to_numpy()

movie2

> 숫자로 변경하고 데이터타입은 모두 numpy array

> 정규화는 굳이 하지 않겠음. 0이랑 1이어서 굳이 하든 안하든 상관 없어보임

 

문제256. 위의 데이터를 훈련 데이터와 테스트 데이터로 분리하시오.

from sklearn.model_selection import train_test_split

x_train,x_test,y_train,y_test = train_test_split(movie2, m_y, test_size = 0.2, random_state = 2)

문제257. 위의 훈련데이터로 나이브베이즈 모델을 생성하고 테스트 데이터의 정확도를 확인하시오.

GaussianNB의 var_smoothing말고 BernoulliNB의 alpha 옵션으로 라플라스 값을 조정하시오.

 BernoulliNB의 alpha 옵션 default값이 1, 정확도 100%가 나오는 alpha값이 뭔지 알아내시오.

# 훈련데이터 테스트 데이터 분리
from sklearn.model_selection import train_test_split

x_train,x_test,y_train,y_test = train_test_split(movie2, m_y, test_size = 0.1, random_state = 2)

# 나이브 베이즈 모델 생성 및 훈련
from sklearn.naive_bayes import BernoulliNB
from sklearn.metrics import confusion_matrix
import numpy as np
from tqdm import tqdm_notebook
from sklearn.metrics import accuracy_score

ap_lst = []
for i in tqdm_notebook(np.arange(0.001,1.001,0.001)):
    model = BernoulliNB(alpha=i)
    model.fit(x_train, y_train)

    result = model.predict(x_test)    # 테스트 데이터 예측
    
    accuracy = accuracy_score(y_test,result)
    if accuracy == 1:
        ap_lst.append(round(i,3))
        
print('''0.001 ~ 1사이의 값을 0.001간격으로 alpha값을 대입했을 때,
정확도 100%%가 나오는 alpha의 개수는 %d개 입니다.\n'''%len(ap_lst))
print('정확도가 100%%인 alpha의 최소값은 %s이고 최대값은 %s입니다.\n'%(min(ap_lst), max(ap_lst)))
print(ap_lst)
반응형