[문제] 데이터가 새로 들어왔을때, 해당 데이터와 가장 가까운 자료 5개의 거리를 구하여 표시해라.
#거리 구하는 방법 : sqrt ( ( x-x1)^2 +(y-y1)^2 )
# 자료 49개로 가정.
# 열을 추가해야 정렬을 하더라도 데이터가 모두 같이 움직인다.
# 데이터가 리스트가 아니고 넘파이 데이터면 열 추가가 편하다
-> import numpy as np 이용하자
test_data=[
[5,4,5]
[6,6,10]
[3,2,5]
]
for range(49)
#반복하여 거리 구하자
dist_result.append()
[내 코드]
import matplotlib.pyplot as plt #matplotlib의 pylot 함수를 plt로 줄여서 사용
import numpy as np
import math
# 문제 데이터 생성
#35개 돔
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];
#15개 빙어
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];
#x축 : 길이
x=fish_length+smelt_length;
y=fish_weight+smelt_weight;
#모든 데이터 합체
fish_data=[[l,w] for l,w in zip(fish_length,fish_weight)];#도미 더하기
smelt_data=[[l,w] for l,w in zip(smelt_length,smelt_weight)];#빙어 더하기
Allfish_data=fish_data+smelt_data;
#입력 좌표
inputX=30;
inputY=600;
#거리 계산후 열 추가
for i in range(len(Allfish_data)): # 배열의 원소 수만큼 반복 (i를 y축 으로 계산)
distance = math.sqrt( ((Allfish_data[i][0]-inputX)**2)+((Allfish_data[i][1]-inputY)**2) ); #거리 계산
Allfish_data[i].append(distance);
#Numpy를 이용한 정렬
arr=np.array(Allfish_data);
sorted_indices = np.argsort(arr[:, 2]) #3번째 열을 기준으로 정렬
sorted_arr = arr[sorted_indices]
#출력해주기
plt.scatter(x,y) #훈련 세트
plt.scatter(inputX,inputY,marker='^')
for i in range(5):
plt.scatter(sorted_arr[i][0],sorted_arr[i][1],marker='o');
plt.xlabel('length')
plt.ylabel('weight')
[강사님 코드]
# 1. 데이터 수집
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]
# 데이터 정제
import numpy as np
fish_data = np.column_stack( (fish_length, fish_weight) )
# 출력방법1
# print( 'fish_data: ', fish_data[ 0:3, 0:2] )
# 출력방법2
print( 'fish_data: ', fish_data[ :3, :] )
x1 = 30.0; y1 = 600.0
dist_list = []
for x2, y2 in fish_data:
dist = np.sqrt( ( x2 - x1 ) ** 2 + ( y2 - y1 ) ** 2 )
dist_list.append( dist )
#print(dist_list[0:3]) # 3개의 데이터
print(dist_list[0], dist_list[1], dist_list[2])
print('end')
# fish_data가 a에 해당한다.
# b는 dist_list이다.
c = np.argsort(dist_list)
d = fish_data[c]
# print(d)
o1 = d[ :3, 0]
o2 = d[ :3, 1]
import matplotlib.pyplot as plt
plt.scatter( fish_length, fish_weight, marker = 'x' )
plt.scatter( x1, y1, marker = 'o' )
plt.scatter( o1, o2, marker = '^' )
plt.xlabel( 'length' )
plt.ylabel( 'weight' )
1. np.argsort()는 값의 크기 순서를 리턴한다
2. 이를 활용하면 다음과 같이 출력할수도 있다.
3. 이것을 활용하여 위 코드에서 np.argsort()사용한 원리이다.
K-최근접 이웃 회귀(p114)
지도 학습 알고리즘 = 분류 & 회귀
[분류]: 샘플을 몇 개의 클래스 중 하나로 분류하는 문제
[회귀]: 어떤 숫자를 예측하는 문제
예시) 아이가 태어났을때 부모보다 더 크지 않는다
import numpy as np
from sklearn.model_selection import train_test_split
perch_length=np.array([1,2,3,4,5])
perch_weight=np.array([5,6,7,8,9])
a,b,c,d=train_test_split(
perch_length,
perch_weight
)
print(1,a) # 배열 'a'의 내용 출력
print(2, type(a)) # 'a'의 데이터 타입 출력
print(3,a.shape) # 'a'의 형태 출력 # (3,) >> 1차원에 데이터 3개가 있다.
print(4, a.ndim) # 'a'의 차원 수 출력
print(5, len(a)) # 'a'의 길이(원소 개수) 출력
a=a.reshape(1,3)
a=a.reshape(len(a),3)
a=a.reshape(-1,1) #-을 사용하면 스스로 len을 사용하여 돌린다(위랑 동일)
print(6,a)
print(7,a.shape) #3행 1열
print(8,a.ndim) #차원이 달라진다
print(9,len(a))
#회귀란 평균을 이용하여 임의의 수치를 예측하는것이다.
#3-1장의 핵심 주체
# 농어의 길이를 입력하면
# 이웃에 있는 농어의 무게의 평균값을 예측값으로 사용하겠다
'SW 교육' 카테고리의 다른 글
[2024.08.05] 데이터 분석 (0) | 2024.08.05 |
---|---|
[2024.08.02] 특성 공학과 규제 (0) | 2024.08.02 |
[2024.08.01] K-최근접 이웃 회귀, 선형 회귀, 다항 회귀, 다중 회귀 (0) | 2024.08.01 |
[2024.07.30] 머신러닝 첫구현(knn알고리즘) (0) | 2024.07.30 |
[2024.07.29] 주피터 노트북 사용환경 만들기 (0) | 2024.07.29 |