`numpy`로 최소제곱법
아래 공식은 도입부에서 다룬 미적분을 전개한 결과입니다. 이번 연습에서는 미적분 결과가 옳다고 보고, 이 공식을 numpy 코드로 구현해 보겠습니다.
$$ a_{1} = \frac{ covariance(x, y) }{ variance(x) } $$ $$ a_{0} = mean(y) - a_{1} mean(x) $$
이 연습은 강의의 일부입니다
Python으로 배우는 선형 모델 입문
연습 안내
- 미리 로드된 데이터에서 두 변수
x, y의 평균과 편차를 계산하세요. np.sum()을 사용해 최소제곱 공식의 합을 완성하고, 이를 통해a0와a1의 최적 값을 구하세요.model()을 사용해 최적 기울기 a1과 절편 a0에서 모델 값y_model을 생성하세요.- 미리 정의된
compute_rss_and_plot_fit()으로 이 최적 모델이 데이터에 잘 맞는지 시각적으로 확인하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# prepare the means and deviations of the two variables
x_mean = np.____(x)
y_mean = np.____(y)
x_dev = x - ____
y_dev = y - ____
# Complete least-squares formulae to find the optimal a0, a1
a1 = np.sum(____ * ____) / np.sum( np.square(____) )
a0 = ____ - (a1 * ____)
# Use the those optimal model parameters a0, a1 to build a model
y_model = model(x, ____, ____)
# plot to verify that the resulting y_model best fits the data y
fig, rss = compute_rss_and_plot_fit(a0, a1)