머신러닝- 혼공머
chapter 2-1 지도학습 - 훈련세트 테스트 세트
막막한
2023. 3. 19. 15:31
In [1]:
'''
머신러닝 알고리즘은 크게 지도학습과 비지도 학습으로 나눈다
지도학습 알고리즘은 훈련하기 위해 데이터와 정답 필요
지도학습에서 데이터와 정답을 입력과 타깃이라하고 이 둘을 합쳐 훈련 데이터라 부른다
입력데이터만 있을 때는 비지도 학습 알고리즘을 사용
'''
Out[1]:
'\n머신러닝 알고리즘은 크게 지도학습과 비지도 학습으로 나눈다\n\n지도학습 알고리즘은 훈련하기 위해 데이터와 정답 필요\n\n지도학습에서 데이터와 정답을 입력과 타깃이라하고 이 둘을 합쳐 훈련 데이터라 부른다\n\n입력데이터만 있을 때는 비지도 학습 알고리즘을 사용\n\n'
In [2]:
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 [3]:
# 생선의 길이와 무게를 하나의 리스트로 담은 2차원 리스트 만들기
fish_data=[[l,w] for l,w in zip(fish_length, fish_weight)]
fish_target=[1]*35 +[0]*14
In [4]:
# 하나의 생선 데이터는 샘플
# 사이킷런의 KN 클래스 임포트하고 모델 객체 만들기
from sklearn.neighbors import KNeighborsClassifier
kn=KNeighborsClassifier()
In [5]:
#인덱스 지정
fish_data[4]
Out[5]:
[29.0, 430.0]
In [6]:
# 슬라이싱은 :을 가운데 두고 인덱스 범위를 지정해 여러 개 원소 선택
# 첫번째 ~ 다섯번째 샘플 선택
fish_data[0:5]
# 슬라이싱은 마지막 인덱스 원소는 포함하지 않는다
Out[6]:
[[25.4, 242.0], [26.3, 290.0], [26.5, 340.0], [29.0, 363.0], [29.0, 430.0]]
In [7]:
fish_data[44:]
Out[7]:
[[12.2, 12.2], [12.4, 13.4], [13.0, 12.2], [14.3, 19.7], [15.0, 19.9]]
In [9]:
# 훈련 세트로 입력값 중 0~34 인덱스 사용
train_input= fish_data[:35]
# 훈련 세트로 타겟값 중 0~34 인덱스 사용
train_target= fish_target[:35]
# 태스트 세트로 입력값 중 35~ 마지막 인덱스 사용
test_input= fish_data[35:]
# 태스트 세트로 타겟값 중 35~ 마지막 인덱스 사용
test_target= fish_target[35:]
In [10]:
#fit으로 호출해 모델 훈련, 테스트 세트로 score()호출해 평가
kn.fit(train_input, train_target)
kn.score(test_input, test_target)
C:\Users\82104\anaconda3\lib\site-packages\sklearn\neighbors\_classification.py:228: FutureWarning: Unlike other reduction functions (e.g. `skew`, `kurtosis`), the default behavior of `mode` typically preserves the axis it acts along. In SciPy 1.11.0, this behavior will change: the default value of `keepdims` will become False, the `axis` over which the statistic is taken will be eliminated, and the value None will no longer be accepted. Set `keepdims` to True or False to avoid this warning.
mode, _ = stats.mode(_y[neigh_ind, k], axis=1)
Out[10]:
0.0
In [11]:
# 0.0이 나왔다 훈련세트와 테스트 세트를 나눌려면 도미와 빙어가 골고루 섞이게 만들어야한다
#넘파이 - 대표적인 배열 라이브러리
import numpy as np
# 리스트를 넘파이 배열로 바꾸기
input_arr=np.array(fish_data)
target_arr=np.array(fish_target)
In [12]:
print(input_arr)
[[ 25.4 242. ]
[ 26.3 290. ]
[ 26.5 340. ]
[ 29. 363. ]
[ 29. 430. ]
[ 29.7 450. ]
[ 29.7 500. ]
[ 30. 390. ]
[ 30. 450. ]
[ 30.7 500. ]
[ 31. 475. ]
[ 31. 500. ]
[ 31.5 500. ]
[ 32. 340. ]
[ 32. 600. ]
[ 32. 600. ]
[ 33. 700. ]
[ 33. 700. ]
[ 33.5 610. ]
[ 33.5 650. ]
[ 34. 575. ]
[ 34. 685. ]
[ 34.5 620. ]
[ 35. 680. ]
[ 35. 700. ]
[ 35. 725. ]
[ 35. 720. ]
[ 36. 714. ]
[ 36. 850. ]
[ 37. 1000. ]
[ 38.5 920. ]
[ 38.5 955. ]
[ 39.5 925. ]
[ 41. 975. ]
[ 41. 950. ]
[ 9.8 6.7]
[ 10.5 7.5]
[ 10.6 7. ]
[ 11. 9.7]
[ 11.2 9.8]
[ 11.3 8.7]
[ 11.8 10. ]
[ 11.8 9.9]
[ 12. 9.8]
[ 12.2 12.2]
[ 12.4 13.4]
[ 13. 12.2]
[ 14.3 19.7]
[ 15. 19.9]]
In [13]:
input_arr.shape (샘플수, 특성수)
Out[13]:
(49, 2)
In [15]:
# 넘파이 arrange()함수 만들어 1씩 증가하는 인덱스 만들기
np.random.seed(42) #랜덤시드 42 랜덤으로 섞기
index=np.arange(49)ㅣ2ㅑ-
np.random.shuffle(index)
In [16]:
index
Out[16]:
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 [22]:
input_arr[[0,1,2,3]]
Out[22]:
array([[ 25.4, 242. ],
[ 26.3, 290. ],
[ 26.5, 340. ],
[ 29. , 363. ]])
In [23]:
# 리스트대신 넘파이 배열을 인덱스로 전달
# input_arr와 target_arr에 전달해 랜덤한 35개 샘플을 훈련세트로 만들기
train_input=input_arr[index[:35]]
train_target=target_arr[index[:35]]
In [24]:
input_arr[13], train_input[0] #인덱스 13 가져온것 - 랜덤으로 섞였나 확인
Out[24]:
(array([ 32., 340.]), array([ 32., 340.]))
In [25]:
#나머지 14개 테스트 세트로 만들기
test_input= input_arr[index[35:]]
test_target=target_arr[index[35:]]
In [26]:
# 2차원 배열은 행과 열 인덱스를 콤마,로 나누어 지정
import matplotlib.pyplot as plt
plt.scatter(train_input[:,0], train_input[:,1]) # 모든 행 : /콤마,/ 첫 번째 열0
plt.scatter(test_input[:,0], test_input[:,1])
plt.xlabel('length')
plt.ylabel('weight')
plt.show()
주황색: 테스트 세트 파란색: 훈련세트
In [27]:
#훈련세트와 테스트 세트로 k-최근접 이웃 모델 훈련시키기
kn.fit(train_input, train_target)
Out[27]:
KNeighborsClassifier()
In [29]:
kn.score(test_input, test_target)
C:\Users\82104\anaconda3\lib\site-packages\sklearn\neighbors\_classification.py:228: FutureWarning: Unlike other reduction functions (e.g. `skew`, `kurtosis`), the default behavior of `mode` typically preserves the axis it acts along. In SciPy 1.11.0, this behavior will change: the default value of `keepdims` will become False, the `axis` over which the statistic is taken will be eliminated, and the value None will no longer be accepted. Set `keepdims` to True or False to avoid this warning.
mode, _ = stats.mode(_y[neigh_ind, k], axis=1)
Out[29]:
1.0
In [30]:
kn.predict(test_input)
# 도미, 빙어 0 1
C:\Users\82104\anaconda3\lib\site-packages\sklearn\neighbors\_classification.py:228: FutureWarning: Unlike other reduction functions (e.g. `skew`, `kurtosis`), the default behavior of `mode` typically preserves the axis it acts along. In SciPy 1.11.0, this behavior will change: the default value of `keepdims` will become False, the `axis` over which the statistic is taken will be eliminated, and the value None will no longer be accepted. Set `keepdims` to True or False to avoid this warning.
mode, _ = stats.mode(_y[neigh_ind, k], axis=1)
Out[30]:
array([0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0])
In [31]:
test_target
Out[31]:
array([0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0])
테스트 세트에 대한 예측결과가 정답과 일치한다
지도학습: 입력과 타깃 전달, 모델 훈련한 다음 새로운 데이터 예측하는 데 활용 비지도학습: 타깃 데이터 없음, 예측하는 것이 아니라 입력 데이터에서 특징 찾는데 활용 훈련 세트: 모델을 훈련할 때 사용하는 데이터, 훈련세트가 클수록 좋다 테스트 세트: 전체 데이터에서 20~30%를 테스트 세트로 사용하는 경우가 많다
<핵심패키지와 함수> numpy -seed()는 넘파이에서 난수 생성하기 위한 정수 초깃값 지엉 -arange() 일정한 간격의 정수 또는 실수 배열 만든다 -shuffle() 주어진 배열 랜덤하게 섞기,