# 단순회귀 : 경력 증가시 연봉 증가 상관관계
model <- lm(salary ~ experience, data = df)
summary(model)
##
## Call:
## lm(formula = salary ~ experience, data = df)
##
## Residuals:
## Min 1Q Median 3Q Max
## -5.291 -1.441 0.249 0.719 8.849
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 22.8111 1.3761 16.576 2.39e-12 ***
## experience 1.6200 0.2313 7.004 1.54e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.991 on 18 degrees of freedom
## Multiple R-squared: 0.7316, Adjusted R-squared: 0.7167
## F-statistic: 49.06 on 1 and 18 DF, p-value: 1.541e-06
# 다중회귀 : 경력 증가시 적성검사 점수 증가로 인한 연봉 증가까지 포함된 관계
# experience ~ score 의 cor() = 0.34
# model <- lm(salary ~ ., data = df)
model <- lm(salary ~ experience + score, data = df)
summary(model)
##
## Call:
## lm(formula = salary ~ experience + score, data = df)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.3586 -1.4581 -0.0341 1.1862 4.9102
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.17394 6.15607 0.516 0.61279
## experience 1.40390 0.19857 7.070 1.88e-06 ***
## score 0.25089 0.07735 3.243 0.00478 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.419 on 17 degrees of freedom
## Multiple R-squared: 0.8342, Adjusted R-squared: 0.8147
## F-statistic: 42.76 on 2 and 17 DF, p-value: 2.328e-07
# 추정된 회귀식
# salary = 3.174 + 1.404 * experience + 0.251 * score
# b1 : b2(score)가 일정하다고 할 때, experience가 1년 증가하면 salary가 $1,404 증가할 것으로 기대된다.
# b2 : b1(experience)가 일정하다고 할 때, score가 1점 증가하면 salary가 $251 증가할 것으로 기대된다.
# 다중회귀분석 결과 해석
# (1) Adjusted R-squared
# R-squared: 0.83 --> experience와 score가 salary 변동량의 83%를 설명한다.
# But, 설명변수 갯수가 증가하면 결정계수도 증가
# --> 설명변수 갯수에 대한 패널티 적용한 결정계수 = Adjusted R-squared
# (2) F-test
# H0 : b1 = b2 = ...... = bk = 0
# 종속변수와 모든 독립(설명)변수 집합간에 유의한 관계가 존재하는지 검정
# b0 는 큰 의미가 없다.
# (3) T-test
# H0 : bi = 0
# 각 개별 독립변수의 유의성 검정
# (4) 잔차분석 --> Residuals plot / Normal Q-Q plot / Leverage plot
# 영향점이 있는 경우
plot(model) # --> Leverage plot에서 2번째 자료가 이상치 & 영향점
dcolor <- rep(1, length(df$salary))
dcolor[2] = 2
pairs(df, col = dcolor, pch = dcolor) # 2번 자료만 다르게 표시
# 영향점 제거는 주관적으로 판단하는 수밖에 없다.
df2 <- df[-2, ] # 영향점 제거할 경우
pairs.panels(df2) # salary ~ experience 상관계수 높아짐(0.91). 다른 상관계수는 낮아짐.
model2 <- lm(salary ~ experience + score, data = df2)
summary(model2) # score 회귀계수가 유의하지 않다.
##
## Call:
## lm(formula = salary ~ experience + score, data = df2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.5221 -1.4259 0.1133 1.3351 3.8131
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 12.31238 5.93883 2.073 0.0547 .
## experience 1.42607 0.16426 8.682 1.89e-07 ***
## score 0.13469 0.07486 1.799 0.0909 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.999 on 16 degrees of freedom
## Multiple R-squared: 0.8592, Adjusted R-squared: 0.8416
## F-statistic: 48.83 on 2 and 16 DF, p-value: 1.542e-07
# 추정과 예측
# 경력 5년, 적성검사성적 80점인 사람과 경력 10년, 성적 70점인 사람의 연봉 예측
# 평균 연봉의 95% 신뢰구간
predict(model, data.frame("experience" = c(5,10), "score" = c(80,70)),
interval = "confidence")
# 독립변수들이 서로 높은 상관관계를 가지면 회귀계수의 정확한 추정이 어렵다.
# ---> 모형 선택 방법론을 적용하여 가장 적절한 변수를 선택할 수 있다.
# 30개 부서에서 부서당 35명의 직원 설문조사
# 데이터 숫자는 해당 질문에 긍정한 직원의 비율
attitude
a <- lm(rating ~ complaints + learning, data = attitude)
summary(a)
##
## Call:
## lm(formula = rating ~ complaints + learning, data = attitude)
##
## Residuals:
## Min 1Q Median 3Q Max
## -11.5568 -5.7331 0.6701 6.5341 10.3610
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 9.8709 7.0612 1.398 0.174
## complaints 0.6435 0.1185 5.432 9.57e-06 ***
## learning 0.2112 0.1344 1.571 0.128
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 6.817 on 27 degrees of freedom
## Multiple R-squared: 0.708, Adjusted R-squared: 0.6864
## F-statistic: 32.74 on 2 and 27 DF, p-value: 6.058e-08
# learning의 t-test p-value 값을 보면 유의하지 않다.
# 하지만 rating과 상관관계가 없는 것이 아니다.
# complaints 와의 상관관계도 있기 때문에 rating 변수에 대한 역할이 작아보일 뿐이다.
# 모형 선택법 (Model Selection) = 설명변수 선택
# *** 해당 업무분야에서 반드시 들어가야 하는 변수는 고정 !!!
# (1) Forward selection
# --- 가장 유의한 변수부터 하나씩 추가 (R-sq 기준)
# --- 변수값의 작은 변동에도 결과가 크게 달라져 안정성 부족
# (2) Backward selection
# --- 모든 변수를 넣고 가장 기여도가 낮은 것부터 하나씩 제거
# --- 전체 변수 정보를 이용하는 장점
# --- 변수의 갯수가 많은 경우 사용 어려움. 안정성 부족.
# (3) Stepwise selection
# --- Forward selection과 backward selection을 조합
# --- 새로운 변수 추가 후에 기존 변수의 중요도가 약화되면 그 변수 제거
# (4) All Subsets Regression
# --- 모든 가능한 모형을 비교하여 최적의 모형선택
# --- 여러 모형 중 최소 AIC, BIC, Mallow’s Cp 또는 최대 adjusted R-sq를 갖는 모형을 선택
# --- 모형의 복잡도에 벌점을 주는 방법. AIC (Akaike information criterion), BIC (Bayesian ...)
# Backward selection
out <- lm(rating ~ ., attitude)
summary(out)
plot(leap, scale = "adjr2") # adjusted r-squred 기준
# practice 5
# hotel margin prediction
data <- read.csv("data/laquinta.csv")
summary(data)
## Margin Number Nearest Office.Space
## Min. :27.30 Min. :1613 Min. :0.100 Min. :140.0
## 1st Qu.:40.15 1st Qu.:2729 1st Qu.:1.675 1st Qu.:391.5
## Median :46.00 Median :2934 Median :2.250 Median :486.5
## Mean :45.74 Mean :2985 Mean :2.310 Mean :492.2
## 3rd Qu.:51.62 3rd Qu.:3269 3rd Qu.:2.925 3rd Qu.:588.0
## Max. :62.80 Max. :4214 Max. :4.200 Max. :875.0
## Enrollment Income Distance
## Min. : 6.00 Min. :28.00 Min. : 0.200
## 1st Qu.:13.38 1st Qu.:33.00 1st Qu.: 4.550
## Median :16.00 Median :36.00 Median : 7.350
## Mean :16.07 Mean :36.22 Mean : 6.918
## 3rd Qu.:19.50 3rd Qu.:39.00 3rd Qu.: 9.025
## Max. :26.50 Max. :46.00 Max. :14.400