Scipy로 최적화하기
최소 RSS 값을 찾는 해석적(analytic) 해를 numpy로 구현할 수도 있어요. 하지만 더 복잡한 모델에서는 해석적 공식을 구할 수 없기 때문에 다른 방법을 사용해야 합니다.
이번 연습 문제에서는 같은 최적화 문제를 더 일반적인 방식으로 풀기 위해 scipy.optimize를 사용해 보겠습니다.
이 과정에서, "최적해가 얼마나 좋은가"를 알려 주는 추가 반환값도 확인하게 됩니다. 비교를 쉽게 하기 위해, 이전 연습 문제에서 사용한 것과 동일한 측정 데이터와 매개변수를 그대로 사용하겠습니다. 새로운 scipy 접근법과의 차이를 살펴보세요.
이 연습은 강의의 일부입니다
Python으로 배우는 선형 모델 입문
연습 안내
- 함수
model_func(x, a0, a1)을 정의하고, 주어진 배열x에 대해a0 + a1*x를 반환하게 하세요. scipy의optimize.curve_fit()함수를 사용해a0와a1의 최적값을 계산하세요.param_opt를 언패킹하여 모델 매개변수를a0 = param_opt[0],a1 = param_opt[1]로 저장하세요.- 미리 정의된 함수
compute_rss_and_plot_fit을 사용해 정답을 검증하고 결과를 확인하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Define a model function needed as input to scipy
def model_func(x, a0, a1):
return ____ + (____*x)
# Load the measured data you want to model
x_data, y_data = load_data()
# call curve_fit, passing in the model function and data; then unpack the results
param_opt, param_cov = optimize.curve_fit(____, x_data, y_data)
a0 = param_opt[0] # a0 is the intercept in y = a0 + a1*x
a1 = param_opt[1] # a1 is the slope in y = a0 + a1*x
# test that these parameters result in a model that fits the data
fig, rss = compute_rss_and_plot_fit(____, ____)