In [1]:
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]
In [2]:
import matplotlib.pyplot as plt
plt.scatter(bream_length, bream_weight)
plt.xlabel('length')
plt.ylabel('weight')
plt.show()
In [3]:
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]
In [4]:
plt.scatter(bream_length,bream_weight)
plt.scatter(smelt_length,smelt_weight)
plt.xlabel('length')
plt.ylabel('weight')
plt.show()
In [5]:
length = bream_length + smelt_length
weight = bream_weight + smelt_weight
In [6]:
fish_data = [[l, w] for l, w in zip(length, weight)] #l=length, w=weigth
- zip() 함수는 나열된 리스트에서 원소를 하나씩 꺼내주는 일을 한다.
In [7]:
print(fish_data)
In [8]:
fish_target = [1] * 35 + [0] * 14
print(fish_target)
- 도미는 1, 빙어는 0으로 분류한다.
In [9]:
from sklearn.neighbors import KNeighborsClassifier
kn = KNeighborsClassifier()
In [10]:
kn.fit(fish_data, fish_target)
Out[10]:
In [11]:
kn.score(fish_data, fish_target)
Out[11]:
In [12]:
kn.predict([[30,600]])
Out[12]:
- 모델은 30cm, 600g의 spec.을 가진 물고기는 도미라고 추측한다.
In [13]:
print(kn._fit_X)
In [14]:
print(kn._y)
Out [14]:
In [15]:
kn49 = KNeighborsClassifier(n_neighbors=49)
In [16]:
kn49.fit(fish_data, fish_target)
kn49.score(fish_data, fish_target)
Out[16]:
In [17]:
print(35/49)
Out [17]:
- fish_data에 있는 생선 중 35개가 도미이고 빙어가 14개이다.
- kn49 모델은 도미만 올바르게 분류하므로 위와 같은 acc.를 보인다.
- 참고로 n_neighbors의 default값은 5이다.
In [18]:
kn = KNeighborsClassifier()
kn.fit(fish_data, fish_target)
for n in range(5, 50) :
kn.n_neighbors = n
score = kn.score(fish_data, fish_target)
if score < 1 :
print(n,score)
break
Out [18]:
- 처음으로 acc.가 1이 아니게 되는 n=18임을 알 수 있다.
'혼자 공부하는 머신러닝 + 딥러닝' 카테고리의 다른 글
[혼공머신] 6. Feature Engineering & Regularization (0) | 2021.12.17 |
---|---|
[혼공머신] 5. Linear Regression (0) | 2021.12.17 |
[혼공머신] 4. K-NN 회귀 (0) | 2021.12.17 |
[혼공머신] 3. 데이터 전처리 (0) | 2021.12.17 |
[혼공머신] 2. 훈련 세트와 테스트 세트 나누기 (0) | 2021.12.17 |