ML

ML/ 데이터 전처리 방법

새우는 맛있새우 2026. 1. 13. 18:27

훈련 세트와 체스트 세트르 사이킷런에서 제공하는 train_test_split() 함수로 세련되게 나누어 보겠다.

from sklearn.model_selection import train_test_split
train_input, test_input, train_target, test_target = train_test_split(fish_data, fish_target, stratify= fish_target, random_state=42)

샘플링 편향이 일어나지 않게 하기 위해서 stratify 변수에 타겟 데이터를 넣어주면 된다.

 

이제 데이터를 훈련시키고, 길이 25에 무게 150인 고기를 예측(predict) 해본다. ( 도미가 나와야함 ! )

 

어라?

 

근데 해보면 빙어가 나온다. 왜그럴까?

 

kneighbors() 메서드를 이용하면 넣어준 점의 이웃까지의 거리와 이웃 샘플의 인덱스들을 반환해준다.

 

distances, indexes = kn.kneighbors([[25,150]])

plt.scatter(train_input[:,0], train_input[: ,1])
plt.scatter(25,150,marker='^')
plt.scatter(train_input[indexes,0], train_input[indexes,1], marker='D')
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

 

그래프를 보면 알듯이 x축과 y축의 거리차이가 무지막지하게 난다. 딱 보면 더 가까워 보이는 도미를 선택할 것 같지만 단위가 다르므로 빙어가 더 가깝다.

 

스케일이 다르므로 데이터 전처리하는 과정이 필요하다.

 

표준점수를 활용한다. 표준 점수는 표준편차의 몇 배만큼 떨어져 있는지를 나타낸다.

 

mean= np.mean(train_input, axis=0)
std= np.std(train_input, axis=0)

넘파이에 있는 mean() 함수는 평균을 계산해주고, std() 함수는 표준편차를 계산한다. axis 값이 0이면 세로 방향(열)으로 계산을 해주고, 1이면 가로방향(행)으로 계산.

 

train_scaled= (train_input - mean)/std

표준 점수를 구해준다.(브로드캐스팅)

 

kn.fit(train_scaled, train_target)

업데이트 된 훈련데이터로 훈련해주고,

test_scaled= (test_input-mean)/std

test 데이터도 업데이트해준다.

new = ([25,150]-mean)/std
distances, indexes = kn.kneighbors([new])
plt.scatter(train_scaled[:,0], train_scaled[:,1])
plt.scatter(new[0],new[1],marker='^')
plt.scatter(train_scaled[indexes,0],train_scaled[indexes,1],marker='D')
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

25,150도 표준점수로 바꿔준다.

그럼 이제, 성공적으로 도미로 예측하는 모습을 보여준다.

'ML' 카테고리의 다른 글

ML/ 훈련 세트와 테스트 세트 분리  (0) 2026.01.13
ML/k-최근접 이웃 알고리즘  (0) 2026.01.13