김자영 강사님
독립변수와 종속변수 간의 선형적 관계를 찾는다. 즉, 독립변수가 변할 때 종속변수가 어떻게 변하는지를 설명하는 직선을 찾는다.
y
: 예측값(종속변수)x
: 독립변수w
: 기울기(회귀계수)b
: 절편여러 개의 독립변수가 종속변수에 미치는 영향을 분석한다.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, root_mean_squared_error, r2_score
pandas
: 데이터를 불러오고 다루기 위한 라이브러리numpy
: 수치 계산을 위한 라이브러리matplotlib.pyplot
, seaborn
: 데이터 시각화를 위한 라이브러리train_test_split
: 데이터를 학습용(훈련) 데이터와 평가용(테스트) 데이터로 나누기 위한 함수LinearRegression
: 선형 회귀 모델을 구현하는 클래스mean_absolute_error
, root_mean_squared_error
, r2_score
: 모델의 성능을 평가하는 지표(MAE와 RMSE, R^2)를 계산하기 위한 함수df = pd.read_csv('data/advertising.csv')
데이터를 CSV 파일로 불러온다. df
는 데이터 프레임 형태로 저장된다.
여기서는 TV 광고비, 라디오 광고비, 신문 광고비와 같은 독립변수와 판매량이라는 종속변수로 구성된다.
X = df[['TV']] # TV 광고비 (독립변수)
y = df['Sales'] # 판매량 (종속변수)
X
: 독립변수로 TV 광고비를 사용. 두 개 이상의 독립변수가 있을 수 있지만, 단순 선형 회귀에서는 하나의 독립변수를 사용한다.y
: 종속변수로 판매량을 나타냄. TV 광고비가 판매량에 어떤 영향을 미치는지 예측하는 것이 목표X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
test_size=0.25
: 전체 데이터 중 25%를 테스트 세트로 사용random_state=42
: 실행할 때마다 동일한 결과를 얻기 위해 설정한느 고정된 난수 시드X_train
, y_train
: 모델 학습에 사용되는 훈련 데이터X_test
, y_test
: 학습된 모델을 평가하는 데 사용되는 테스트 데이터model = LinearRegression() # 선형 회귀 모델 생성
model.fit(X_train, y_train) # 훈련 데이터를 사용하여 모델 학습
LinearRegression()
을 사용해 선형 회귀 모델을 생성fit(X_train, y_train)
: 훈련 데이터를 사용해 모델을 학습시킨다.y_pred = model.predict(X_test)
학습된 모델을 사용해 테스트 데이터의 X_test
값으로 판매량을 예측한다. y_pred
는 모델이 예측한 판매량을 담고 있다.
mae = mean_absolute_error(y_test, y_pred)
rmse = root_mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f'MAE: {mae:.2f}')
print(f'RMSE: {rmse:.2f}')
print(f'R2: {r2:.2f}')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('ggplot')
# 한글폰트 설정 (그래프에서 한글 깨짐 방지)
import matplotlib as mpl
mpl.rc('font', family='Malgun Gothic')
mpl.rcParams['axes.unicode_minus'] = False
# datetime 컬럼을 날짜 형식으로 읽어오기
df = pd.read_csv('data/bike_sharing_demand.csv', parse_dates=['datetime'])
# 데이터 확인
display(df.head(3)) # 데이터 상위 3개 행 출력
display(df.tail(3)) # 데이터 하위 3개 행 출력
parse_dates=['datetime']
: CSV 파일에서 datetime
열을 날짜 형식으로 변환해 읽어온다.df.head()
, df.tail()
: 데이터의 앞(뒷)부분을 확인하여 데이터 구조를 살펴본다.df.info()
데이터의 구조(행과 열), 결측치 유무, 각 열의 데이터 타입을 확인.
# 'datetime'에서 연, 월, 일, 시간, 요일 추출
df['year'] = df['datetime'].dt.year
df['month'] = df['datetime'].dt.month
df['day'] = df['datetime'].dt.day
df['hour'] = df['datetime'].dt.hour
df['dayofweek'] = df['datetime'].dt.dayofweek # 월요일:0, 일요일:6
파생변수 기존 데이터를 기반으로 새롭게 생성된 변수이다. 여기서는 datetime
컬럼에서 연도, 월, 일, 시간, 요일 정보를 추출해 추가한다.
연, 월, 일, 시간, 요일별 대여량 시각화
plt.figure(figsize=(15, 8))
features = ['year', 'month', 'day', 'hour', 'dayofweek']
for i, feature in enumerate(features):
plt.subplot(2, 3, i+1)
sns.barplot(data=df, x=feature, y='count', estimator='mean', hue='year', palette='muted')
plt.title(feature + '-count')
plt.tight_layout()
plt.show()
# 요일과 시간에 따른 자전거 대여량 시각화
sns.lineplot(data=df, x='hour', y='count', marker='o', hue='dayofweek', estimator='sum', palette='muted')
plt.title('hour-dayofweek count')
plt.xticks(range(0, 24))
plt.grid(ls=':')
plt.show()
hour
과 dayofweek
에 따른 자전거 대여량을 선 그래프로 표현hue='dayofweek'
: 요일별로 구분된 그래프를 그려준다.# 기온과 대여량 관계 시각화
plt.figure(figsize=(15, 4))
plt.subplot(121)
sns.histplot(df['temp'], bins=20, kde=True) # 히스토그램과 커널 밀도 추정
plt.title('temp-count')
plt.subplot(122)
sns.regplot(data=df, x='temp', y='count', color='gray', line_kws={'color': 'red'}, marker='.')
plt.title('temp-count')
plt.show()
temp
와 count
의 관계를 시각화# 변수 간 상관관계 분석
corr_matt = ['temp', 'atemp', 'humidity', 'windspeed', 'count']
corr = abs(df[corr_matt].corr())
sns.heatmap(corr, annot=True, cmap='Blues', fmt='.2f')
plt.show()
corr()
함수는 상관관계 게수를 계산하고, heatmap
으로 시각화한다.temp
, atemp
, humidity
, windspeed
, count
간의 상관관계를 분석.# 변수 선택
X = df[['temp', 'humidity', 'windspeed']] # 독립변수
y = df['count'] # 종속변수
# 데이터 분할: 훈련세트와 테스트세트
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
train_test_split()
을 사용해 데이터셋을 75%는 훈련용, 25%는 테스트용으로 분할
# 선형 회귀 모델 생성 및 학습
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
# 테스트 데이터 예측
y_pred = model.predict(X_test)
# 성능 평가
from sklearn.metrics import mean_absolute_error, root_mean_squared_error, r2_score
mae = mean_absolute_error(y_test, y_pred)
rmse = root_mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f'MAE: {mae:.2f}')
print(f'RMSE: {rmse:.2f}')
print(f'R^2: {r2:.2f}')
LinearRegression()
으로 선형 회귀 모델을 생성한 후 fit()
메서드를 사용해 훈련 데이터를 학습.