코딩헤딩

[ML(머신러닝)] 머신러닝 기초 3-2 <훈련 및 테스트 분류(train_test_split)> 본문

카테고리 없음

[ML(머신러닝)] 머신러닝 기초 3-2 <훈련 및 테스트 분류(train_test_split)>

멈머이 2023. 12. 21. 20:52
728x90

https://coding-heading.tistory.com/83

 

[ML(머신러닝)] 머신러닝 기초 3-1 <훈련 및 테스트 분류(numpy 셔플링)>

- 정의된 변수 이름은 없음 - 훈련데이터 : 훈련(fit)에 사용되는 데이터 : (훈련 독립변수) train_input, train-x, X_train : (훈련 종속변수) train_target, train_y, Y_ train - 검증데이터 : 훈련 정확도(score)에 사

coding-heading.tistory.com

위 글과 이어집니다.


* 머신러닝, 딥러닝에서 사용하는 테이터 분류기 함수

from sklearn.model_selection import train_test_split

 - 랜덤 하게 섞으면서 두 개(훈련 : 테스트)의 데이터로 분류함

 

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,)

*중요* 
첫번쨰 값 : 독립변수
두 번째 값 : 종속변수
test_size : 분류 기준()
random_state : 랜덤규칙
stratify = fish_target : 종속변수의 범주 비율을 훈련과 테스트의 비율대비 편향 없이 조정시킴

                                   (종속변수를 넣는다./ 편향을 최소화 시키는 방식/ 가끔 쓴다.)
첫 번째 결괏값 : 훈련 독립변수
두 번째 결괏값 : 테스트 독립변수
세 번째 결괏값 : 훈련 종속변수
네 번째 결괏값 : 테스트 종속변수

 

### 모델(클래스) 생성하기
kn = KNeighborsClassifier(n_neighbors=5)

### 모델 훈련 시키기
kn.fit(train_input, train_target)

### 훈련 정확도 확인하기
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인 경우.
  - 과소적합이 일어나는 모델은 사용하 수 없음. 튜닝하면서 값조정. 1이 아닌 가장 높은 정확도 찾기.
  - 과대적합 중에 훈련 정확도가 1인 경우의 모델은 사용할 수 없음.
  - 과대적합이 보통 0.1 이상의 차이를 보이면 정확도와 차이가 많이 난다고 의심해 볼 수 있음.

*중요*
 모델 선정기준 : 과소적합이 일어나지 않으며, 훈련 정확도가 1이 아니고 훈련과 검증의 차이가 0.1 이내인 경우.
 선정된 모델을 "일반화 모델" 이라고 칭한다. 다만, 추가로 선정 기준 중에 평가기준이 있음.

   => 가장 바람직한 결과는 훈련 > 검증 > 테스트  (훈련 > 검증 < 테스트인 경우도 있음)

 

* 정확도가 가장 높을때

# 정확도가 가장 높을떄의 이웃의 갯수를 담을 변수
nCnt = 0
# 정확도가 가장 낮을떄의 이웃의 갯수를 담을 변수
nScore = 0

for n in range(3, len(train_input),2):
    kn.n_neighbors = n
    score = kn.score(train_input, train_target)
    # print(f"{n} / {score}")

    ### 1보다 작은 정확도인 경우
    if score <1:
        ### nScore의 값이 score보다 작은 경우 담기
        if nScore < score:
            nScore = score
            nCnt = n

print(f"nCnt = {nCnt} / nScore = {nScore}")

결과 : nCnt = 21 / nScore = 0.7058823529411765

 

* 산점도 그리기

plt.scatter(train_input[:,0], train_input[:,1], c="red", label="bream")
# plt.scatter(smelt_lenght, smelt_weight, c="blue", label="smeelt")
plt.scatter(25, 150, marker="^", c="green", label="pred")
plt.xlabel("lenght")
plt.ylabel("weight")
plt.legend()
plt.show()

* 사용된 이웃 확인하기

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

결과 : array([[29, 16, 26,  0, 11]], dtype=int64)

거리, 인덱스 값 

 

* 이웃을 포함하여 산정도 그리기

plt.scatter(train_input[:,0], train_input[:,1], c="red", label="bream")
plt.scatter(25, 150, marker="^", c="green", label="pred")
plt.scatter(train_input[indexes, 0], train_input[indexes, 1], c="blue", label="nei")
plt.xlabel("lenght")
plt.ylabel("weight")
plt.legend()
plt.show()

가장 가까운 이웃 5개를 보여주는 산점도이다. 하지만 그래프로 보기에는 오른쪽 위의 점들이 더 가까운 것으로 보이지만, 사용된 이웃은 오른쪽 아래 5개이다. 이런 현상이 일어나는 이유는 각 축의 스케일이 다르기 때문이다.

이 문제를 해결하기 위해서는 정규화 작업이 필요하다.

728x90