머신러닝 / 규칙기반 알고리즘(oneR, Riper) 파이썬 구현
52 규칙기반 알고리즘(oneR, Riper) 을 파이썬으로 구현
oneR알고리즘 관련 패키지는 R에만 있고 파이썬에는 없음.
R에서의 Riper 패키지는 이진분류, 다중분류 둘 다 분류가 가능한 패키지
그런데 파이썬의 Riper 패키지는 이진분류만 가능함.
구현을 위해 먼저 아나콘다 프롬프터창에 아래의 패키지를 설치해야함.
pip install wittgenstein
#1. 데이터 로드
#2. 결측치 확인
#3. 학습데이터와 라벨설정
#4. 훈련데이터와 테스트 데이터 분리
#5. 모델 생성
#6. 모델 훈련
#7. 모델 예측
#8. 모델 평가
#1. 데이터 로드
import pandas as pd
mush = pd.read_csv("c:\\data\\mushrooms.csv")
mush.shape #(8124, 23)
#2. 결측치 확인
mush.isnull().sum() #결측치 없음
#3. 학습데이터와 라벨설정
x= mush.iloc[:,1:] #정답컬럼 제외한 나머지
y = mush['type'] #정답컬럼
파이썬의 Riper패키지가 라벨(정답)을 0과 1 또는 False와 True로 되어있는 데이터만 받기 때문에 사이킷런의 label encoder로 변환해줌
#정답컬럼을 0,1로 변환
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
encoder.fit(y)
y2 = encoder.transform(y) #관심범주(poisonous)가 1
#관심범주를 확인하는 코드
print(encoder.classes_) #['edible' 'poisonous'] = [0,1]
type(y2) #0과 1로 변환한 정답컬럼이 numpy.ndarray형태가 됨
x2 = x.to_numpy() #학습데이터도 똑같이 numpy.ndarray형태로 바꿔줌
type(x2) #numpy.ndarray
#4. 훈련데이터와 테스트 데이터 분리
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x2,y2,test_size = 0.2, random_state = 1)
print(x_train.shape) #(6499, 22)
print(x_test.shape) #(1625, 22)
print(y_train.shape) #(6499,)
print(y_test.shape) #(1625,)
#5. 모델 생성
import wittgenstein as lw
model = lw.RIPPER(random_state = 1)
model
#6. 모델 훈련
model.fit(x_train, y_train)
#7. 모델 예측
result = model.predict(x_test)
result
#8. 모델 평가
sum(result == y_test) / len(y_test) * 100 #100.0% 정확도
규칙기반 Riper 알고리즘은 사이킷런에 내장되어 있지 않음. 별도의 패키지인 wittgenstein을 pip으로 설치하고 사용해야 함. 사이킷런의 머신러닝 모델들은 학습 데이터를 전부 0과 1로 변경해줘야 했는데 wittgenstein패키지에서는 변경안해줘도 됨. 대신 정답컬럼만 0과 1로 변경해줘야함.
> 파이썬에서는 어떤 규칙으로 어떻게 분류했는지 확인할 수 없음. 확인하고 싶으면 R로 확인해야함.
p246. 5장에서는 특징값에 따라 데이터를 분할하는 소위 '탐욕(greedy)' 알고리즘을 사용하는 두 개의 분류방법을 다뤘음. 의사결정트리는 분할 정복 전략을 사용해 플로차트와 같은 구조를 생성하는 반면 규칙 학습자는 논리적인 if-else 규칙을 식별해 데이터를 분리하고 정복함. 두 방법 다 통계적 배경없이도 해석될 수 있는 모델을 생성
문제279. 독일은행 데이터에서 채무 불이행자를 예측하는 분류모델을 Riper 알고리즘으로 만드시오.
(데이터 : credit.csv)
#1. 데이터 로드
import pandas as pd
credit = pd.read_csv("c:\\data\\credit.csv")
credit.shape #(1000, 17)
#2. 결측치 확인
credit.isnull().sum() #결측치 없음
#3. 학습데이터와 라벨설정
x = credit.iloc[:,:-1]
y = credit.iloc[:,-1]
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
encoder.fit(y)
y2 = encoder.transform(y)
print(encoder.classes_) #['no' 'yes'] = [0,1]
x2 = x.to_numpy()
#4. 훈련데이터와 테스트데이터 분리
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x2,y2,test_size = 0.1, random_state = 1)
print(x_train.shape) #(900, 16)
print(x_test.shape) #(100, 16)
print(y_train.shape) #(900,)
print(y_test.shape) #(100,)
#5. 모델생성
import wittgenstein as lw
model = lw.RIPPER(random_state = 1)
#6. 모델훈련
model.fit(x_train,y_train)
#7. 모델예측
result_credit = model.predict(x_test)
#8. 모델평가
acc = sum(result_credit == y_test) / len(y_test) * 100 #69.0% 정확도
print(acc)
from sklearn.metrics import confusion_matrix
tn, fp, fn, tp = confusion_matrix(y_test, result_credit).ravel()
print(fn) #26
독일은행 테스트 데이터에 대해서 69% 정확도를 보이고 있음.(random_state = 5일경우 72%까지 나오기는 함)
독버섯 데이터의 경우 나이브 베이즈 알고리즘에서는 FN값이 1개가 나왔는데 Riper 알고리즘의 경우 Fn값 0에 정확도 100%의 성능을 보이고 있어서 독버섯 데이터는 나이브 베이즈보다 Riper알고리즘이 더 적합한 모델.
독일은행 데이터의 경우 Riper 알고리즘이 의사결정트리에서와 비슷한 정확도가 출력되고 있어서 다른 알고리즘을 더 사용해봐야 더 정확도를 올릴 수 있을지 결정될 것 같음.