import numpy as np import pandas as pd import matplotlib.pyplot as plt
- Data Collection
from sklearn.datasets import load_iris iris_dataset = load_iris()iris_dataset.keys()- Data Preparation
# 훈련데이터와 테스트데이터 분리 #train_test_split(arrays, # 분할 시킬 데이터를 입력 # test_size, # 테스트 데이터셋의 비율 # train_size, # 학습 데이터셋의 비율 # random_state, # 데이터 분할 시 셔플이 이루어지는데 이를 위한 시드값 # shuffle, # 셔플여부 설정 # stratify # 지정한 데이터의 비율을 유지 # ) from sklearn.model_selection import train_test_split # train_test_split함수는 디폴트값이 75%의 훈련데이터, 25%의 테스트데이터 X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state = 0)X_train.shape- Choose a model
- Train the model
knn.fit(X_train, y_train)- Evaluate the model
#예측하기 # 만약 야생에서 꽃받침의 길이가 5cm, 폭이 2.9cm, 꽃잎의 길이가 1cm, 폭이 0.2cm인 붓꽃을 보았다면 X_new = np.array([[5, 2.9, 1, 0.2]]) prediction = knn.predict(X_new) prediction # 예측값이 0 즉, setosa=> 97%의 확률로 붓꽃의 품종을 정확히 맞춤
+)
- 산점도 그래프를 보면 sepal length, sepal width 2개의 특성만 가지고도 분류가 가능해보임
- 2개의 특성만 학습하여 머신러닝을 수행해보자
- Data Preparation
# 훈련데이터와 테스트데이터로 나누기 X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'][:,:2], iris_dataset['target'], random_state = 0)- Choose a model
- Train the model
knn.fit(X_train, y_train)- Evaluate the model
knn.score(X_test, y_test)- Hyperparameter tuning
# 하이퍼파라미터 튜닝(이웃의 수를 조절하며 정확도 보기) from sklearn import metrics train_list = [] test_list = [] for k in range(1, 20, 2) : knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X_train, y_train) train_pred = knn.predict(X_train) train_score = metrics.accuracy_score(train_pred, y_train) train_list.append(train_score) test_pred = knn.predict(X_test) test_score = metrics.accuracy_score(test_pred, y_test) test_list.append(test_score)plt.figure(figsize=(8,5)) plt.plot(range(1, 20, 2), train_list, label = 'Train acc') plt.plot(range(1, 20, 2), test_list, label = 'Test acc') plt.legend() plt.xlabel('n_neighbors') plt.ylabel('Accuracy') plt.title('Iris')