AI/MachineLearning

K-Nearest Neighbor 개념, min-max scaling , 모델링 과정

oaho 2023. 2. 23. 01:27
반응형
KNN

K-Nearest Neighbor : K최근접 이웃
 

  • 3-NN for Regression : K개 값의 평균을 계산하여 값을 예측
  • 3-NN for Classificaion : 가장 많이 포함된 유형으로 분류

 
K값의 중요성

  • K(탐색하는 이웃 개수)에 따라 데이터를 다르게 예측할 수도 있음
  • 일반적으로

  - K를 1로 설정 안함 -> 이웃 하나로 현재 데이터를 판단하기에는 너무 편향된 정보
  - K를 홀수로 설정 -> 짝수인 경우 과반수 이상의 이웃이 나오지 않을 수 있음
 
검증 데이터로 가장 정확도가 높은 K를 찾아 KNN 알고리즘의 K로 사용

K 이웃 분류
3 ⭐⭐❤
8 ⭐⭐❤❤💚💚💚💚 💚

 
 
 
 

KNN모델링 절차

 
1. x, y 분리
 

  1. target 변수 명확히 지정
  2. target을 제외한 변수를 x 데이터프레임으로 선언
  3. y 데이터프레임은 target변수만을 가짐
# target 확인
target = 'Ozone'

# 데이터 분리
x = data.drop(target, axis=1)
y = data.loc[:, target]

 
2. 학습용, 평가용 데이터 분리
 

# 모듈 불러오기
from sklearn.model_selection import train_test_split

# 데이터 분리
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=1)

 
 

3. 정규화 ⭐

KNN 모델 성능을 높이기 위해서는 스케일링 작업을 진행해야 함
 
Scaling => 결과 0~1사이의 값으로 나옴 => 같은 범위의 데이터를 가짐 => 성능이 좋아짐
 

  • 방법1: 공식사용

x_max = x_train.max()
m_min = x_train.min()

# 정규화
x_train = (x_train - x_min) / ( x_max - x_min )
x_test = ( x_test - x_min ) / ( x_max - x_min)

 
 

  • 방법2: 함수 사용 : MinMaxScaler
# 최댓값, 최솟값 구하기
from sklearn.preprocessing import MinMaxScaler

x_col = list(x)

scaler = MinMaxScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test) # x_train에서 배운 대로 정규화 하라

# 데이터프레임 만들기(이후에 필요하다면)
x_train = pd.DataFrame(x_train, columns = x_col)
x_test = pd.DataFrame(x_test, columns = x_col)

 

 x_train, x_test 같은 최솟값, 최댓값 사용하는 이유: 10 -> 0.3 이런식으로 x_train데이터와, x_test데이터에서 같은 값이 같은 값으로 정규화 되어야하기 때문이다.

 


 
 

4. 모델링
: 모델을 선언하고 학습하고 평가하는 과정 진행
 
1) 불러오기

from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_absolute_error, r2_score

 
2) 선언하기

model = KNeighborsRegressor(n_neighbors=5)

n_neighbors 는 K 값이다.
K 기본값 = 5
 
3) 학습하기

model.fit(x_train, y_train)

 
4) 예측하기

y_pred = model.predict(x_test)

 
5) 평가하기
- target 데이터 값이 숫자형 이므로 (범주값X)LinearRegression방식사용
 

print(mean_absolute_error(y_test, y_pred))
print(r2_score(y_test, y_pred))

 
 
 
 
< LinearRegression 성능 평가 >
 

 

머신러닝 - LinearRegression(MAE, MSE, RMSE, MAPE, R2 - Score)

회귀모델 성능 평가 1) x, y 분리 target 변수 명확히 지정 target을 제외한 변수를 x 데이터프레임으로 선언 y 데이터프레임은 target변수만을 가짐 target = 'Ozone' x = data.drop(target, axis=1) y = data.loc[:, target

oaho.tistory.com

 

반응형