# LinearRegression으로 선형회귀모델을 작성 - mtcars dataset을 사용
import statsmodels.api
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score, mean_squared_error
mtcars = statsmodels.api.datasets.get_rdataset('mtcars').data
print(mtcars.head(3))
print(mtcars.corr(method = 'pearson'))
# hp가 mpg에 영향을 준다 라는 가정하에 모델을 생성 # r(상관계수) : -0.776168
x = mtcars[['hp']].values # 독립변수는 metrix로 넣어주어야 된다. [] o
print(x[:5])
y = mtcars['mpg'].values # 종속변수는 그대로 넣어주어도 된다. [] x
print(y[:5])
# plt.scatter(x, y)
# plt.show()
lmodel = LinearRegression().fit(x, y)
print('회귀계수(slope) :', lmodel.coef_) # -0.06822828
print('회귀계수(intercept) :', lmodel.intercept_) # 30.098860539622496
print()
pred = lmodel.predict(x)
print('예측값 :', np.round(pred[:5], 1))
print('실제값 :', y[:5])
# 모델 성능 확인
print('MSE :', mean_squared_error(y, pred)) # 실제값, 예측값 13.9898
print('R2(설명력) :', r2_score(y, pred)) # 0.60243
# 새로운 hp 데이터로 mpg 예측
new_hp = [[110]] # 독립변수 값이기 때문에 metrix로 넣어주어야 된다.
new_pred = lmodel.predict(new_hp)
print('%s 마력인 경우 연비는 %s입니다.'%(new_hp[0][0], new_pred[0]))
<console>
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
mpg cyl disp ... am gear carb
mpg 1.000000 -0.852162 -0.847551 ... 0.599832 0.480285 -0.550925
cyl -0.852162 1.000000 0.902033 ... -0.522607 -0.492687 0.526988
disp -0.847551 0.902033 1.000000 ... -0.591227 -0.555569 0.394977
hp -0.776168 0.832447 0.790949 ... -0.243204 -0.125704 0.749812
drat 0.681172 -0.699938 -0.710214 ... 0.712711 0.699610 -0.090790
wt -0.867659 0.782496 0.887980 ... -0.692495 -0.583287 0.427606
qsec 0.418684 -0.591242 -0.433698 ... -0.229861 -0.212682 -0.656249
vs 0.664039 -0.810812 -0.710416 ... 0.168345 0.206023 -0.569607
am 0.599832 -0.522607 -0.591227 ... 1.000000 0.794059 0.057534
gear 0.480285 -0.492687 -0.555569 ... 0.794059 1.000000 0.274073
carb -0.550925 0.526988 0.394977 ... 0.057534 0.274073 1.000000
[11 rows x 11 columns]
[[110]
[110]
[ 93]
[110]
[175]]
[21. 21. 22.8 21.4 18.7]
회귀계수(slope) : [-0.06822828]
회귀계수(intercept) : 30.098860539622496
예측값 : [22.6 22.6 23.8 22.6 18.2]
실제값 : [21. 21. 22.8 21.4 18.7]
MSE : 13.989822298268805
R2(설명력) : 0.602437341423934
110 마력인 경우 연비는 22.593749951750496입니다.
hp와 mpg의 상관계수 시각화