> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/undefined-6/machine-learning-knn.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# Machine Learning - KNN 분석

## 1. KNN(K-nearest neigbors)분석

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2F2tn8HzY9geaYuDyq2fFS%2Fimage.png?alt=media&amp;token=5c7606f2-2fa9-4ec0-b53c-8202cc8b2437" alt=""><figcaption></figcaption></figure>

* ML의 지도학습에 속하며, 입력데이터와 **가장 가까운** K개의 이웃 데이터를 기준으로 그들의 **라벨(또는 값)을** 분류하는 방식의 알고리즘
* 이웃 데이터들은 **거리(distance)**&#xB97C; 기반으로 판단한다.
* 학습과정이 거의 없고 결과가 직관적이다.
* 주변 이웃 데이터들을 기반으로 분류를 수행하기 때문에 이상치(Outlier)에 민감하다.
* 각 클래스의 데이터양이 크게 차이나는 경우 정확도가 떨어진다.
* 데이터의 차원이 늘어나면 공간의 부피가 급격히 상승한다.

### 1) K (하이퍼 파라미터)

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2FxGKvyTyhC3NsdaRrywaJ%2Fimage.png?alt=media&amp;token=f8592186-1244-45b4-b724-cf68e6a31ee0" alt=""><figcaption></figcaption></figure>

* 새로운 입력데이터에 대해 거리(distance)상 가장 가까운 이웃을 몇 개로 설정할지를 의미한다.
* k값에 따라 새로운 입력데이터는 A혹은 B가 될 수 있으므로, 개발자가 직접 k값을 조절해보면서 적절한 값을 찾아주어야 한다.
  * **K가 너무 작으면** → 노이즈에 민감 (과적합)
  * **K가 너무 크면** → 주변 클래스가 섞여버림 (과소적합)
* 위 이미지 상 k가 3인경우 x는 ClassB. k가 6인 경우 Class a가 된다.

### 2) 기하학적 거리(Distance)

* 새로운 입력데이터가 주어졌을 때 기존 훈련데이터(이웃)들과의 유사성을 측정하는 방법으로 , 두 점 사이의 거리가 가까울 수록 유사하다고 판단한다.
* 거리를 구하는 알고리즘은 여러개 있으나 대부분 **Euclidean** 거리를 사용한다.

#### 거래를 구하는 알고리즘들

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2Frl96ioiltHSaMC3Zq9TV%2Fimage.png?alt=media&amp;token=2a71ed67-2609-4fb1-aa7d-171de1191f8f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2FJ6qKrioPX658IwNXG4Sp%2Fimage.png?alt=media&amp;token=5a629972-4ba0-4962-8933-92e85e8f00f8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2FC9E2qjD2iSd9gegOiCJx%2Fimage.png?alt=media&amp;token=9c5bc003-a053-41bf-9828-9ea89ea4f07d" alt=""><figcaption></figcaption></figure>

#### Enclidean거리를 구하는 방법

*

```
<figure><img src="/files/UNi64c1THepBTpBShe7S" alt=""><figcaption></figcaption></figure>
```

* 새로운 입력요소(new)가 들어오는 경우 기존 데이터들과의 거리를 구한다.

| 비교 대상    | 계산식                               | 거리(d)    |
| -------- | --------------------------------- | -------- |
| A(10, 3) | √((12−10)² + (4−3)²) = √(4 + 1)   | **2.24** |
| A(12, 6) | √((12−12)² + (4−6)²) = √(0 + 4)   | **2.00** |
| B(14, 5) | √((12−14)² + (4−5)²) = √(4 + 1)   | **2.24** |
| B(15, 4) | √((12−15)² + (4−4)²) = √(9 + 0)   | **3.00** |
| B(16, 8) | √((12−16)² + (4−8)²) = √(16 + 16) | **5.66** |

