선형 회귀 알고리즘
선형 회귀를 제대로 이해하려면 알고리즘이 어떻게 동작하는지 아는 것이 도움이 돼요. ols() 코드는 어떤 수식과 어떤 데이터셋에서도 동작해야 하므로 수백 줄로 되어 있어요. 하지만 단일 데이터셋에 대한 단순 선형 회귀의 경우, 몇 줄만으로 선형 회귀 알고리즘을 구현할 수 있어요.
워크플로는 다음과 같아요:
- 먼저, 다음과 같은 일반 문법으로 제곱합을 계산하는 함수를 작성해요:
def function_name(args):
# some calculations with the args
return outcome
- 다음으로,
scipy의 minimize 함수를 사용해 이 함수를 최소화하는 계수를 찾아요.
설명 변수 값(taiwan_real_estate의 n_convenience 열)은 x_actual로 제공돼요.
반응 변수 값(taiwan_real_estate의 price_twd_msq 열)은 y_actual로 제공돼요.
minimize()도 불러와져 있어요.
이 연습은 강의의 일부입니다
Python의 statsmodels로 배우는 중급 회귀
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Complete the function
def calc_sum_of_squares(coeffs):
# Unpack coeffs
____, ____ = ____
# Calculate predicted y-values
y_pred = ____ + ____ * ____
# Calculate differences between y_pred and y_actual
y_diff = ____ - ____
# Calculate sum of squares
sum_sq = ____
# Return sum of squares
return sum_sq
# Test the function with intercept 10 and slope 1
print(calc_sum_of_squares([10, 1]))