코딩이야기

하루하루 코딩 이야기 1 : Iris 붓꽃 품종 예측하기

구경영 2023. 11. 14. 14:25
728x90

2023.11.14

 

 

동아리, 공모전, 팀플 등 매우 바쁜 와중에

내가 공부하는, 공부했던 자료에 대한 정리의 필요성을 느껴 정리해보고자 한다.

 

 

첫 시작은 사이킷런 패키지에서 제공하는 Iris Data 를 활용한

iris 붓꽃 품종 예측하기

 

 

글의 순서는

 

1. 사이킷런에 대한 소개와 특징
2. 데이터 불러오기
3. 학습 / 테스트 데이터셋 분리 후 점수 측정
4. 시각화

 


출처 : https://soyoung-new-challenge.tistory.com/30

1. 사이킷런 패키지에 대한 소개와 특징


(1) 사이킷런이란?
- 파이썬 머신러닝 라이브러리 중 가장 많이 사용되는 라이브러리


(2) 사이킷런의 특징
- 가장 이해하기 쉽고 간편한 API
- 다양한 알고리즘 및 프레임워크 제공
- 실전에서 검증된 라이브러리


(3) 사이킷런의 한계
- pytorch, tensorflow와 같은 딥러닝 전문 패키지보다
구현할 수 있는 알고리즘의 수준이 낮음

 


 

 

import pandas as pd
import numpy as np

# Data Loading
from sklearn.datasets import load_iris
iris = load_iris()
iris_df = pd.DataFrame(data = iris.data,
                       columns = iris.feature_names)
iris_df['label'] = iris.target

 


 

3. 학습 / 테스트 데이터셋 분리 후 점수 측정


Model은 DecisionTreeClassifier 사용
Scoring은 accuracy score 사용
test_size와 random_state는 각각 0.25 / 0으로 설정
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

X_train, X_test, y_train, y_test = train_test_split(iris.data, iris_df.label,
                                                    test_size = 0.25, random_state = 0)

model = DecisionTreeClassifier(random_state = 0)
model.fit(X_train, y_train)
pred = model.predict(X_test)

print('예측 정확도 :{0:.3f}'.format(accuracy_score(y_test, pred)))

 

import seaborn as sns
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

sns.boxplot(data=iris_df, x='label', y='sepal length (cm)', ax=ax1)
sns.boxplot(data=iris_df, x='label', y='sepal width (cm)', ax=ax2)

plt.rcParams['font.family'] = 'Malgun Gothic'
plt.suptitle('붓꽃 품종 별 Sepal 길이와 너비 차이')
ax1.set_title('Sepal Length')
ax1.set_xlabel('Iris 품종')
ax1.set_ylabel('Sepal Length (cm)')

ax2.set_title('Sepal Width')
ax2.set_xlabel('Iris 품종')
ax2.set_ylabel('Sepal Width (cm)')

plt.show()

 

 

붓꽃 품종별  petal length와 petal width 차이 boxplot으로 비교

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

sns.boxplot(data=iris_df, x='label', y='petal length (cm)', ax=ax1)
sns.boxplot(data=iris_df, x='label', y='petal width (cm)', ax=ax2)

plt.rcParams['font.family'] = 'Malgun Gothic'
plt.suptitle('붓꽃 품종 별 petal 길이와 너비 차이')
ax1.set_title('petal Length')
ax1.set_xlabel('Iris 품종')

ax2.set_title('pepal Width')
ax2.set_xlabel('Iris 품종')

plt.show()

 

수치형 변수에 따른 붓꽃 품종 scatter plot 시각화

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
sns.scatterplot(data = iris_df, x = 'sepal length (cm)', y = 'sepal width (cm)', hue = 'label', ax = ax1, s = 50)
sns.scatterplot(data = iris_df, x = 'petal length (cm)', y = 'petal width (cm)', hue = 'label', ax = ax2, s = 50)

plt.suptitle('붓꽃 품종 scatter plot')
plt.show()

sepal에 비해서 petal 변수가 더 품종을 잘 분리할 수 있도록 도와주는 것을 확인

 

728x90