### 3) KNN 예시

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2F5RVc1YBPVCvBnYtRsi3z%2Fimage.png?alt=media&amp;token=fd4e031d-201d-48ad-aaaa-c1af1b63c3c7" alt=""><figcaption></figcaption></figure>

* k값을 각기 다르거 설정했을 경우, k가 30인 경우가 가장 잘 분류된 것으로 보인다.

### 4) Python 예시

```python
## 0. 환견설정
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from IPython.display import Image

# 기본 폰트 사이즈 변경
plt.rcParams['font.size'] = 14

# 기본 그래프 사이즈 변경
plt.rcParams['figure.figsize'] = (5,5)

# 기본 그리드 표시
# 필요에 따라 설정할 때는, plt.grid()
plt.rcParams['axes.grid'] = True
plt.rcParams["grid.linestyle"] = ":"

# 마이너스 기호 정상 출력
plt.rcParams['axes.unicode_minus'] = False

## 도미자료와 방어자료 불러오기
# Image(url = "https://www.ikonet.com/en/visualdictionary/images/us/bony-fishes-271500.jpg",
#       width = 600, height = 400)

## 1. 도미자료 출력 및 시각화
# 도미 자료 (Bream Data) - 길이와 무게
bream_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]
bream_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]

# 빙어 자료 (Smelt Data) - 길이와 무게
smelt_length = [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]
smelt_weight = [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]

# list 길이
# 각 리스트의 길이를 출력합니다. (도미 35개, 방어 14개)
print(type(bream_length))
print("length of bream = ", len(bream_length), "\nlength of smelt = ",len(smelt_length))

# 각 변수별 평균값을 계산하고 소수점 셋째 자리에서 반올림하여 출력합니다.
print("mean of 도미길이 = ", round(np.mean(bream_length), 2))
print("mean of 방어길이 = ", round(np.mean(smelt_length), 2))

print("mean of 도미무게 = ", round(np.mean(bream_weight), 2))
print("mean of 방어무게 = ", round(np.mean(smelt_weight), 2))

# 도미(파란색)와 빙어(빨간색) 데이터를 산점도로 시각화합니다.

plt.scatter(bream_length, bream_weight, label = "Bream")
plt.scatter(smelt_length, smelt_weight, c = "r", label = "Smelt")
plt.xlabel('Length (cm)')
plt.ylabel('Weight (g)')
plt.title("Bream vs Smelt")
plt.legend()
plt.show()

## 2. skilearn형식에 맞게 List자료를 수정
# 도미와 빙어의 길이/무게 리스트를 하나로 합칩니다. (도미 자료가 먼저, 빙어 자료가 나중)
length = bream_length + smelt_length
weight = bream_weight + smelt_weight

# 통합된 길이와 무게 리스트를 출력하고 길이를 확인합니다.
print("length = \n", length)
print("length length = ", len(length))

print("\nweight = \n", weight)
print("weight length = ", len(weight))

# NumPy를 사용하여 길이(length)와 무게(weight) 리스트를 열 방향(column)으로 붙여 2차원 배열을 생성합니다.
# fish_data는 독립 변수(특성) 데이터셋이 됩니다.
fish_data = np.column_stack((length, weight))

# fish_data 배열의 크기(49행, 2열)를 출력합니다.
print("배열크기 fish_data = ", np.shape(fish_data))

print(fish_data[:10,])

# 타겟(레이블) 설정: 도미는 1 (35개), 빙어는 0 (14개)으로 인덱스 배열을 생성합니다.
one_index = np.ones(35)
zero_index = np.zeros(14)

print("one_index = \n", one_index)
print("zero_index = \n", zero_index)

# 도미 타겟(1)과 빙어 타겟(0)을 합쳐 최종 타겟 배열(fish_target)을 생성합니다.
fish_target = np.append(one_index, zero_index)

print("\nfish_target = \n", fish_target)

## 3. 훌련세트와 테스트 세트 나누기
# ----------------- 훈련/테스트 데이터 분할 -----------------
# fish_data와 fish_target을 훈련 세트와 테스트 세트로 나눕니다.
# train_size = 0.7: 훈련 세트 70% (34개), 테스트 세트 30% (15개)
# stratify=fish_target: 타겟 클래스(0과 1)의 비율을 유지하며 분할합니다. (편향 방지)
# random_state=42: 무작위 추출을 위한 시드값 설정 (결과 재현 가능하게 함)

from  sklearn.model_selection import train_test_split

# default test_size = 0.25
train_input, test_input, train_target, test_target = train_test_split(
    fish_data, fish_target, train_size = 0.7, stratify=fish_target, random_state=42)

print('훈련자료 배열크기 = {0}, 테스트자료 배열크기 = {1}'.format(train_input.shape, test_input.shape))

# 훈련 세트(파란색)와 테스트 세트(빨간색)를 산점도로 시각화하여 분리된 상태를 확인합니다

plt.scatter(train_input[:, 0], train_input[:, 1], label = "Train")
plt.scatter(test_input[:, 0], test_input[:, 1], c = "r", label = "Test")
plt.xlabel('Length')
plt.ylabel('Weight')
plt.legend()
plt.show()

## 4. 표준화의 중요성과 KNN 생성
from sklearn.neighbors import KNeighborsClassifier
## knn 학습 parameter
#### n_neighbors : int, default=5
#### weights : {'uniform', 'distance'} or callable, default='uniform'
#### algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
#### leaf_size : int, default=30
#### p : int, default = 2
#### metric : str or callable, default='minkowski'

# KNN 분류기 객체를 생성합니다.
# n_neighbors=5: 가장 가까운 5개의 이웃 사용
# p=2: 유클리디안 거리(Euclidean distance)를 사용 (L2 norm)
kn = KNeighborsClassifier(n_neighbors=5, p = 2)
# 훈련 세트를 사용하여 모델을 학습시킵니다
kn.fit(train_input, train_target)
# 테스트 세트를 사용하여 모델의 정확도(score)를 평가합니다.
kn.score(test_input, test_target)

# 훈련 세트 데이터를 검정색 점(k)으로 시각화합니다.
plt.scatter(train_input[:,0], train_input[:,1], c = "k")
# 새로운 데이터 포인트 [길이=25, 무게=150]를 빨간색 십자(+) 마커로 표시합니다.
plt.scatter(25, 150, marker = "+", s = 100, c = "r")
plt.xlabel('Length')
plt.ylabel('Weight')
plt.show()

## 1) 표준화 전 자료를 이용한 KNN
# 새로운 포인트 [25, 150]에 가장 가까운 K=5개의 훈련 데이터를 찾습니다.
distance, index = kn.kneighbors([[25, 150]])
# 5개 이웃과의 거리를 출력합니다.
print("distance = \n", distance)
# 5개 이웃의 훈련 데이터 인덱스를 출력합니다. (주로 빙어 인덱스가 나올 것임)
print("index = \n", index)

# 새로운 포인트와 그 이웃들을 시각화합니다.
plt.scatter(train_input[:,0], train_input[:,1], c = "k")
plt.scatter(25, 150, marker ="+", c = "r", s = 200)
# 이웃으로 선택된 5개 포인트를 청록색 마름모(D)로 표시합니다.
plt.scatter(train_input[index, 0], train_input[index, 1],
            marker = "D", c = "c")
plt.xlabel('Length')
plt.ylabel('Weight')
plt.show()

### 2) 자료의 표준화
## - 이웃한 데이터 포인트찾기
print('훈련자료의 이웃자료 = \n{0}, \n훈련자료의 그룹 = {1}'.format(train_input[index], train_target[index]))
print('\n훈련자료와의 거리는 = {}'.format(distance))

# 축의 범위를 변경하여 시각화합니다.
plt.scatter(train_input[:,0], train_input[:,1])
plt.scatter(25, 150, marker='^')
plt.scatter(train_input[index,0], train_input[index,1], marker='D')
plt.xlim((0, 1000))
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

## 3) 표준화 된 자료를 이용한 KNN
# 훈련 세트의 데이터를 표준화(Z-score 스케일링)합니다. (train_scaled)
# 공식: Z = (X - mean) / std
mean = np.mean(train_input, axis = 0)
std = np.std(train_input, axis = 0)
print('평균은 ={0}, 표준편차 = {1}'.format(mean, std))

train_scaled = (train_input - mean)/std

# 예측할 새로운 포인트 [25, 150]도 훈련 세트의 평균과 표준편차를 이용해 스케일링합니다.
new = ([25, 250] - mean)/std
print('z-score 점수는 =', new)

# 스케일링된 훈련 데이터와 새로운 포인트의 위치를 시각화합니다.
# 데이터가 중앙(0 근처)에 모여 있고, 축 범위가 비슷해진 것을 확인합니다.
plt.scatter(train_scaled[:,0], train_scaled[:,1])
plt.scatter(new[0], new[1], marker='^', s  = 100, c = "r")
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

# ----------------- KNN 모델 재학습 및 평가 (스케일링 후) -----------------
# 스케일링된 훈련 세트로 KNN 모델을 다시 학습시킵니다.
kn.fit(train_scaled, train_target)
# 테스트 세트도 훈련 세트의 평균/표준편차를 이용해 스케일링합니다.
test_scaled = (test_input - mean) / std

# 스케일링된 테스트 세트로 모델의 정확도를 평가합니다. (정확도가 향상되었을 것)
kn.score(test_scaled, test_target)
print('Accuracy of test set= ', kn.score(test_scaled, test_target))
print(kn.predict([new]))
# print(kn.predict_proba([new]))

# 스케일링된 새로운 포인트에 가장 가까운 K=5개의 이웃을 다시 찾습니다.
distances, indexes = kn.kneighbors([new])

# 스케일링된 훈련 데이터와 새로운 포인트, 그리고 이웃들을 시각화합니다.
plt.scatter(train_scaled[:,0], train_scaled[:,1])
plt.scatter(new[0], new[1], marker='^')
# 이웃으로 선택된 5개 포인트를 마름모(D)로 표시합니다. (이번에는 도미 그룹이 이웃으로 선택될 것)
plt.scatter(train_scaled[indexes,0], train_scaled[indexes,1], marker='D')
plt.xlabel('length')
plt.ylabel('weight')
plt.show()
```

