Creative Code

트리(graphviz) 본문

코딩 study/python

트리(graphviz)

빛하루 2023. 10. 31. 09:23

pip install graphviz 먼저 설치

# 필요한 라이브러리 및 모듈을 가져오기
from sklearn.tree import DecisionTreeClassifier  # 결정 트리 분류기를 사용하기 위한 모듈
from sklearn.datasets import load_iris  # 아이리스 데이터셋을 불러오기 위한 모듈
from sklearn.model_selection import train_test_split  # 데이터를 훈련 및 테스트 세트로 분할하기 위한 모듈
from sklearn.tree import export_graphviz  # 결정 트리를 시각화하기 위한 모듈
import graphviz  # 그래프 시각화 도구를 사용하기 위한 모듈
import pandas as pd  # 데이터프레임을 다루기 위한 판다스 라이브러리를 가져옵니다.

# 결정 트리 분류기를 생성하고 설정합니다
dt_clf = DecisionTreeClassifier(random_state=156, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1) 
# random_state: 무작위성을 조절하기 위한 시드값
# criterion: 정보 이득을 계산하는데 사용할 평가 지표 (gini 또는 entropy 사용)
# max_depth: 결정 트리의 최대 깊이 (None으로 설정하면 제한 없음)
# min_samples_split: 노드를 분할하기 위한 최소 샘플 수
# min_samples_leaf: 리프 노드가 가져야 할 최소 샘플 수

# 아이리스 데이터를 불러오고 훈련 및 테스트 세트로 분할합니다
iris = load_iris()  # 아이리스 데이터셋을 불러옵니다
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=11)
# iris.data: 입력 특성 데이터
# iris.target: 클래스 레이블 (타깃)
# test_size: 테스트 세트의 크기 (20%의 데이터를 테스트 세트로 설정)

# 결정 트리 모델을 훈련합니다
dt_clf.fit(X_train, y_train)

# 결정 트리를 시각화하여 "tree.dot" 파일에 저장합니다
export_graphviz(dt_clf, out_file='tree.dot', feature_names=iris.feature_names, class_names=iris.target_names)

# "tree.dot" 파일을 읽어 그래프를 시각화합니다
with open('tree.dot') as f:
    dot_graph = f.read()
graphviz.Source(dot_graph)

# 타이타닉 데이터의 전처리를 위한 함수들을 정의합니다
def fillna(df):
    df['Age'].fillna(df['Age'].mean(), inplace=True)  # 'Age' 열의 빈 값을 평균값으로 채웁니다
    df['Cabin'].fillna('N', inplace=True)  # 'Cabin' 열의 빈 값을 'N'으로 채웁니다
    df['Embarked'].fillna('N', inplace=True)  # 'Embarked' 열의 빈 값을 'N'으로 채웁니다
    df['Fare'].fillna(0, inplace=True)  # 'Fare' 열의 빈 값을 0으로 채웁니다
    return df

def drop_features(df):
    df.drop(columns=['PassengerId', 'Name', 'Ticket'], inplace=True)  # 불필요한 열을 삭제합니다
    return df

def format_features(df):
    from sklearn.preprocessing import LabelEncoder  # LabelEncoder를 사용하여 범주형 변수를 숫자로 변환합니다
    df['Cabin'] = df.Cabin.str[0]  # 'Cabin' 열의 첫 글자를 추출하여 저장합니다
    features = ['Cabin', 'Sex', 'Embarked']
    for feature in features:
        le = LabelEncoder()
        df[feature] = le.fit_transform(df[feature])  # 범주형 변수를 숫자로 변환합니다
        print(le.classes_)  # 변환된 클래스를 출력합니다
    return df

def transform_features(df):
    df = fillna(df)  # 빈 값 처리 함수를 호출하여 데이터프레임을 전처리합니다
    df = drop_features(df)  # 불필요한 열 삭제 함수를 호출하여 데이터프레임을 전처리합니다
    df = format_features(df)  # 범주형 변수 변환 함수를 호출하여 데이터프레임을 전처리합니다
    return df

# 타이타닉 데이터를 불러오고 전처리합니다
titanic = pd.read_csv('titanic_train.csv')  # 타이타닉 데이터를 데이터프레임으로 불러옵니다
y = titanic.Survived  # 생존 여부 (타깃) 데이터
x = titanic.drop(columns=['Survived'])  # 타깃 데이터를 제외한 나머지 데이터
x = transform_features(x)  # 전처리 함수를 호출하여 데이터를 전처리합니다

# 새로운 결정 트리 모델을 생성하고 타이타닉 데이터로 훈련합니다
dt_clf = DecisionTreeClassifier(random_state=156, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=11)
dt_clf.fit(X_train, y_train)

# 타이타닉 데이터의 결정 트리를 시각화하여 "titanic.dot" 파일에 저장합니다
export_graphviz(dt_clf, out_file='titanic.dot', feature_names=x.columns, class_names=['사망', '생존'], filled=True)

# "titanic.dot" 파일을 읽어 그래프를 시각화하고 "titanic.png" 파일로 저장합니다
with open('titanic.dot', encoding='utf8') as f:
    dot_graph = f.read()
graph = graphviz.Source(dot_graph)
print(graph)
graph.render(filename='titanic.png', format='png')