Menu
CoddyTech

트리 읽기

Coddy Machine Learning 여정의 지도 학습 섹션에 포함된 레슨. 58개 중 28번째.

트리의 질문은 읽을 수 있으므로 트리가 무엇을 학습했는지 확인할 수 있습니다. 길이 5.1 cm, 너비 1.6 cm인 꽃을 아이리스 트리에서 따라가 보세요:

주황색으로 한 경로가 강조된 상자 형태의 아이리스 트리: 꽃잎 너비가 0.80 이하인가요? 아니요, 1.6입니다. 꽃잎 길이가 4.95 이하인가요? 아니요, 5.1입니다. 경로는 클래스 2에서 끝납니다

export_text는 동일한 질문을 텍스트로 출력하며, 수준마다 들여쓰기 한 단계씩 적용합니다:

from sklearn.tree import export_text

print(export_text(tree, feature_names=["petal_length", "petal_width"]))

다음과 같이 출력됩니다:

|--- petal_width <= 0.80
|   |--- class: 0
|--- petal_width >  0.80
|   |--- petal_length <= 4.95
|   |   |--- class: 1
|   |--- petal_length >  4.95
|   |   |--- class: 2

각 행은 자신의 경로에 있는 질문에만 답합니다. Class 2는 virginica이며, 길고 넓은 꽃잎에 적절한 답입니다.

challenge icon

챌린지

중급

치즈 가게의 트리는 수분 함량과 숙성 주수를 바탕으로 치즈를 fresh, soft 또는 hard로 판별합니다. 시작 코드는 트리를 학습시키고 새 치즈를 입력받습니다.

  1. 특성 이름과 함께 트리의 질문을 출력하세요.
  2. 트리를 실행해 질문을 확인한 다음, if/else를 사용해 같은 질문을 하고 같은 답을 반환하도록 by_hand를 완성하세요.

출력된 결과를 바탕으로, 트리가 soft라고 판별하는 치즈의 경우:

By hand: soft
The tree: soft

직접 해보기

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text

# 치즈 하나당 한 행: 수분 함량(%), 숙성 기간(주), 치즈 종류
cheeses = pd.read_csv("cheeses.csv")
features = ["moisture_pct", "aged_weeks"]
X_train, X_test, y_train, y_test = train_test_split(cheeses[features], cheeses["cheese"], test_size=0.25, random_state=0)
tree = DecisionTreeClassifier(max_depth=2, random_state=0)
tree.fit(X_train, y_train)

# 종류를 알아낼 새 치즈
moisture = int(input())
aged = int(input())
new_cheese = pd.DataFrame([[moisture, aged]], columns=features)

# 아래에 코드를 작성하세요: 트리를 출력한 다음, 트리와 같은 방식으로 by_hand에서 답하세요


def by_hand(moisture, aged):
    return "fresh"


# 아래 줄은 변경하지 마세요
print("By hand:", by_hand(moisture, aged))
print("The tree:", tree.predict(new_cheese)[0])
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

지도 학습의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러