### 5) KNN의 특징

| 장점                             | 단점                                |
| ------------------------------ | --------------------------------- |
| ✅ 구현이 매우 간단                    | ❌ 데이터가 많을수록 계산량이 많음               |
| ✅ 학습 과정이 거의 없음 (lazy learning) | ❌ 고차원일수록 거리 계산의 의미가 희미해짐 (차원의 저주) |
| ✅ 비모수 방식 → 데이터 분포 가정 X         | ❌ 이상치(outlier)에 민감함               |
| ✅ 분류/회귀 둘 다 가능                 | ❌ 특징 스케일이 다르면 거리 계산 왜곡            |

### 6) KNN은 어디에 쓰이나?

* 패턴 인식 (이미지, 음성)
* 추천 시스템
* 이상치 탐지 (Outlier Detection)
* 분류(Classification)와 회귀(Regression) 문제 전반

### 7) 핵심 요약

| 구분             | 내용                        |
| -------------- | ------------------------- |
| **알고리즘명**      | K-Nearest Neighbors (KNN) |
| **핵심 아이디어**    | 가까운 K개의 이웃을 기준으로 예측       |
| **모델 종류**      | 지도학습 (분류/회귀 모두 가능)        |
| **핵심 하이퍼파라미터** | K (이웃 수), 거리 계산 방식        |
| **전처리 중요 요소**  | 표준화(Standardization)      |

***
