`statsmodels`로 최소제곱법
여러 Python 라이브러리는 모델 최적화의 내부 과정을 매번 직접 다루지 않아도 되도록 편리한 추상화 인터페이스를 제공합니다.
예를 들어, 이번 연습 문제에서는 statsmodels 라이브러리를 사용해 최소제곱 최적화(RSS 최소화)를 활용한 좀 더 고수준의 일반화된 워크플로로 모델을 구축해 보겠습니다.
시작을 돕기 위해 x_data, y_data = load_data()로 불러온 데이터를 미리 로드해 두었고, df = pd.DataFrame(dict(x_column=x_data, y_column=y_data))를 사용해 열 이름이 x_column, y_column인 pandas DataFrame에 저장해 두었습니다.
이 연습은 강의의 일부입니다
Python으로 배우는 선형 모델 입문
연습 안내
formula="y_column ~ x_column",data=df를 인수로 하는ols()로 모델을 만들고,.fit()을 호출해 데이터에 적합하세요.model_fit.predict()를 사용해y_model값을 구하세요.- 제공된 함수
plot_data_with_model()로y_data와y_model을 겹쳐서 그리세요. model_fit.params에서 모델 파라미터a0,a1값을 추출하세요.compute_rss_and_plot_fit()를 사용해 이 결과가numpy로 구현된 해석적 공식과 일치하는지 확인하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Pass data and `formula` into ols(), use and `.fit()` the model to the data
model_fit = ols(____="y_column ~ x_column", ____=df).____()
# Use .predict(df) to get y_model values, then over-plot y_data with y_model
y_model = model_fit.____(df)
fig = plot_data_with_model(x_data, ____, ____)
# Extract the a0, a1 values from model_fit.params
a0 = model_fit.____['Intercept']
a1 = model_fit.____['x_column']
# Visually verify that these parameters a0, a1 give the minimum RSS
fig, rss = compute_rss_and_plot_fit(a0, a1)