728x90
다음은 코드입니다.
import requests, json
def get_trade_log_list(pSize):
apikey = '6XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX7'
url = 'https://openapi.gg.go.kr/Apttradedelngdetail'
params ={
'KEY' : apikey,
'type':'json',
'pSize':pSize,
}
response = requests.get(url, params=params)
trade_log_list = response.json()
trade_log_list = trade_log_list['Apttradedelngdetail']
trade_log_list = trade_log_list[1]['row']
#print(json.dumps(trade_log_list, indent=4, ensure_ascii=False))
DELNG_AMT_list = []
PRVTUSE_AR_list = []
for trade_log in trade_log_list:
DELNG_AMT_list.append(trade_log['DELNG_AMT']) # 거래금액(만원)
PRVTUSE_AR_list.append(trade_log['PRVTUSE_AR']) # 전용면적(㎡)
return PRVTUSE_AR_list, DELNG_AMT_list
# 10건의 전용면적리스트와 거래금액리스트를 가져오기
PRVTUSE_AR_list, DELNG_AMT_list = get_trade_log_list(10)
print("전용면적리스트")
print(PRVTUSE_AR_list)
print("전용면적리스트")
print(DELNG_AMT_list)
def normalize_minmax(input_list):
result_list = []
for value in input_list:
result_list.append((value - min(input_list)) / (max(input_list) - min(input_list)))
return result_list
import numpy as np
import matplotlib.pyplot as plt
def prediction(theta_0, theta_1, x):
"""주어진 학습 데이터 벡터 x에 대해서 모든 예측 값을 벡터로 리턴하는 함수"""
return theta_1 * x + theta_0
def prediction_difference(theta_0, theta_1, x, y):
"""모든 예측 값들과 목표 변수들의 오차를 벡터로 리턴해주는 함수"""
return prediction(theta_0, theta_1, x) - y
def gradient_descent(theta_0, theta_1, x, y, iterations, alpha):
m = len(x)
cost_list = []
"""주어진 theta_0, theta_1 변수들을 경사 하강를 하면서 업데이트 해주는 함수"""
for i in range(iterations): # 정해진 번만큼 경사 하강을 한다
error = prediction_difference(theta_0, theta_1, x, y) # 예측값들과 입력 변수들의 오차를 계산
cost_list.append(error@error / (2*m))
theta_0 = theta_0 - alpha * error.mean()
theta_1 = theta_1 - alpha * ((error*x).mean())
plt.scatter(PRVTUSE_AR_list, DELNG_AMT_list)
plt.plot(PRVTUSE_AR_list, prediction(theta_0, theta_1, x), 'ro-')
plt.title("iteration " + str(i))
if i == 0:
plt.pause(5)
plt.pause(0.00001)
plt.clf()
return theta_0, theta_1, cost_list
# 입력 변수(집 크기) 초기화 (모든 집 평수 데이터를 1/10 크기로 줄임)
PRVTUSE_AR_list = normalize_minmax(PRVTUSE_AR_list)
PRVTUSE_AR_list = np.array(PRVTUSE_AR_list)
# 목표 변수(집 가격) 초기화 (모든 집 값 데이터를 1/10 크기로 줄임)
DELNG_AMT_list = normalize_minmax(DELNG_AMT_list)
DELNG_AMT_list = np.array(DELNG_AMT_list)
# theta 값들 초기화 (아무 값이나 시작함)
theta_0 = 0#2.5
theta_1 = 0
# 학습률 1.0으로 100번 경사 하강
theta_0, theta_1, cost_list = gradient_descent(theta_0, theta_1, PRVTUSE_AR_list, DELNG_AMT_list, 100, 1.0)
plt.show()
다음은 실행결과로 그려지는 그래프영상입니다.
이상과 같이 10건의 데이터로 간단한 경사하강법 모델구축을 실행해보았습니다.
728x90
'Python' 카테고리의 다른 글
python으로 windows service 만들기 (0) | 2022.06.09 |
---|---|
python isPalindrome 함수 (0) | 2022.06.02 |
[python] 경기도 아파트 매매 실거래 데이터 그래프 그리기 (0) | 2022.05.16 |
[python] 경기도 아파트 매매 실거래 데이터 가져오기 (0) | 2022.05.16 |
[python] pyplot을 사용하여 그래프 그리기 (0) | 2022.05.13 |