from sklearn.datasets import load_iris
iris_dataset = load_iris()
iris_dataset # 중괄호: key와 value로 이루어져 있는 딕셔너리 타입
#0: setosa, 1:versicolor, 2: virginica
iris_dataset['target'] # 정답, label
iris_dataset['data'] # 문제집, feature
type(iris_dataset['data']) # 데이터 형태를 확인하고 싶을 때 사용
iris_dataset['target'].shape # 150건의 줄로 되어있다(feature가 없는 1차원 데이터)
iris_dataset['data'].shape # 150건의 feature가 4개인(4차원; 파이썬으로 말하면 column) 데이터
import matplotlib.pyplot as plt
import pandas as pd # 헷갈리면 판다스로 바꿔서 확인 가능
# 데이터프레임을 사용하여 데이터 분석(시각화) -> feature와 label의 연관성을 확인
iris_df = pd.DataFrame(iris_dataset['data'], columns=iris_dataset.feature_names)
iris_df.head(150)
iris_df.info()
# 각 feature들의 산점도 행렬 4 X 4
pd.plotting.scatter_matrix(iris_df, c= iris_dataset['target'], figsize=(15,15),
marker='o', hist_kwds={'bins':20}, s=60, alpha=.8)
# marker: 동그라미
# his_kwds: 히스토그램 키워드
# s: 마커 사이즈
# c: 마커 컬러
# alpha: 투명도
plt.show()
import numpy as np
plt.imshow([np.unique(iris_dataset['target'])])
#그린 차트의 타겟들이 어떻게 구성되어 있는지 확인가능 근데 이름은 모름... 어떻게 하면 될까?
_=plt.xticks(ticks=np.unique(iris_dataset['target']), labels=iris_dataset['target_names'])
언더스코어: 값을 사용하지 않을 거면(출력하지는 않을 거면) 변수에 담아서 사용만 안 함
즉, return받는 값을 사용하지는 않음, 변수 이름이 '_'이다.
명명을 특징있게 적으면 변수 사용하는 것처럼 보이니까...(코딩 약속)
언더스코어 적용 전
언더스코어 적용 후
iris_dfp = iris_df[['petal width (cm)','petal length (cm)']]
# 각 feature들의 산점도 행렬 2 X 2
pd.plotting.scatter_matrix(iris_dfp, c= iris_dataset['target'], figsize=(15,15),
marker='o', hist_kwds={'bins':20}, s=60, alpha=.8)
plt.show()
# <분류에 필요한 변수>
# (문제지) data > x_train/x_test
# (정답지) target > y_train/y_test
iris_dataset['target']
from sklearn.model_selection import train_test_split
# 아래와 같이 변수를 분리해서 줌
# <분류에 필요한 변수>
# (문제지) data > x_train/x_test
# (정답지) target > y_train/y_test
X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'],
test_size=0.25, random_state=777)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
# 가장 가깝게 있는 데이터 셋 1개를 보고 예측해볼게
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
y_pred
#정확도 확인
# 1) mean() 함수를 사용해서 정확도 확인
np.mean(y_pred == y_test)
# 2) score() 함수를 사용해서 정확도 확인 -> 테스트 셋으로 예측한 후 정확도 출력
knn.score(X_test, y_test)
# 평가지표 계산(precison과 recall, f1-score를 활용)
from sklearn import metrics
knn_report = metrics.classification_report(y_test, y_pred)
print(knn_report)
#라이브러리 임포트
import mglearn
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore') #오류 빨강색, 워닝 노란색
# 데이터셋 다운로드
X , y = mglearn.datasets.make_forge()
print("X.shape : ", X.shape)
print("y.shape : ", y.shape)
y
plt.figure(dpi=150)
plt.rc('font', family='NanumBarunGothic')
# 산점도 그리기
mglearn.discrete_scatter(X[:,0], X[:,1], y)
#이진분류이기 때문에 class 값은 두개임
plt.legend(['클래스0','클래스1'], loc=4)
plt.xlabel("첫 번째 특성")
plt.ylabel("두 번째 특성")
plt.show()
#데이터 셋 다운로드
X, y = mglearn.datasets.make_wave(n_samples=40)
print("X.shape : ", X.shape) #하나의 feature로 이루어져 있음
print("y.shape : ", y.shape)
y
# 산점도 X, y
plt.figure(dpi=100)
plt.rc('font', family='NanumBarunGothic')
plt.rcParams['axes.unicode_minus'] = False #음수 오류 방지
plt.plot(X,y,'o')
plt.ylim(-3,3)
plt.xlabel("특성")
plt.ylabel("타깃")
plt.show()
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
cancer['target_names']
cancer['target']
cancer['data'].shape
cancer['DESCR']
import matplotlib.pyplot as plt
import pandas as pd # 헷갈리면 판다스로 바꿔서 확인 가능
# 데이터프레임을 사용하여 데이터 분석 -> feature와 label의 연관성을 확인
c_df = pd.DataFrame(cancer['data'], columns=cancer.feature_names)
import numpy as np
plt.imshow([np.unique(cancer['target'])])
#그린 차트의 타겟들이 어떻게 구성되어 있는지 확인가능 근데 이름은 모름... 어떻게 하면 될까?
_=plt.xticks(ticks=np.unique(cancer['target']), labels=cancer['target_names'])
pd.plotting.scatter_matrix(c_df, c= cancer['target'], figsize=(15,15),
marker='o', hist_kwds={'bins':20}, s=10, alpha=.8)
plt.show()
from sklearn.datasets import load_boston
boston = load_boston()
boston.data.shape
boston.target
boston.feature_names
<참고. 보스턴 집값 데이터의 feature 정보>
CRIM per capita crime rate by town
ZN proportion of residential land zoned for lots over 25,000 sq.ft.
INDUS proportion of non-retail business acres per town
CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
NOX nitrogen oxides concentration (parts per 10 million)
RM average number of rooms per dwelling
AGE proportion of owner-occupied units built prior to 1940
DIS weighted mean distances to five Boston employment centres
RAD index of accessibility to radial highways
TAX full-value property-tax rate per $10,000
PTRATIO pupil-teacher ratio by town
B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
LSTAT lower status of the population (%)
MEDV Median value of owner-occupied homes in $1000's
CRIM: 지역별 범죄발생률
ZN: 25,000평방피트를 넘는 거주 지역의 비율
INDUS: 도시별 비상업 지역의 넓이 비율
CHAS: 찰스강에 대한 더미 변수(1 = 강의 경계, 0 = 나머지)
NOX: 일산화질소 농도
RM: 거주할 수 있는 평균 방의 개수
AGE: 1940년 이전에 지어진 소유 주택의 비율
DIS: 5개의 주요 고용센터까지의 가중치가 고려된 거리
RAD: 고속도로의 접근 용이도
TAX: 10,000달러당 재산세 비율
PTRATIO: 지역의 교사와 학생 수 비율
B: 지역의 흑인 거주 비유
LSTAT: 하위 계층의 비율
MEDV: 본인 소유 주택 가격의 중앙값
pip install mglearn
import mglearn
import matplotlib.pyplot as plt
import warnings
warnings. filterwarnings('ignore')
plt.figure(dpi=100)
mglearn.plots.plot_knn_classification(n_neighbors = 1)
plt.figure(dpi=100)
mglearn.plots.plot_knn_classification(n_neighbors = 3)
plt.figure(dpi=100)
mglearn.plots.plot_knn_classification(n_neighbors = 5)
Forge 데이터 셋을 활용한 이진 분류 문제로 정의
X, y = mglearn.datasets.make_forge()
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=7)
X_train.shape
X_test.shape
y_train.shape
y_test.shape
From sklearn.neighbors import KNeighborsClassfier
clf =KNeighborsClassifier(n_neighbors=3)
clf.fit(X_train,y_train)
#테스트 정확도
clf.score(X_test, y_test)
#훈련 정확도
clf.score(X_train, y_train)
#이웃의 수에 따른 정확도를 저장할 리스트 변수 선언
train_scores = []
test_scores = []
num_settings = range(1,16) # 유지 보수 용이성을 위해 변수로 선언
for num_neighbor in num_settings:
#모델 생성
clf = KNeighborsClassifier(n_neighbors=num_neighbor)
clf.fit(X_train, y_train)
#훈련 세트 정확도 저장
train_scores.append(clf.score(X_train, y_train))
#테스트 세트 정확도 저장
test_scores.append(clf.score(X_test, y_test))
#예측 정확도 비교 그래프 그리기
plt.figure(dpi=100)
plt.plot(num_settings, train_scores, label='훈련 정확도')
plt.plot(num_settings, test_scores, label='테스트 정확도')
plt.ylabel('정확도')
plt.xlabel('이웃의 수')
plt.legend()
plt.show() #sweet spot = 3
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
from sklearn.model_Selection import train_test_split
X_train, X_test, y_train, y_test = train_test_slplit(cancer.data, cancer.target, random_state =7)
cancer.data.shape
X_train.shape #75% 훈련 데이터
X_test.shape # 25% 훈련 데이터
#이웃에 수에 따른 정확도를 저장할 리스트 변수 선언
train_scores = []
test_scores = []
num_settings = range(1,11) # 유지 보수 용이성을 위해 변수로 선언
#1~10까지 n_neighbors의 수를 증가시켜서 학습 후 정확도 저장
for num_neighbor in num_settings:
#모델 생성
clf = KNeighborsClassifier(n_neighbors=num_neighbor)
clf.fit(X_train, y_train)
#훈련 세트 정확도 저장
train_scores.append(clf.score(X_train, y_train))
#테스트 세트 정확도 저장
test_scores.append(clf.score(X_test, y_test))
#예측 정확도 비교 그래프 그리기
plt.figure(dpi=100)
plt.plot(num_settings, train_scores, label='훈련 정확도')
plt.plot(num_settings, test_scores, label='테스트 정확도')
plt.ylabel('정확도')
plt.xlabel('이웃의 수')
plt.legend()
plt.show()