결정트리를 이용한 붓꽃 데이터 분류의 구현¶
붓꽃 데이터는 sklearn.datasets에 들어 있음.
from sklearn.datasets import load_iris
붓꽃 데이터를 로딩하면, Bunch라는 것이 생기는데, 간단히 dictionary 같은 것임임
iris = load_iris()
print(f"iris type: {type(iris)}")
iris type: <class 'sklearn.utils._bunch.Bunch'>
붓꽃 데이터는 'data'와 'target'으로 구성되어 있음.
- 150개 꽃에 대한 정보가 담겨 있음.
- 'data'는 꽃받침과 꽃잎 길이와 폭의 4가지 숫자들로 구성
- 'target'은 붓꽃 종류가 0, 1, 그리고 2로 표시
X, y = iris.data, iris.target
print(f"iris.data type: {type(iris.data)} shape: {iris.data.shape}")
print(iris['data'][:5])
print(f"iris.target type: {type(iris.target)} shape: {iris.target.shape}")
print(iris['target'][:5])
iris.data type: <class 'numpy.ndarray'> shape: (150, 4) [[5.1 3.5 1.4 0.2] [4.9 3. 1.4 0.2] [4.7 3.2 1.3 0.2] [4.6 3.1 1.5 0.2] [5. 3.6 1.4 0.2]] iris.target type: <class 'numpy.ndarray'> shape: (150,) [0 0 0 0 0]
학습과 테스트를 위해, 150개를 8:2 (train:test) 비율로 나눔
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=True, random_state=119)
print(X_train.shape, X_test.shape)
print(y_train.shape, y_test.shape)
(120, 4) (30, 4) (120,) (30,)
결정 트리를 만들고, 데이터로 학습 시킨다.
from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier()
dt.fit(X_train, y_train)
DecisionTreeClassifier()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| criterion | 'gini' | |
| splitter | 'best' | |
| max_depth | None | |
| min_samples_split | 2 | |
| min_samples_leaf | 1 | |
| min_weight_fraction_leaf | 0.0 | |
| max_features | None | |
| random_state | None | |
| max_leaf_nodes | None | |
| min_impurity_decrease | 0.0 | |
| class_weight | None | |
| ccp_alpha | 0.0 | |
| monotonic_cst | None |
학습 완료된 결정트리에 테스트 데이터를 넣어서 정확도를 계산한다.
여기서는 90% 정도 나온다.
y_pred_dt = dt.predict(X_test)
from sklearn.metrics import accuracy_score
print("Accuracy - Decision Tree: {:.2f}".format(accuracy_score(y_test, y_pred_dt)))
Accuracy - Decision Tree: 0.90
'머신러닝' 카테고리의 다른 글
| 결정 트리 (decision tree)와 붓꽃 (iris) (6) | 2025.06.08 |
|---|---|
| 이름만 간지나는 AI engineering (2) | 2025.06.07 |
| 파이토치 모델 저장; pytorch model save (0) | 2022.11.06 |
| 파이토치(Pytorch) Distributed Data Parallel (DDP)사용하기 (0) | 2022.10.30 |
| Decision Tree; 결정트리; 의사결정트리 (0) | 2022.10.28 |



