from sklearn.datasets import load_iris
iris = load_iris()
iris_feature = iris.data
iris_target = iris.target
#데이터를 불러왔으면 반드시 shape을 확인해 보아야합니다. -> 행개수 와 열개수 구하는것.
print("feature shape :()".format(iris_feature.shape))
print("target shape : ()".foramt(iris_target.shape))
결과값 :
feature shape : (150, 4)
target shape : (150, )
import pandas as pd
feature_names = iris.feature_names
iris_df = pd.DataFrame(
data = iris_feature,
columns = feature_names
)
iris_df['target'] = iris_target
iris_df.head(10)
# 분류 문제에서 가장 중요하게 확인할 내용
# 타겟의 개수 확인 (비율 확인)
iris_df['target'].value_counts()
학습 데이터 / 테스트 데이터 분리하기
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
iris_df.drop['target'], axis = 1 ), #Feature Matrix, target 컬럼을 제외하고 다른 열들을 선택
iris_df['target'], # Target Vector
test_size = 0.2, # 테스트 세트의 비율. 보통은 0.2~ 0.3
random_state = 11 # 랜덤 시드 고정값
)
print(" 훈련 데이터의 shape : {}".format(X_train.shape))
print(" 테스트 데이터의 shape : {}".format(y_test.shape))
결과 값:
훈련 데이터의 shape : (120, 4)
테스트 데이터의 shape : ( 30, 40)
모델 훈련
#의사결정나무 분류기 사용
from sklearn.tree import DecisionTreeClassifier
#모델 객체 생성 - 모델의 각종 옵션(하이퍼 파라미터)을 설정한다.
dt_clf = DecisionTreeClassifier()
#모델 훈련 - 훈련이 다 끝나면, 학습된 모델이 Return 된다.
#fit()메소드 - 훈련시키는 메소드
dt_clf.fit(X_train, y_train)
테스트 데이터 예측
pred = dt_clf.predict(X_test)
#예측할때는 Feature만 넣기.
#테스트 데이터의 차원 = 훈련 데이터의 차원
print("테스트 세트의 예측 결과 : {}.format(pred))
결과값 :
테스트 세트의 예측 결과 : [2 2 1 2 2 0 1 0 0 1 1 1 1 2 2 0 2 1 2 2 1 0 0 1 0 0 2 1 .... ]
평가
예측 정확도 ( Accuracy) 평가
from sklearn.metrics import accuracy_score
acc_result = accuracy_score(y_test, pred)
print("예측 정확도 : {:.4f}".format(acc_result))
결과 :
예측정확도 : 0.8667
총 정리 : 데이터 로드 --> iris데이터를 DataFrame으로 만들기( 데이터와 열 이름 넣기) target 추가하기
--> 학습 데이터 / 테스트 데이터 분리하기 --> 모델 훈련 시키기 --> 테스트 데이터 예측하기
--> 평가하기 ( 예측정확도 )
'한국경제신문(toss bank)' 카테고리의 다른 글
데이터 세트 훈련 교차 검증 (KFold, Stratified, cross_val_score,GridSearchCV) (0) | 2024.08.01 |
---|---|
데이터 세트 분리, 모델 학습(fit), 예측 수행(predict), 평가(evaluate) (0) | 2024.07.31 |
머신러닝 사이킷런 ( sklearn ) (0) | 2024.07.30 |
머신러닝의 유형 및 단점 (0) | 2024.07.29 |
머신러닝의 개념 Machine Learning (0) | 2024.07.29 |