회귀분석

제이제이·2024년 2월 28일
  • 회귀분석은 독립 변수가 종속 변수에 미치는 영향을 확인하고자 하는 분석 방법이고, 예측할 때 사용한다.
  • 단순선형회귀분석 : 하나의 종속 변수와 하나의 독립 변수 사이의 관계를 분석
  • 다중선형회귀분석 : 하나의 종속 변수와 여러 독립 변수 사이의 관계를 분석

데이터 준비

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

fish = pd.read_csv('https://bit.ly/fish_csv_data')
fish_input= fish['Length'].to_numpy().reshape(-1,1)
fish_target= fish['Weight'].to_numpy().reshape(-1,1)
     
train_input, test_input, train_target, test_target = train_test_split(
    fish_input, fish_target, random_state=42)

1. 단순선형회귀

한 가지 변수가 다른 변수에 어느 정도 영향을 끼치는 지 확인할 때 사용한다.

from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(train_input, train_target)

print(lr.score(train_input, train_target)) # 0.8529337826650527
print(lr.score(test_input, test_target)) # 0.8156142079322759


print(lr.coef_, lr.intercept_) # 30.74712939  -482.91756701
# Weight = lr.coef_ * Length + lr.intercept_
# 위와 같은 식으로 도미의 길이가 도미의 무게에 얼마나 영향을 끼치는 지 알 수 있다.

2. 다중선형회귀

fish_input2 = fish[['Length', 'Diagonal', 'Height', 'Width']].to_numpy()

train_input, test_input, train_target, test_target = train_test_split(
    fish_input2, fish_target, random_state=42)
    
lr = LinearRegression()
lr.fit(train_input, train_target)

print(lr.score(train_input, train_target)) # 0.8832205123776352
print(lr.score(test_input, test_target)) # 0.8792941906217031


print(lr.intercept_) #-523.12881271
pd.DataFrame([lr.coef_.flatten()],columns = ['Length', 'Diagonal', 'Height', 'Width'])

# Weight = 53.972645 * Length - 28.896694 * Diagonal + 22.444731 * Height + 18.667501 * Width + lr.intercept_
생선의 무게에 다른 변수들이 얼마나 영향을 끼치는지 알 수 있다.

profile
데이터분석공부중

0개의 댓글