Replicated

최소자승법 - Python 구현 본문

카테고리 없음

최소자승법 - Python 구현

라구넹 2025. 4. 7. 21:49
import numpy as np

x = np.array([1, 2, 3]).reshape(-1, 1)
y = np.array([2, 3, 5])

x_with_intercept = np.c_[np.ones(x.shape[0]), x]

w = np.linalg.inv(x_with_intercept.T.dot(x_with_intercept)).dot(x_with_intercept.T).dot(y)

intercept = w[0]
slope = w[1]

print("절편: ", intercept)
print("기울기: ", slope)

y_pred = x_with_intercept.dot(w)
print("예측값: ", y_pred)

x는 독립변수

.reshape(-1, 1)은 무엇이냐?

- reshape 배열의 형태 변경

- -1 -> 행 개수 자동 계산

- 열의 개수 1로 고정

=> 1열짜리 세로 벡터로 만들어달라!

 

x_with_intercept = np.c_[np.ones(x.shape[0]), x]

x_with_intercept -> x에 절편을 추가

np.ones(x.shape[0]) -> 길이가 3인 [1, 1, 1] 벡터 생성

np.c_[]는 열 방향으로 두 배열을 붙여줌

[[1. 1.]
 [1. 2.]
 [1. 3.]]

결과적으론 이런 형태

 

w = np.linalg.inv(x_with_intercept.T.dot(x_with_intercept)).dot(x_with_intercept.T).dot(y)

그냥 이거 수식

 

intercept = w[0]
slope = w[1]

w[0]는 절편

w[1]은 x 계수

 

y_pred = x_with_intercept.dot(w)

이제 가중치(세타)를 입력값이랑 곱하면 y 예측값이 나올 것임

결과는 이렇게 나옴

 


 

사이킷런(SKlearn) 이용도 가능

import numpy as np
from sklearn.linear_model import LinearRegression

x = np.array([1, 2, 3]).reshape(-1, 1)
y = np.array([2, 3, 5])

model = LinearRegression()

model.fit(x, y)

print("회기 계수 (기울기): ", model.coef_)
print("절편: ", model.intercept_)

y_pred = model.predict(x)
print("예측값: ", y_pred)

x, y만드는 것까진 같은데

그냥 LinearRegression 만들고 fit해버리면 답 나옴

coef_가 기울기

intercept_가 절편

가설함수는 _predict()