[ML] 최소 제곱 선형 회귀 모델

Woong·2023년 9월 11일
0

Python / Machine Learning

목록 보기
20/20

최소 제곱법 (Ordinary Least Squares, OLS)

  • 선형 회귀 직선의 모델 파라미터를 추정하는 방법
    • training sample 까지의 수직 거리 (=offset) 의 제곱합을 최소화
  • 선형 최소 제곱법 (linear least squares) 라고도 한다.

사이킷런으로 회귀 모델의 가중치 추정

  • 사이킷런의 회귀 추정기는 scipy의 최소 제곱 구현 (scipy.linalg.lstsq) 를 사용

    • gradient descent(경사하강법) 을 사용하지 않기 때문에 표준화 전처리 불필요
    • 표준화하지 않았을 때 모델의 가중치가 달라지는 것에 유의
  • 데이터 준비


import matplotlib.pyplot as plt
from mlxtend.plotting import scatterplotmatrix

import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/rasbt/'
                 'python-machine-learning-book-3rd-edition/'
                 'master/ch10/housing.data.txt',
                 header=None,
                 sep='\s+')

df.columns = ['CRIM', 'ZN', 'INDUS', 'CHAS',
              'NOX', 'RM', 'AGE', 'DIS', 'RAD',
              'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']

cols = ['LSTAT', 'INDUS', 'NOX', 'RM', 'MEDV']
X = df[['RM']].values
y = df['MEDV'].values
  • 시각화를 위한 함수 정의
    • training sample 의 산점도와 회귀 직선 그리기
def lin_regplot(X, y, model):
    plt.scatter(X, y, c='steelblue', edgecolor='white', s=70)
    plt.plot(X, model.predict(X), color='black', lw=2)
    return
  • 사이킷런으로 회귀 모델의 가중치 추정
from sklearn.linear_model import LinearRegression

slr = LinearRegression()
slr.fit(X, y)
y_pred = slr.predict(X)
print('기울기: %.3f' % slr.coef_[0])
print('절편: %.3f' % slr.intercept_)


lin_regplot(X, y, slr)
plt.xlabel('Average number of rooms [RM]')
plt.ylabel('Price in $1000s [MEDV]')
plt.show()
	
  • 출력값
기울기: 9.102
절편: -34.671

reference

  • 서적 '머신러닝 교과서 with 파이썬, 사이킷런, 텐서플로 개정 3판'

0개의 댓글