손실 함수 최소화하기
이 연습 문제에서는 scipy.optimize.minimize를 사용해 선형 회귀를 "처음부터" 직접 구현해 보겠습니다.
학습에는 Boston 주택 가격 데이터 세트를 사용하며, 이미 X와 y 변수에 로드되어 있습니다. 단순화를 위해 회귀 모형에 절편은 포함하지 않겠습니다.
이 연습은 강의의 일부입니다
Python으로 배우는 선형 분류기
연습 안내
- 최소제곱 선형 회귀의 손실 함수를 채워 넣으세요.
- scikit-learn의
LinearRegression으로 학습한 후 계수를 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# The squared error, summed over training examples
def my_loss(w):
s = 0
for i in range(y.size):
# Get the true and predicted target values for example 'i'
y_i_true = y[i]
y_i_pred = w@X[i]
s = s + (____)**2
return s
# Returns the w that makes my_loss(w) smallest
w_fit = minimize(my_loss, X[0]).x
print(w_fit)
# Compare with scikit-learn's LinearRegression coefficients
lr = LinearRegression(fit_intercept=False).fit(X,y)
print(____)