728x90
반응형
In [2]:
### 라이브러리
import matplotlib.pyplot as plt
### 그래프 내에 한글이 포함된 경우 폰트 처리가 필요함
# 한글 깨짐 방지를 위하여 폰트 환경설정 라이브러리
from matplotlib import font_manager,rc
## 운영체제 확인을 위한 라이브러리
# import platform
plt.rc("font", family = "Malgun Gothic")
# plt.rd("font", family = "AppleGothic")
### 그래프 내에 마이너스 표시- 기호 적용하기
plt.rcParams["axes.unicode_minus"] = False
In [3]:
"""
<훈련, 검증, 테스트 데이터 분류시 주로 사용되는 변수명>
- 정의된 변수 이름은 없음,
- 훈련데이터: 훈련: 훈련(fit)에 사용되는 데이터
- : (훈련 독립변수) train_input, train_x, X_train
: (훈련 종속변수) train_target, tain_y, y_train
- 검증데이터: 훈련정확도(score)에 사용되는 데이터
:(검증 독립변수) val_input, val_x, X_val
:(검증 종속변수) val_target, val_y, y_val
- 테스트데이터: 예측(gredict)에 사용되는 데이터
:(테스트 독립변수) test_input, test_x, X_test
:(테스트 종속변수) test_targetm test_y, y_test
<데이터 분류 순서>
1. 훈련과 테스트를 비율로 먼저 나누기
- 훈련과 테스트 비율 : 주로 7:3을 사용 , 또는 7.5:2.5 또는 8:2
2. 훈련과 검증 데이터를 나누기(데이터가 많으면 )
- 훈련과 검증 비율: 주로 4:2 또는 6: 2를 사용
3. 가장 많이 사용되는 훈련 : 검증 : 테스트 비율 대략 => 6:2:2
"""
Out[3]:
' \n<훈련, 검증, 테스트 데이터 분류시 주로 사용되는 변수명>\n- 정의된 변수 이름은 없음,\n- 훈련데이터: 훈련: 훈련(fit)에 사용되는 데이터\n- : (훈련 독립변수) train_input, train_x, X_train\n : (훈련 종속변수) train_target, tain_y, y_train\n- 검증데이터: 훈련정확도(score)에 사용되는 데이터\n :(검증 독립변수) val_input, val_x, X_val\n :(검증 종속변수) val_target, val_y, y_val\n- 테스트데이터: 예측(gredict)에 사용되는 데이터\n :(테스트 독립변수) test_input, test_x, X_test\n :(테스트 종속변수) test_targetm test_y, y_test\n\n<데이터 분류 순서>\n1. 훈련과 테스트를 비율로 먼저 나누기\n - 훈련과 테스트 비율 : 주로 7:3을 사용 , 또는 7.5:2.5 또는 8:2\n\n2. 훈련과 검증 데이터를 나누기\n - 훈련과 검증 비율: 주로 4:2 또는 6: 2를 사용\n3. 가장 많이 사용되는 훈련 : 검증 : 테스트 비율 대략 => 6:2:2\n'
In [7]:
### 사용할 데이터 정의하기
fish_length = [25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0,
31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0,
35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0, 9.8,
10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0]
fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0,
500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0,
700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0, 6.7,
7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]
In [9]:
### 훈련에 사용할 데이터를 2차원 데이터 형태로 만들기
fish_data = [[l, w] for l, w in zip(fish_length, fish_weight)]
fish_data
len(fish_data)
Out[9]:
49
In [10]:
### 종속 변수 (생선이름) 생성하기
# - 1 1차원으로 생성합니다. : ["도미", "도미",,,"빙어"]
### 종속 변수로 사용하는 데이터 형태 : 정수형을 주로 사용
# - 범주 값의 갯수에 따라 : 0~n 값을 사용
# - 이진 분류: 0또는 1사용
# - 다중 분류: 0~n개 사용
### - 도미 : 방어 = 1: 0
# - 이진분류에서는 찾고자하는 값을 1로 정의하는 것이 일반적인 개념이다.
# - 다만, 어떤 값을 사용하여도 무관하긴하다.
fish_target = [1]*35 + [0]*14
# fish_target= [ "도미" for f in range(36) ]
len(fish_target)
Out[10]:
49
훈련 및 테스트 데이터로 분류하기¶
In [14]:
### 훈련데이터 (train)
# - 훈련 독립 변수
train_input= fish_data[:35]
# -훈련 종속변수
train_target=fish_target[:35]
print(len(train_input), len(train_target))
35 35
In [17]:
### 태스트데이터 (test)
# - 훈련 독립 변수
test_input= fish_data[35:]
# -훈련 종속변수
test_target=fish_target[35:]
print(len(test_input), len(test_target))
14 14
In [ ]:
모델 생성하기¶
In [18]:
from sklearn.neighbors import KNeighborsClassifier
In [19]:
### 모델 (클래스) 생성
# - 이웃의 갯수는 기본 값 사용
kn = KNeighborsClassifier()
kn
Out[19]:
KNeighborsClassifier()
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.
KNeighborsClassifier()
In [20]:
### 모델 훈련 시키기
# - 훈련 데이터 적용
kn.fit(train_input, train_target)
Out[20]:
KNeighborsClassifier()
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.
KNeighborsClassifier()
In [22]:
kn.score(train_input,train_target)
Out[22]:
1.0
In [26]:
# 훈련 정확도 확인하기
# - 훈련 데이터 사용 abs
train_score= kn.score(train_input, train_target)
### 검증하기
# - 테스트 데이터 사용
test_score = kn.score(test_input, test_target)
train_score, test_score
### (해석)
# - 훈련 정확도가 1이기 때문에 과대적합이 발생하였으며,
# - 검증 정확도가 0으로 나타났음
# --> 따라서 이 훈련 모델은 튜닝을 통해 성능 향상을 시켜야할 필요성이 있음
Out[26]:
(1.0, 0.0)
In [27]:
kn.predict([[1,100]])
Out[27]:
array([1])
In [28]:
### 원인 분석
# - 데이터 분류시 : 35개의 도미값으로만 훈련을 시켰기 때문에 발생한 문제
# 즉 , 검증데이터가 0이 나왔다는 것은, 또는 매우 낮은 정확도가 나온 경우
# *** 데이터에 변함이 발생했을 가능성이 있다고 의심해 봅니다.
# - 샘플링편향: 특정 데이터에 집중되어 데이터가 구성되어 훈련이 이루어 진 경우 발생하는 현상
# --> 해소 방법: 훈련/검증/테스트 데이터 구성시에 잘 섞어야 합니다. (셔플이라고 합니다.)
In [30]:
### 샘플링 편향 해소하기
# numpy 셔플링 함수 사용
import numpy as np
# 파이썬의 리스트를 넘파이의 배열타입으로 변경하기
In [37]:
### 넘파이 배열 형태로 변형하기
print(type(fish_data))
input_arr= np.array(fish_data)
target_arr = np.array(fish_target)
print(type(input_arr))
### 데이터 갯수 확인하기
# - shape : 차원을 확인하는 넘파이 속성(행,열)
# 독립변수: 2차원, 종속변수:1차원
input_arr.shape, target_arr.shape
<class 'list'>
<class 'numpy.ndarray'>
Out[37]:
((49, 2), (49,))
In [91]:
### 랜덤하게 섞기...
# - 랜덤 규칙 지장하기
# - random.seed(42): 데이터를 랜덤하게 생성할때 규칙성을 띄도록 정의
# : 숫자 값은 의미 없는 값으로 규칙을 의미함(42를 자주사용함)
np.random.seed(42)
In [92]:
index = np.arange(49)
index
Out[92]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48])
In [93]:
np.random.shuffle(index)
index
Out[93]:
array([13, 45, 47, 44, 17, 27, 26, 25, 31, 19, 12, 4, 34, 8, 3, 6, 40,
41, 46, 15, 9, 16, 24, 33, 30, 0, 43, 32, 5, 29, 11, 36, 1, 21,
2, 37, 35, 23, 39, 10, 22, 18, 48, 20, 7, 42, 14, 28, 38])
In [94]:
### 훈련 및 테스트 데이터 분류하기
train_input = input_arr[index[:35]]
train_target = target_arr[index[:35]]
test_input= input_arr[index[35:]]
test_target= target_arr[index[35:]]
print(train_input.shape, train_target.shape)
print(test_input.shape, test_target.shape)
(35, 2) (35,)
(14, 2) (14,)
In [97]:
len(train_input[:,1])
Out[97]:
35
In [ ]:
In [105]:
plt.figure(figsize=(5,5))
plt.scatter(train_input[:,0],train_input[:,1], c="red", label="1")
plt.scatter(test_input[:,0],test_input[:,1], c="blue", label="2")
# plt.scatter(test_target[:,0],test_target[:,1], c="red", label="빙어")
plt.xlabel("length")
plt.ylabel("weghit")
plt.title("물고기 크기별 무게", fontweight=700, fontsize=22)
plt.legend()
plt.show
# 해석
# - 임의 예측 데이터가 분포한 위치를 통해서 시각저그로 확인 가능
# - 모델(클래스)이 사용하는 기본 이웃의 값은 <<<<<<<<5>>>>>>>>>>개를 기준으로 합니다.
Out[105]:
<function matplotlib.pyplot.show(close=None, block=None)>
In [86]:
## 모델 생성하기
kn = KNeighborsClassifier()
kn
Out[86]:
KNeighborsClassifier(n_neighbors=17)
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.
KNeighborsClassifier(n_neighbors=17)
In [87]:
### 훈련시키기
kn.fit(train_input, train_target)
Out[87]:
KNeighborsClassifier(n_neighbors=17)
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.
KNeighborsClassifier(n_neighbors=17)
In [88]:
### 훈련 정확도 확인하기
train_score = kn.score(train_input, train_target)
### 검증 정확도 확인하기
test_score = kn.score(test_input, test_target)
train_score, test_score
Out[88]:
(1.0, 0.9285714285714286)
In [80]:
### 예측하기
test_pred = kn.predict(test_input)
print(f"predict: {test_pred}")
print(f"실제값: {test_target}")
predict: [1 1 0 0 0 1 1 1 1 1 1 0 0 1]
실제값: [1 1 0 0 0 1 1 1 1 1 1 0 1 1]
In [106]:
kn = KNeighborsClassifier()
kn.fit(train_input, train_target)
nScore= 0
### KNN 모델 생성하기
# n_neighbors : 이웃의 갯수(하이퍼 파라메터 속성)
### 모델 생성완료 했으니 모델 훈련시키기
nCnt=0
# kn20 = KNeighborsClassifier(n_neighbors=3)
# kn20.fit(fish_data, fish_target)
for n in range(3,len(train_input),2):
kn.n_neighbors=n
score= kn.score(train_input,train_target)
# 1보다 작은 정확도인 경우
if score> nScore and score!=1:
nScore=score
nCnt=n
print(n,score)
### 모델의 성능이 가장 좋은 시점의 이웃의 갯수를 추출하기 위해
# - 하이퍼 파라메터 튜닝 결과 , 이웃의 갯수 19개를 사용했을 때
# - 가장 좋은 성능을 발휘하는 것으로 확인됨
3 1.0
5 1.0
7 1.0
9 1.0
11 1.0
13 1.0
15 1.0
17 0.7714285714285715
19 0.7714285714285715
21 0.7714285714285715
23 0.7714285714285715
25 0.7714285714285715
27 0.7714285714285715
29 0.7714285714285715
31 0.7714285714285715
33 0.7714285714285715
데이터 분류하기2¶
In [108]:
print(fish_length, fish_weight)
[25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0, 31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0, 35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0, 9.8, 10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0] [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0, 500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0, 700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0, 6.7, 7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]
In [111]:
### 2차원 데이터 생성하기
fish_data= np.column_stack((fish_length,fish_weight))
### 1차원 데이터 생성하기
# 리스트를 1과 0으로 만든뒤 합치기
fish_target = np.concatenate((np.ones(35),np.zeros(14)))
fish_target
Out[111]:
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
데이터 섞으면서 분류하기¶
In [112]:
### 머신러닝, 딥러닝에서 사용하는 데이터 분류기 함수
# - 랜덤하게 섞으면서 두개 (훈련: 테스트)의 데이터로 분류함
from sklearn.model_selection import train_test_split
In [193]:
### 첫번째 값: 독립변수
### 두번째 값: 종속변수
### test_size= 0.3(30%라는 뜻) : 분류 기준(훈련: 테스트 = 7:3)
### random_state : 랜덤규칙
### stratify=fish_target: 종속변수의 범주 비율을 훈련과 테스트의 비율대비 편향없이 조정시킴
### 첫번째 결과값: 훈련 독립변수
### 두번째 결과값: 테스트 독립변수
### 세번째 결과값: 훈련 종속변수
### 네번째 결과값: 테스트 종속변수
train_input, test_input, train_target, test_target=train_test_split(fish_data, fish_target,
test_size=0.3, random_state=42,
stratify= fish_target)
print(f"{train_input.shape}, {train_target.shape},{test_input.shape},{test_target.shape}")
(34, 2), (34,),(15, 2),(15,)
In [204]:
## 모델 클래스 생성하기
kn = KNeighborsClassifier(n_neighbors=5)
kn
Out[204]:
KNeighborsClassifier()
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.
KNeighborsClassifier()
In [205]:
### 모델 훈련시키기
kn.fit(train_input, train_target)
Out[205]:
KNeighborsClassifier()
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.
KNeighborsClassifier()
In [206]:
# 훈련 정확도 확인하기
train_score = kn.score(train_input,train_target)
# 검증 정확도 확인하기
test_score = kn.score(test_input,test_target)
train_score, test_score
### 해석
# 과대 적함 : 훈련 > 검증, 또는 훈련이 1인 경우
# 과소적합 : 훈련 < 검증, 또는 검증이 0인 경우
# - 과소적합이 일어나는 모델은 사용할 수 없음
# - 과대적합 중에 훈련 정확도가 1인 경우의 모델은 사용할 수 없음
# - 과대 적합이 보통 0.1 이상의 차이를 보이려면 정확도의 차이가 많이 난다고 의심할 수 있음
# 모델 선정 기준 : 과소적합이 일어나지 않으면서
# : 훈련 정확도가 1이 아니고,
# : 훈련과 검증의 차이가 0.1이내인 경우
# **** 선정된 모델을 "일반화모델" 이라고 칭합니다
# 다만 추가로 선정 기준 중에 평가기준이 있음
### ***** 가장 바람직한 결과는 훈련> 검증 > 테스트
# (훈련>검증<테스트 인경우도 있음)
Out[206]:
(1.0, 1.0)
In [197]:
kn = KNeighborsClassifier()
kn.fit(train_input, train_target)
nScore= 0
### KNN 모델 생성하기
# n_neighbors : 이웃의 갯수(하이퍼 파라메터 속성)
### 모델 생성완료 했으니 모델 훈련시키기
nCnt=0
# kn20 = KNeighborsClassifier(n_neighbors=3)
# kn20.fit(fish_data, fish_target)
for n in range(3,len(train_input),2):
kn.n_neighbors=n
score= kn.score(train_input,train_target)
# 1보다 작은 정확도인 경우
if score> nScore and score!=1:
nScore=score
nCnt=n
print(n,score)
print(f"최고 성능: {nCnt}")
### 모델의 성능이 가장 좋은 시점의 이웃의 갯수를 추출하기 위해
# - 하이퍼 파라메터 튜닝 결과 , 이웃의 갯수 19개를 사용했을 때
# - 가장 좋은 성능을 발휘하는 것으로 확인됨
3 1.0
5 1.0
7 1.0
9 1.0
11 1.0
13 1.0
15 1.0
17 1.0
19 1.0
21 0.7058823529411765
23 0.7058823529411765
25 0.7058823529411765
27 0.7058823529411765
29 0.7058823529411765
31 0.7058823529411765
33 0.7058823529411765
최고 성능: 21
In [213]:
### 임의 데이터로 테스트하기
kn.predict([[25,150]])
Out[213]:
array([0.])
In [214]:
# 산점도 그리기
plt.figure(figsize=(5,5))
plt.scatter(train_input[:,0],train_input[:,1], c="red", label="1")
# plt.scatter(test_input[:,0],test_input[:,1], c="blue", label="2")
plt.scatter(25,150, c="green", label="빙어")
plt.xlabel("length")
plt.ylabel("weghit")
plt.title("물고기 크기별 무게", fontweight=700, fontsize=22)
plt.legend()
plt.show
Out[214]:
<function matplotlib.pyplot.show(close=None, block=None)>
In [221]:
### 사용된 이웃 확인하기
dist, indexes = kn.kneighbors([[25,150]])
indexes
Out[221]:
array([[29, 16, 26, 0, 11]], dtype=int64)
In [233]:
# 이웃을 포함하여 산점도 그리기
plt.figure(figsize=(5,5))
plt.scatter(train_input[:,0],train_input[:,1], c="red", label="도미")
plt.scatter(25,150,marker="^", s =100, c="green", label="pred")
plt.scatter(train_input[indexes,0],train_input[indexes,1], c="blue", label="빙어")
plt.xlabel("length")
plt.ylabel("weghit")
plt.title("물고기 크기별 무게", fontweight=700, fontsize=22)
plt.legend()
plt.show
### 에측 결과는 방어로 확인되었으나
# - 시각적으로 확인하였을때는 도미에 더 가까운 것으로 확인됨
# - 실제 이웃을 확인한 결과 방어 족 이웃을 모두 사용하고 있음
# ==> 이런 현상이 발생한 원인 : 스케일(x축과 y축의 단위)이 다르기 때문에 나타나는 현상
# -> " 스케일이 다르다 " 라고 표현 합니다.
### 해소방법 : 데이터 정규화 전처리를 수행해야 함
Out[233]:
<function matplotlib.pyplot.show(close=None, block=None)>
정규화 하기¶
In [236]:
"""
<현재까지 수행 순서>
1.데이터 수집
2.독립변수 2차원과 종속변수 1차원 데이터로 취합
3. 훈련, 검증, 테스트 데이터로 섞으면서 분리
4. 훈련, 검증, 테스트 데이터로 중 독립변수에 대해서만 정규화 전처리수행
------------------------[전-처-리-과-정]---------------------------
5. 훈련모델 생성
6. 모델 훈련 시키기
7. 훈련 및 검증 정확도 확인
8. 하이퍼파라메터 튜닝
9. 예측
"""
Out[236]:
'\n<현재까지 수행 순서>\n1.데이터 수집\n2.독립변수 2차원과 종속변수 1차원 데이터로 취합\n3. 훈련, 검증, 테스트 데이터로 섞으면서 분리\n4. 훈련, 검증, 테스트 데이터로 중 독립변수에 대해서만 정규화 전처리수행\n------------------------[전-처-리-과-정]---------------------------\n5. 훈련모델 생성\n6. 모델 훈련 시키기\n7. 훈련 및 검증 정확도 확인\n8. 하이퍼파라메터 튜닝\n9. 예측\n\n\n\n\n'
In [237]:
### 정규화 -> 표준점수화 하기
# 표준점수 = (각 데이터 - 데이터 전체 평균) / 데이터 전체 표준편차
# 표준 점수 : 각 데이터가 원점(0)에서 표준편차 만큼 얼마나 떨어져 있는 지를 나타내는 값
In [238]:
### 데이터 전체 평균 구하기
mean = np.mean(train_input, axis=0)
mean
Out[238]:
array([ 27.02352941, 445.60294118])
In [239]:
### 데이터 전체 표준편차 구하기
std = np.std(train_input, axis=0)
std
Out[239]:
array([ 10.0816099 , 319.21122132])
In [240]:
### 정규화 (표준점수) 처리하기
train_scaled = (train_input -mean)/std
train_scaled
Out[240]:
array([[-1.4703534 , -1.35773091],
[ 0.49361864, 0.48368306],
[ 0.74159491, 0.54633749],
[ 0.36467098, 0.17041086],
[ 0.49361864, 0.48368306],
[ 0.79119016, 0.85960969],
[-1.55962486, -1.36869543],
[ 0.89038067, 0.84081336],
[ 0.19604712, -0.04887968],
[-1.56954391, -1.36524944],
[ 0.26548048, 0.17041086],
[-1.4901915 , -1.36524944],
[ 0.39442813, 0.09209281],
[ 0.98957118, 1.73677184],
[ 0.19604712, -0.25877205],
[ 0.59280915, 0.79695525],
[-1.26205334, -1.33423549],
[ 0.44402339, 0.17041086],
[ 1.23754745, 1.50181769],
[-1.70841062, -1.37496088],
[ 0.89038067, 1.26686354],
[-1.63897726, -1.3724547 ],
[ 0.6424044 , 0.51501027],
[-1.62905821, -1.37402106],
[ 0.79119016, 0.79695525],
[ 0.79119016, 0.8752733 ],
[-1.391001 , -1.35773091],
[ 0.29523763, 0.01377476],
[ 0.59280915, 0.79695525],
[-1.19261998, -1.33360895],
[ 0.49361864, -0.33082465],
[ 0.6424044 , 0.64031915],
[ 0.29523763, -0.17418855],
[ 1.38633321, 1.65845379]])
In [244]:
# 이웃을 포함하여 산점도 그리기
plt.figure(figsize=(5,5))
plt.scatter(train_scaled[:,0],train_scaled[:,1], c="red", label="도미")
plt.scatter(25,150,marker="^", s =100, c="green", label="pred")
plt.scatter(train_input[indexes,0],train_input[indexes,1], c="blue", label="빙어")
plt.xlabel("length")
plt.ylabel("weghit")
plt.title("물고기 크기별 무게", fontweight=700, fontsize=22)
plt.legend()
plt.show
Out[244]:
<function matplotlib.pyplot.show(close=None, block=None)>
In [246]:
### 예측하고자 하는 값들도 모두 정규화 처리해야함
new = ([25,150] -mean)/std
new
Out[246]:
array([-0.20071491, -0.92604182])
In [252]:
# 이웃을 포함하여 산점도 그리기
plt.figure(figsize=(5,5))
plt.scatter(train_scaled[:,0],train_scaled[:,1], c="red", label="도미")
plt.scatter(new[0],new[1] ,marker="^", s =100, c="green", label="pred")
plt.scatter(train_scaled[indexes,0],train_scaled[indexes,1], c="blue", label="빙어")
plt.xlabel("length")
plt.ylabel("weghit")
plt.title("물고기 크기별 무게", fontweight=700, fontsize=22)
plt.legend()
plt.show
Out[252]:
<function matplotlib.pyplot.show(close=None, block=None)>
In [253]:
### 모델 생성하기
kn = KNeighborsClassifier()
### 모델 훈련하기
kn.fit(train_scaled, train_target)
Out[253]:
KNeighborsClassifier()
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.
KNeighborsClassifier()
In [255]:
### 훈련데이터 검증하기
train_score=kn.score(train_scaled,train_target)
train_score
Out[255]:
1.0
In [260]:
### 테스트 데이터로 검증하기
#******************** 검증 또는 테스트 데이터를 스케일링 정규화 처리
# - 이때는 훈련에서 사용한 mean 과 sta를 그대로 사용해야함
test_scaled = (test_input -mean)/std
test_score=kn.score(test_scaled,test_target)
test_score
Out[260]:
1.0
In [262]:
### 예측하기
kn.predict([new])
Out[262]:
array([1.])
In [264]:
### 예측에 사용된 이웃 확인하고 시각화하기
dist, indexes = kn.kneighbors([new])
indexes
Out[264]:
array([[14, 32, 30, 8, 27]], dtype=int64)
In [268]:
plt.figure(figsize=(5,5))
plt.scatter(train_scaled[:,0],train_scaled[:,1], c="red", label="도미")
plt.scatter(new[0],new[1] ,marker="^", s =100, c="green", label="pred")
plt.scatter(train_scaled[indexes,0],train_scaled[indexes,1], c="blue", label="이웃")
plt.xlabel("length")
plt.ylabel("weghit")
plt.title("물고기 크기별 무게", fontweight=700, fontsize=22)
plt.legend()
plt.show
Out[268]:
<function matplotlib.pyplot.show(close=None, block=None)>
In [ ]:
728x90
반응형
'파이썬' 카테고리의 다른 글
시계열 분석01 (1) | 2024.01.15 |
---|---|
다중회귀 모델 특성공학 (3) | 2023.12.21 |
생선분류로 알아보는 머신러닝 (1) | 2023.12.20 |
머신러닝 기초 (3) | 2023.12.19 |
데이터프레임_정리 (2) | 2023.12.05 |