Linear Regression and Model Selection
Multiple Linear Regression · Forward · Backward · Model Diagnostics
Ketika beberapa karakteristik pemain digunakan untuk menjelaskan gaji, tidak semua prediktor selalu diperlukan. Praktikum ini mempelajari regresi linear berganda dan pemilihan model menggunakan data Hitters.When several player characteristics are used to explain salaries, not every predictor is necessarily required. This practicum explores multiple linear regression and model selection using Hitters.
Bangun model penuh, periksa kolinearitas, bandingkan prosedur seleksi, kemudian lakukan diagnostik dan prediksi. Jalankan kode RStudio secara berurutan.Fit a full model, inspect multicollinearity, compare selection procedures, and then perform diagnostics and prediction. Run the RStudio code in sequence.
PackagePackage
Siapkan paket untuk regresi, diagnostik, dan seleksi model.Prepare packages for regression, diagnostics, and model selection.
Silahkan install package jika belum ada.
# install.packages("ISLR2")
# install.packages("tidyverse")
# install.packages("broom")
# install.packages("car")
# install.packages("leaps")library(ISLR2)
library(tidyverse)── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ── ✔ dplyr 1.2.1 ✔ readr 2.2.0 ✔ forcats 1.0.1 ✔ stringr 1.6.0 ✔ ggplot2 4.0.3 ✔ tibble 3.3.1 ✔ lubridate 1.9.5 ✔ tidyr 1.3.2 ✔ purrr 1.2.2 ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ── ✖ dplyr::filter() masks stats::filter() ✖ dplyr::lag() masks stats::lag() ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(broom)
library(car)Loading required package: carData
Attaching package: 'car'
The following object is masked from 'package:dplyr':
recode
The following object is masked from 'package:purrr':
somelibrary(leaps)Please install the packages if they have not been installed.
# install.packages("ISLR2")
# install.packages("tidyverse")
# install.packages("broom")
# install.packages("car")
# install.packages("leaps")library(ISLR2)
library(tidyverse)── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ── ✔ dplyr 1.2.1 ✔ readr 2.2.0 ✔ forcats 1.0.1 ✔ stringr 1.6.0 ✔ ggplot2 4.0.3 ✔ tibble 3.3.1 ✔ lubridate 1.9.5 ✔ tidyr 1.3.2 ✔ purrr 1.2.2 ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ── ✖ dplyr::filter() masks stats::filter() ✖ dplyr::lag() masks stats::lag() ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(broom)
library(car)Loading required package: carData
Attaching package: 'car'
The following object is masked from 'package:dplyr':
recode
The following object is masked from 'package:purrr':
somelibrary(leaps)DataData
Gunakan Hitters dari ISLR2. Periksa 322 observasi dan nilai Salary yang hilang sebelum membangun model.Use Hitters from ISLR2. Inspect 322 observations and missing Salary values before fitting models.
Data yang digunakan adalah data Hitters dari package ISLR2 . Data ini berisi informasi mengenai pemain Major League Baseball pada musim 1986.
Peubah Salary akan digunakan sebagai peubah respon, sedangkan beberapa karakteristik pemain akan digunakan sebagai peubah prediktor.
data("Hitters")Melihat dimensi data.
dim(Hitters)[1] 322 20
Melihat nama peubah yang tersedia.
names(Hitters)[1] "AtBat" "Hits" "HmRun" "Runs" "RBI" "Walks" [7] "Years" "CAtBat" "CHits" "CHmRun" "CRuns" "CRBI" [13] "CWalks" "League" "Division" "PutOuts" "Assists" "Errors" [19] "Salary" "NewLeague"
Melihat beberapa observasi pertama.
head(Hitters) AtBat Hits HmRun Runs RBI Walks Years CAtBat CHits CHmRun
-Andy Allanson 293 66 1 30 29 14 1 293 66 1
-Alan Ashby 315 81 7 24 38 39 14 3449 835 69
-Alvin Davis 479 130 18 66 72 76 3 1624 457 63
-Andre Dawson 496 141 20 65 78 37 11 5628 1575 225
-Andres Galarraga 321 87 10 39 42 30 2 396 101 12
-Alfredo Griffin 594 169 4 74 51 35 11 4408 1133 19
CRuns CRBI CWalks League Division PutOuts Assists Errors
-Andy Allanson 30 29 14 A E 446 33 20
-Alan Ashby 321 414 375 N W 632 43 10
-Alvin Davis 224 266 263 A W 880 82 14
-Andre Dawson 828 838 354 N E 200 11 3
-Andres Galarraga 48 46 33 N E 805 40 4
-Alfredo Griffin 501 336 194 A W 282 421 25
Salary NewLeague
-Andy Allanson NA A
-Alan Ashby 475.0 N
-Alvin Davis 480.0 A
-Andre Dawson 500.0 N
-Andres Galarraga 91.5 N
-Alfredo Griffin 750.0 AMelihat struktur data.
str(Hitters)'data.frame': 322 obs. of 20 variables: $ AtBat : int 293 315 479 496 321 594 185 298 323 401 ... $ Hits : int 66 81 130 141 87 169 37 73 81 92 ... $ HmRun : int 1 7 18 20 10 4 1 0 6 17 ... $ Runs : int 30 24 66 65 39 74 23 24 26 49 ... $ RBI : int 29 38 72 78 42 51 8 24 32 66 ... $ Walks : int 14 39 76 37 30 35 21 7 8 65 ... $ Years : int 1 14 3 11 2 11 2 3 2 13 ... $ CAtBat : int 293 3449 1624 5628 396 4408 214 509 341 5206 ... $ CHits : int 66 835 457 1575 101 1133 42 108 86 1332 ... $ CHmRun : int 1 69 63 225 12 19 1 0 6 253 ... $ CRuns : int 30 321 224 828 48 501 30 41 32 784 ... $ CRBI : int 29 414 266 838 46 336 9 37 34 890 ... $ CWalks : int 14 375 263 354 33 194 24 12 8 866 ... $ League : Factor w/ 2 levels "A","N": 1 2 1 2 2 1 2 1 2 1 ... $ Division : Factor w/ 2 levels "E","W": 1 2 2 1 1 2 1 2 2 1 ... $ PutOuts : int 446 632 880 200 805 282 76 121 143 0 ... $ Assists : int 33 43 82 11 40 421 127 283 290 0 ... $ Errors : int 20 10 14 3 4 25 7 9 19 0 ... $ Salary : num NA 475 480 500 91.5 750 70 100 75 1100 ... $ NewLeague: Factor w/ 2 levels "A","N": 1 2 1 2 2 1 1 1 2 1 ...
Pada data Hitters terdapat beberapa observasi yang tidak memiliki informasi pada peubah Salary .
sum(is.na(Hitters$Salary))[1] 59
Observasi yang memiliki nilai hilang akan dikeluarkan terlebih dahulu.
hitters <- Hitters %>%
drop_na()Periksa kembali ukuran data dan jumlah missing value.
dim(hitters)[1] 263 20
sum(is.na(hitters))[1] 0
Untuk mempermudah ilustrasi, pada bagian awal hanya digunakan beberapa peubah prediktor.
hitters_sub <- hitters %>%
select(
Salary,
AtBat,
Hits,
HmRun,
Runs,
RBI,
Walks,
Years
)head(hitters_sub)Salary AtBat Hits HmRun Runs RBI Walks Years -Alan Ashby 475.0 315 81 7 24 38 39 14 -Alvin Davis 480.0 479 130 18 66 72 76 3 -Andre Dawson 500.0 496 141 20 65 78 37 11 -Andres Galarraga 91.5 321 87 10 39 42 30 2 -Alfredo Griffin 750.0 594 169 4 74 51 35 11 -Al Newman 70.0 185 37 1 23 8 21 2
Peubah yang digunakan adalah:
Salary : gaji tahunan pemain dalam ribuan dolar AtBat : jumlah kesempatan memukul Hits : jumlah pukulan yang berhasil HmRun : jumlah home run Runs : jumlah run RBI : jumlah run batted in Walks : jumlah walk Years : jumlah tahun bermain di liga utama
The data used in this practicum are the Hitters data from the ISLR2 package. These data contain information on Major League Baseball players from the 1986 season.
The Salary variable will be used as the response variable, while several player characteristics will be used as predictor variables.
data("Hitters")View the dimensions of the data.
dim(Hitters)[1] 322 20
View the available variable names.
names(Hitters)[1] "AtBat" "Hits" "HmRun" "Runs" "RBI" "Walks" [7] "Years" "CAtBat" "CHits" "CHmRun" "CRuns" "CRBI" [13] "CWalks" "League" "Division" "PutOuts" "Assists" "Errors" [19] "Salary" "NewLeague"
View the first few observations.
head(Hitters) AtBat Hits HmRun Runs RBI Walks Years CAtBat CHits CHmRun
-Andy Allanson 293 66 1 30 29 14 1 293 66 1
-Alan Ashby 315 81 7 24 38 39 14 3449 835 69
-Alvin Davis 479 130 18 66 72 76 3 1624 457 63
-Andre Dawson 496 141 20 65 78 37 11 5628 1575 225
-Andres Galarraga 321 87 10 39 42 30 2 396 101 12
-Alfredo Griffin 594 169 4 74 51 35 11 4408 1133 19
CRuns CRBI CWalks League Division PutOuts Assists Errors
-Andy Allanson 30 29 14 A E 446 33 20
-Alan Ashby 321 414 375 N W 632 43 10
-Alvin Davis 224 266 263 A W 880 82 14
-Andre Dawson 828 838 354 N E 200 11 3
-Andres Galarraga 48 46 33 N E 805 40 4
-Alfredo Griffin 501 336 194 A W 282 421 25
Salary NewLeague
-Andy Allanson NA A
-Alan Ashby 475.0 N
-Alvin Davis 480.0 A
-Andre Dawson 500.0 N
-Andres Galarraga 91.5 N
-Alfredo Griffin 750.0 AView the structure of the data.
str(Hitters)'data.frame': 322 obs. of 20 variables: $ AtBat : int 293 315 479 496 321 594 185 298 323 401 ... $ Hits : int 66 81 130 141 87 169 37 73 81 92 ... $ HmRun : int 1 7 18 20 10 4 1 0 6 17 ... $ Runs : int 30 24 66 65 39 74 23 24 26 49 ... $ RBI : int 29 38 72 78 42 51 8 24 32 66 ... $ Walks : int 14 39 76 37 30 35 21 7 8 65 ... $ Years : int 1 14 3 11 2 11 2 3 2 13 ... $ CAtBat : int 293 3449 1624 5628 396 4408 214 509 341 5206 ... $ CHits : int 66 835 457 1575 101 1133 42 108 86 1332 ... $ CHmRun : int 1 69 63 225 12 19 1 0 6 253 ... $ CRuns : int 30 321 224 828 48 501 30 41 32 784 ... $ CRBI : int 29 414 266 838 46 336 9 37 34 890 ... $ CWalks : int 14 375 263 354 33 194 24 12 8 866 ... $ League : Factor w/ 2 levels "A","N": 1 2 1 2 2 1 2 1 2 1 ... $ Division : Factor w/ 2 levels "E","W": 1 2 2 1 1 2 1 2 2 1 ... $ PutOuts : int 446 632 880 200 805 282 76 121 143 0 ... $ Assists : int 33 43 82 11 40 421 127 283 290 0 ... $ Errors : int 20 10 14 3 4 25 7 9 19 0 ... $ Salary : num NA 475 480 500 91.5 750 70 100 75 1100 ... $ NewLeague: Factor w/ 2 levels "A","N": 1 2 1 2 2 1 1 1 2 1 ...
In the Hitters data, several observations do not have information for the Salary variable.
sum(is.na(Hitters$Salary))[1] 59
Observations containing missing values will first be removed.
hitters <- Hitters %>%
drop_na()Check the size of the data and the number of missing values again.
dim(hitters)[1] 263 20
sum(is.na(hitters))[1] 0
To simplify the illustration, only several predictor variables are used in the initial section.
hitters_sub <- hitters %>%
select(
Salary,
AtBat,
Hits,
HmRun,
Runs,
RBI,
Walks,
Years
)head(hitters_sub)Salary AtBat Hits HmRun Runs RBI Walks Years -Alan Ashby 475.0 315 81 7 24 38 39 14 -Alvin Davis 480.0 479 130 18 66 72 76 3 -Andre Dawson 500.0 496 141 20 65 78 37 11 -Andres Galarraga 91.5 321 87 10 39 42 30 2 -Alfredo Griffin 750.0 594 169 4 74 51 35 11 -Al Newman 70.0 185 37 1 23 8 21 2
The variables used are:
Salary : annual salary of the player in thousands of dollars AtBat : number of times at bat Hits : number of hits HmRun : number of home runs Runs : number of runs RBI : number of runs batted in Walks : number of walks Years : number of years in the major leagues
Eksplorasi DataData Exploration
Ringkasan, korelasi, dan scatter plot membantu mengenali distribusi serta hubungan prediktor sebelum estimasi.Summaries, correlations and scatter plots help identify distributions and predictor relationships before estimation.
Sebelum membentuk model regresi, terlebih dahulu dilihat ringkasan dari masing-masing peubah.
summary(hitters_sub) Salary AtBat Hits HmRun
Min. : 67.5 Min. : 19.0 Min. : 1.0 Min. : 0.00
1st Qu.: 190.0 1st Qu.:282.5 1st Qu.: 71.5 1st Qu.: 5.00
Median : 425.0 Median :413.0 Median :103.0 Median : 9.00
Mean : 535.9 Mean :403.6 Mean :107.8 Mean :11.62
3rd Qu.: 750.0 3rd Qu.:526.0 3rd Qu.:141.5 3rd Qu.:18.00
Max. :2460.0 Max. :687.0 Max. :238.0 Max. :40.00
Runs RBI Walks Years
Min. : 0.00 Min. : 0.00 Min. : 0.00 Min. : 1.000
1st Qu.: 33.50 1st Qu.: 30.00 1st Qu.: 23.00 1st Qu.: 4.000
Median : 52.00 Median : 47.00 Median : 37.00 Median : 6.000
Mean : 54.75 Mean : 51.49 Mean : 41.11 Mean : 7.312
3rd Qu.: 73.00 3rd Qu.: 71.00 3rd Qu.: 57.00 3rd Qu.:10.000
Max. :130.00 Max. :121.00 Max. :105.00 Max. :24.000Selanjutnya dilihat hubungan antar peubah numerik menggunakan korelasi.
hitters_sub %>%
cor() %>%
round(3)Salary AtBat Hits HmRun Runs RBI Walks Years Salary 1.000 0.395 0.439 0.343 0.420 0.449 0.444 0.401 AtBat 0.395 1.000 0.964 0.555 0.900 0.796 0.624 0.013 Hits 0.439 0.964 1.000 0.531 0.911 0.788 0.587 0.019 HmRun 0.343 0.555 0.531 1.000 0.631 0.849 0.440 0.113 Runs 0.420 0.900 0.911 0.631 1.000 0.779 0.697 -0.012 RBI 0.449 0.796 0.788 0.849 0.779 1.000 0.570 0.130 Walks 0.444 0.624 0.587 0.440 0.697 0.570 1.000 0.135 Years 0.401 0.013 0.019 0.113 -0.012 0.130 0.135 1.000
Hubungan antara peubah respon dan masing-masing prediktor juga dapat dilihat melalui scatter plot.
hitters_sub %>%
pivot_longer(
cols = -Salary,
names_to = "Prediktor",
values_to = "Nilai"
) %>%
ggplot(aes(x = Nilai, y = Salary)) +
geom_point(alpha = 0.6) +
geom_smooth(method = "lm", se = FALSE) +
facet_wrap(~ Prediktor, scales = "free_x") +
theme_bw()`geom_smooth()` using formula = 'y ~ x'
Before fitting the regression model, a summary of each variable is first examined.
summary(hitters_sub) Salary AtBat Hits HmRun
Min. : 67.5 Min. : 19.0 Min. : 1.0 Min. : 0.00
1st Qu.: 190.0 1st Qu.:282.5 1st Qu.: 71.5 1st Qu.: 5.00
Median : 425.0 Median :413.0 Median :103.0 Median : 9.00
Mean : 535.9 Mean :403.6 Mean :107.8 Mean :11.62
3rd Qu.: 750.0 3rd Qu.:526.0 3rd Qu.:141.5 3rd Qu.:18.00
Max. :2460.0 Max. :687.0 Max. :238.0 Max. :40.00
Runs RBI Walks Years
Min. : 0.00 Min. : 0.00 Min. : 0.00 Min. : 1.000
1st Qu.: 33.50 1st Qu.: 30.00 1st Qu.: 23.00 1st Qu.: 4.000
Median : 52.00 Median : 47.00 Median : 37.00 Median : 6.000
Mean : 54.75 Mean : 51.49 Mean : 41.11 Mean : 7.312
3rd Qu.: 73.00 3rd Qu.: 71.00 3rd Qu.: 57.00 3rd Qu.:10.000
Max. :130.00 Max. :121.00 Max. :105.00 Max. :24.000Next, the relationships among numerical variables are examined using correlations.
hitters_sub %>%
cor() %>%
round(3)Salary AtBat Hits HmRun Runs RBI Walks Years Salary 1.000 0.395 0.439 0.343 0.420 0.449 0.444 0.401 AtBat 0.395 1.000 0.964 0.555 0.900 0.796 0.624 0.013 Hits 0.439 0.964 1.000 0.531 0.911 0.788 0.587 0.019 HmRun 0.343 0.555 0.531 1.000 0.631 0.849 0.440 0.113 Runs 0.420 0.900 0.911 0.631 1.000 0.779 0.697 -0.012 RBI 0.449 0.796 0.788 0.849 0.779 1.000 0.570 0.130 Walks 0.444 0.624 0.587 0.440 0.697 0.570 1.000 0.135 Years 0.401 0.013 0.019 0.113 -0.012 0.130 0.135 1.000
The relationship between the response variable and each predictor can also be examined using scatter plots.
hitters_sub %>%
pivot_longer(
cols = -Salary,
names_to = "Predictor",
values_to = "Value"
) %>%
ggplot(aes(x = Value, y = Salary)) +
geom_point(alpha = 0.6) +
geom_smooth(method = "lm", se = FALSE) +
facet_wrap(~ Predictor, scales = "free_x") +
theme_bw()`geom_smooth()` using formula = 'y ~ x'
Regresi Linear BergandaMultiple Linear Regression
Regresi berganda mengestimasi hubungan kondisional Salary dengan beberapa prediktor.Multiple regression estimates conditional associations between Salary and several predictors.
Regresi linear berganda digunakan ketika terdapat lebih dari satu peubah prediktor. Secara umum model regresi linear berganda dapat dituliskan sebagai
\[Y_i=\beta_0+\beta_1X_{i1}+\beta_2X_{i2}+\cdots+\beta_pX_{ip}+\varepsilon_i.\]
Model awal dibentuk menggunakan seluruh prediktor yang tersedia pada hitters_sub .
mod_full <- lm(
Salary ~ AtBat + Hits + HmRun + Runs +
RBI + Walks + Years,
data = hitters_sub
)summary(mod_full)Call:
lm(formula = Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks +
Years, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-867.11 -197.03 -43.58 100.80 2194.60
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -98.4320 75.2485 -1.308 0.192020
AtBat -2.0211 0.5877 -3.439 0.000682 ***
Hits 8.4843 2.2172 3.827 0.000164 ***
HmRun 1.4661 5.8288 0.252 0.801610
Runs -1.1859 2.7243 -0.435 0.663716
RBI 2.3958 2.5747 0.931 0.352991
Walks 5.5736 1.5123 3.685 0.000279 ***
Years 31.5493 4.7594 6.629 2e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 351.7 on 255 degrees of freedom
Multiple R-squared: 0.4085, Adjusted R-squared: 0.3923
F-statistic: 25.16 on 7 and 255 DF, p-value: < 2.2e-16Output summary() memberikan informasi mengenai estimasi koefisien regresi, standard error, statistik uji, p-value, nilai (R^2), adjusted (R^2), dan statistik F.
Koefisien model dapat ditampilkan dalam bentuk yang lebih ringkas menggunakan fungsi tidy() .
tidy(mod_full)# A tibble: 8 × 5 term estimate std.error statistic p.value <chr> <dbl> <dbl> <dbl> <dbl> 1 (Intercept) -98.4 75.2 -1.31 1.92e- 1 2 AtBat -2.02 0.588 -3.44 6.82e- 4 3 Hits 8.48 2.22 3.83 1.64e- 4 4 HmRun 1.47 5.83 0.252 8.02e- 1 5 Runs -1.19 2.72 -0.435 6.64e- 1 6 RBI 2.40 2.57 0.931 3.53e- 1 7 Walks 5.57 1.51 3.69 2.79e- 4 8 Years 31.5 4.76 6.63 2.00e-10
Sedangkan informasi mengenai model secara keseluruhan dapat dilihat menggunakan fungsi glance() .
glance(mod_full)# A tibble: 1 × 12
r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0.409 0.392 352. 25.2 5.22e-26 7 -1911. 3840. 3872.
# ℹ 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>Multiple linear regression is used when there is more than one predictor variable. In general, the multiple linear regression model can be written as
\[Y_i=\beta_0+\beta_1X_{i1}+\cdots+\beta_pX_{ip}+\varepsilon_i.\]
The initial model is fitted using all predictors available in hitters_sub .
mod_full <- lm(
Salary ~ AtBat + Hits + HmRun + Runs +
RBI + Walks + Years,
data = hitters_sub
)summary(mod_full)Call:
lm(formula = Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks +
Years, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-867.11 -197.03 -43.58 100.80 2194.60
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -98.4320 75.2485 -1.308 0.192020
AtBat -2.0211 0.5877 -3.439 0.000682 ***
Hits 8.4843 2.2172 3.827 0.000164 ***
HmRun 1.4661 5.8288 0.252 0.801610
Runs -1.1859 2.7243 -0.435 0.663716
RBI 2.3958 2.5747 0.931 0.352991
Walks 5.5736 1.5123 3.685 0.000279 ***
Years 31.5493 4.7594 6.629 2e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 351.7 on 255 degrees of freedom
Multiple R-squared: 0.4085, Adjusted R-squared: 0.3923
F-statistic: 25.16 on 7 and 255 DF, p-value: < 2.2e-16The summary() output provides information on regression coefficient estimates, standard errors, test statistics, p-values, (R^2), adjusted (R^2), and the F-statistic.
The model coefficients can be displayed in a more concise form using the tidy() function.
tidy(mod_full)# A tibble: 8 × 5 term estimate std.error statistic p.value <chr> <dbl> <dbl> <dbl> <dbl> 1 (Intercept) -98.4 75.2 -1.31 1.92e- 1 2 AtBat -2.02 0.588 -3.44 6.82e- 4 3 Hits 8.48 2.22 3.83 1.64e- 4 4 HmRun 1.47 5.83 0.252 8.02e- 1 5 Runs -1.19 2.72 -0.435 6.64e- 1 6 RBI 2.40 2.57 0.931 3.53e- 1 7 Walks 5.57 1.51 3.69 2.79e- 4 8 Years 31.5 4.76 6.63 2.00e-10
Information about the overall model can be obtained using the glance() function.
glance(mod_full)# A tibble: 1 × 12
r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0.409 0.392 352. 25.2 5.22e-26 7 -1911. 3840. 3872.
# ℹ 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>MultikolinearitasMulticollinearity
Prediktor berkorelasi dapat menaikkan ketidakpastian koefisien. Gunakan VIF sebagai diagnostik.Correlated predictors can inflate coefficient uncertainty. Use VIF as a diagnostic.
Sebelum melakukan seleksi model, perlu diperiksa apakah terdapat hubungan yang kuat antar peubah prediktor. Salah satu ukuran yang dapat digunakan adalah Variance Inflation Factor atau VIF.
vif(mod_full)AtBat Hits HmRun Runs RBI Walks Years 15.880036 21.207938 5.519571 10.255927 9.408265 2.285411 1.102732
Nilai VIF yang besar menunjukkan adanya hubungan linear yang kuat antara suatu prediktor dengan prediktor lainnya.
Before performing model selection, it is necessary to examine whether strong relationships exist among the predictor variables. One measure that can be used is the Variance Inflation Factor or VIF.
vif(mod_full)AtBat Hits HmRun Runs RBI Walks Years 15.880036 21.207938 5.519571 10.255927 9.408265 2.285411 1.102732
A large VIF value indicates a strong linear relationship between a predictor and the other predictors.
Inflasi variansVariance inflation
Ubah R² dari regresi bantu untuk mengeksplorasi VIF.Change auxiliary-regression R² to explore VIF.
Data ilustratif, bukan hasil estimasi R pada dataset praktikum.Illustrative data, not estimated R results for the practicum dataset.
Backward EliminationBackward Elimination
Backward elimination dimulai dari model penuh dan membuang prediktor sesuai kriteria.Backward elimination starts with the full model and removes predictors according to a criterion.
Backward elimination dimulai dari model yang memuat seluruh peubah prediktor. Selanjutnya, peubah yang memberikan kontribusi paling kecil terhadap model dikeluarkan secara bertahap.
Model awal yang digunakan adalah mod_full .
summary(mod_full)Call:
lm(formula = Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks +
Years, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-867.11 -197.03 -43.58 100.80 2194.60
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -98.4320 75.2485 -1.308 0.192020
AtBat -2.0211 0.5877 -3.439 0.000682 ***
Hits 8.4843 2.2172 3.827 0.000164 ***
HmRun 1.4661 5.8288 0.252 0.801610
Runs -1.1859 2.7243 -0.435 0.663716
RBI 2.3958 2.5747 0.931 0.352991
Walks 5.5736 1.5123 3.685 0.000279 ***
Years 31.5493 4.7594 6.629 2e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 351.7 on 255 degrees of freedom
Multiple R-squared: 0.4085, Adjusted R-squared: 0.3923
F-statistic: 25.16 on 7 and 255 DF, p-value: < 2.2e-16Untuk melihat pengaruh penghapusan satu peubah dari model dapat digunakan fungsi drop1() .
drop1(mod_full, test = "F")Single term deletions
Model:
Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks + Years
Df Sum of Sq RSS AIC F value Pr(>F)
<none> 31536217 3091.7
AtBat 1 1462404 32998620 3101.6 11.8249 0.0006825 ***
Hits 1 1810827 33347044 3104.3 14.6422 0.0001635 ***
HmRun 1 7824 31544041 3089.7 0.0633 0.8016096
Runs 1 23434 31559650 3089.8 0.1895 0.6637159
RBI 1 107079 31643296 3090.5 0.8658 0.3529906
Walks 1 1679758 33215975 3103.3 13.5824 0.0002789 ***
Years 1 5434238 36970455 3131.5 43.9409 2.005e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1Perhatikan p-value yang dihasilkan. Peubah dengan p-value terbesar dan tidak signifikan dapat dipertimbangkan untuk dikeluarkan dari model.
Misalkan berdasarkan hasil tersebut peubah yang akan dikeluarkan adalah HmRun .
mod_b1 <- update(
mod_full,
. ~ . - HmRun
)summary(mod_b1)Call:
lm(formula = Salary ~ AtBat + Hits + Runs + RBI + Walks + Years,
data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-864.39 -197.59 -45.32 99.57 2194.59
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -98.2498 75.1072 -1.308 0.192004
AtBat -2.0220 0.5867 -3.447 0.000663 ***
Hits 8.2605 2.0271 4.075 6.14e-05 ***
Runs -0.8778 2.4290 -0.361 0.718106
RBI 2.9285 1.4614 2.004 0.046129 *
Walks 5.4960 1.4778 3.719 0.000246 ***
Years 31.5869 4.7484 6.652 1.74e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 351 on 256 degrees of freedom
Multiple R-squared: 0.4084, Adjusted R-squared: 0.3945
F-statistic: 29.45 on 6 and 256 DF, p-value: < 2.2e-16Selanjutnya dilakukan pemeriksaan kembali.
drop1(mod_b1, test = "F")Single term deletions
Model:
Salary ~ AtBat + Hits + Runs + RBI + Walks + Years
Df Sum of Sq RSS AIC F value Pr(>F)
<none> 31544041 3089.7
AtBat 1 1463846 33007887 3099.7 11.8800 0.0006631 ***
Hits 1 2046225 33590266 3104.2 16.6064 6.141e-05 ***
Runs 1 16093 31560133 3087.8 0.1306 0.7181062
RBI 1 494823 32038864 3091.8 4.0158 0.0461292 *
Walks 1 1704215 33248256 3101.6 13.8308 0.0002458 ***
Years 1 5452566 36996606 3129.7 44.2510 1.740e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1Apabila masih terdapat peubah yang tidak memberikan kontribusi yang berarti terhadap model, peubah tersebut dapat kembali dikeluarkan.
Sebagai contoh, apabila pada tahap berikutnya peubah Runs dipilih untuk dikeluarkan, maka model dapat diperbarui sebagai berikut.
mod_b2 <- update(
mod_b1,
. ~ . - Runs
)summary(mod_b2)Call:
lm(formula = Salary ~ AtBat + Hits + RBI + Walks + Years, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-856.91 -197.02 -46.80 97.79 2192.63
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -96.4715 74.8190 -1.289 0.198419
AtBat -2.0302 0.5852 -3.469 0.000612 ***
Hits 7.9456 1.8272 4.348 1.98e-05 ***
RBI 2.8334 1.4351 1.974 0.049403 *
Walks 5.2499 1.3094 4.009 7.98e-05 ***
Years 31.9181 4.6512 6.862 5.05e-11 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 350.4 on 257 degrees of freedom
Multiple R-squared: 0.4081, Adjusted R-squared: 0.3966
F-statistic: 35.44 on 5 and 257 DF, p-value: < 2.2e-16drop1(mod_b2, test = "F")Single term deletions
Model:
Salary ~ AtBat + Hits + RBI + Walks + Years
Df Sum of Sq RSS AIC F value Pr(>F)
<none> 31560133 3087.8
AtBat 1 1477893 33038027 3097.9 12.0348 0.0006121 ***
Hits 1 2322082 33882216 3104.5 18.9091 1.978e-05 ***
RBI 1 478731 32038864 3089.8 3.8984 0.0494029 *
Walks 1 1974121 33534254 3101.8 16.0756 7.981e-05 ***
Years 1 5782866 37343000 3130.1 47.0910 5.050e-11 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1Proses dilanjutkan sampai tidak terdapat lagi peubah yang perlu dikeluarkan berdasarkan kriteria yang digunakan.
Backward Selection Menggunakan AIC
Selain menggunakan pengujian terhadap masing-masing peubah, backward selection juga dapat dilakukan berdasarkan Akaike Information Criterion atau AIC.
mod_backward <- step(
mod_full,
direction = "backward",
trace = TRUE
)Start: AIC=3091.65
Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks + Years
Df Sum of Sq RSS AIC
- HmRun 1 7824 31544041 3089.7
- Runs 1 23434 31559650 3089.8
- RBI 1 107079 31643296 3090.5
<none> 31536217 3091.7
- AtBat 1 1462404 32998620 3101.6
- Walks 1 1679758 33215975 3103.3
- Hits 1 1810827 33347044 3104.3
- Years 1 5434238 36970455 3131.5
Step: AIC=3089.72
Salary ~ AtBat + Hits + Runs + RBI + Walks + Years
Df Sum of Sq RSS AIC
- Runs 1 16093 31560133 3087.8
<none> 31544041 3089.7
- RBI 1 494823 32038864 3091.8
- AtBat 1 1463846 33007887 3099.7
- Walks 1 1704215 33248256 3101.6
- Hits 1 2046225 33590266 3104.2
- Years 1 5452566 36996606 3129.7
Step: AIC=3087.85
Salary ~ AtBat + Hits + RBI + Walks + Years
Df Sum of Sq RSS AIC
<none> 31560133 3087.8
- RBI 1 478731 32038864 3089.8
- AtBat 1 1477893 33038027 3097.9
- Walks 1 1974121 33534254 3101.8
- Hits 1 2322082 33882216 3104.5
- Years 1 5782866 37343000 3130.1summary(mod_backward)Call:
lm(formula = Salary ~ AtBat + Hits + RBI + Walks + Years, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-856.91 -197.02 -46.80 97.79 2192.63
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -96.4715 74.8190 -1.289 0.198419
AtBat -2.0302 0.5852 -3.469 0.000612 ***
Hits 7.9456 1.8272 4.348 1.98e-05 ***
RBI 2.8334 1.4351 1.974 0.049403 *
Walks 5.2499 1.3094 4.009 7.98e-05 ***
Years 31.9181 4.6512 6.862 5.05e-11 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 350.4 on 257 degrees of freedom
Multiple R-squared: 0.4081, Adjusted R-squared: 0.3966
F-statistic: 35.44 on 5 and 257 DF, p-value: < 2.2e-16Model yang dihasilkan dapat dilihat melalui formula berikut.
formula(mod_backward)Salary ~ AtBat + Hits + RBI + Walks + Years
Nilai AIC dari model akhir adalah
AIC(mod_backward)[1] 3836.213
Pada step() , pemilihan peubah dilakukan berdasarkan nilai AIC. Oleh karena itu, hasil yang diperoleh tidak harus sama dengan backward elimination yang dilakukan berdasarkan p-value.
Backward elimination starts with a model containing all predictor variables. Variables that contribute the least to the model are then removed gradually.
The initial model used is mod_full .
summary(mod_full)Call:
lm(formula = Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks +
Years, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-867.11 -197.03 -43.58 100.80 2194.60
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -98.4320 75.2485 -1.308 0.192020
AtBat -2.0211 0.5877 -3.439 0.000682 ***
Hits 8.4843 2.2172 3.827 0.000164 ***
HmRun 1.4661 5.8288 0.252 0.801610
Runs -1.1859 2.7243 -0.435 0.663716
RBI 2.3958 2.5747 0.931 0.352991
Walks 5.5736 1.5123 3.685 0.000279 ***
Years 31.5493 4.7594 6.629 2e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 351.7 on 255 degrees of freedom
Multiple R-squared: 0.4085, Adjusted R-squared: 0.3923
F-statistic: 25.16 on 7 and 255 DF, p-value: < 2.2e-16The effect of removing one variable from the model can be examined using the drop1() function.
drop1(mod_full, test = "F")Single term deletions
Model:
Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks + Years
Df Sum of Sq RSS AIC F value Pr(>F)
<none> 31536217 3091.7
AtBat 1 1462404 32998620 3101.6 11.8249 0.0006825 ***
Hits 1 1810827 33347044 3104.3 14.6422 0.0001635 ***
HmRun 1 7824 31544041 3089.7 0.0633 0.8016096
Runs 1 23434 31559650 3089.8 0.1895 0.6637159
RBI 1 107079 31643296 3090.5 0.8658 0.3529906
Walks 1 1679758 33215975 3103.3 13.5824 0.0002789 ***
Years 1 5434238 36970455 3131.5 43.9409 2.005e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1Observe the resulting p-values. The variable with the largest and non-significant p-value can be considered for removal from the model.
Suppose that based on the results, the variable to be removed is HmRun .
mod_b1 <- update(
mod_full,
. ~ . - HmRun
)summary(mod_b1)Call:
lm(formula = Salary ~ AtBat + Hits + Runs + RBI + Walks + Years,
data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-864.39 -197.59 -45.32 99.57 2194.59
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -98.2498 75.1072 -1.308 0.192004
AtBat -2.0220 0.5867 -3.447 0.000663 ***
Hits 8.2605 2.0271 4.075 6.14e-05 ***
Runs -0.8778 2.4290 -0.361 0.718106
RBI 2.9285 1.4614 2.004 0.046129 *
Walks 5.4960 1.4778 3.719 0.000246 ***
Years 31.5869 4.7484 6.652 1.74e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 351 on 256 degrees of freedom
Multiple R-squared: 0.4084, Adjusted R-squared: 0.3945
F-statistic: 29.45 on 6 and 256 DF, p-value: < 2.2e-16The model is then examined again.
drop1(mod_b1, test = "F")Single term deletions
Model:
Salary ~ AtBat + Hits + Runs + RBI + Walks + Years
Df Sum of Sq RSS AIC F value Pr(>F)
<none> 31544041 3089.7
AtBat 1 1463846 33007887 3099.7 11.8800 0.0006631 ***
Hits 1 2046225 33590266 3104.2 16.6064 6.141e-05 ***
Runs 1 16093 31560133 3087.8 0.1306 0.7181062
RBI 1 494823 32038864 3091.8 4.0158 0.0461292 *
Walks 1 1704215 33248256 3101.6 13.8308 0.0002458 ***
Years 1 5452566 36996606 3129.7 44.2510 1.740e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1If there are still variables that do not provide a meaningful contribution to the model, those variables can be removed again.
For example, if Runs is selected for removal in the next step, the model can be updated as follows.
mod_b2 <- update(
mod_b1,
. ~ . - Runs
)summary(mod_b2)Call:
lm(formula = Salary ~ AtBat + Hits + RBI + Walks + Years, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-856.91 -197.02 -46.80 97.79 2192.63
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -96.4715 74.8190 -1.289 0.198419
AtBat -2.0302 0.5852 -3.469 0.000612 ***
Hits 7.9456 1.8272 4.348 1.98e-05 ***
RBI 2.8334 1.4351 1.974 0.049403 *
Walks 5.2499 1.3094 4.009 7.98e-05 ***
Years 31.9181 4.6512 6.862 5.05e-11 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 350.4 on 257 degrees of freedom
Multiple R-squared: 0.4081, Adjusted R-squared: 0.3966
F-statistic: 35.44 on 5 and 257 DF, p-value: < 2.2e-16drop1(mod_b2, test = "F")Single term deletions
Model:
Salary ~ AtBat + Hits + RBI + Walks + Years
Df Sum of Sq RSS AIC F value Pr(>F)
<none> 31560133 3087.8
AtBat 1 1477893 33038027 3097.9 12.0348 0.0006121 ***
Hits 1 2322082 33882216 3104.5 18.9091 1.978e-05 ***
RBI 1 478731 32038864 3089.8 3.8984 0.0494029 *
Walks 1 1974121 33534254 3101.8 16.0756 7.981e-05 ***
Years 1 5782866 37343000 3130.1 47.0910 5.050e-11 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1The process is continued until there are no additional variables that need to be removed based on the criterion being used.
Backward Selection Using AIC
In addition to testing each variable, backward selection can also be performed based on the Akaike Information Criterion or AIC.
mod_backward <- step(
mod_full,
direction = "backward",
trace = TRUE
)Start: AIC=3091.65
Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks + Years
Df Sum of Sq RSS AIC
- HmRun 1 7824 31544041 3089.7
- Runs 1 23434 31559650 3089.8
- RBI 1 107079 31643296 3090.5
<none> 31536217 3091.7
- AtBat 1 1462404 32998620 3101.6
- Walks 1 1679758 33215975 3103.3
- Hits 1 1810827 33347044 3104.3
- Years 1 5434238 36970455 3131.5
Step: AIC=3089.72
Salary ~ AtBat + Hits + Runs + RBI + Walks + Years
Df Sum of Sq RSS AIC
- Runs 1 16093 31560133 3087.8
<none> 31544041 3089.7
- RBI 1 494823 32038864 3091.8
- AtBat 1 1463846 33007887 3099.7
- Walks 1 1704215 33248256 3101.6
- Hits 1 2046225 33590266 3104.2
- Years 1 5452566 36996606 3129.7
Step: AIC=3087.85
Salary ~ AtBat + Hits + RBI + Walks + Years
Df Sum of Sq RSS AIC
<none> 31560133 3087.8
- RBI 1 478731 32038864 3089.8
- AtBat 1 1477893 33038027 3097.9
- Walks 1 1974121 33534254 3101.8
- Hits 1 2322082 33882216 3104.5
- Years 1 5782866 37343000 3130.1summary(mod_backward)Call:
lm(formula = Salary ~ AtBat + Hits + RBI + Walks + Years, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-856.91 -197.02 -46.80 97.79 2192.63
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -96.4715 74.8190 -1.289 0.198419
AtBat -2.0302 0.5852 -3.469 0.000612 ***
Hits 7.9456 1.8272 4.348 1.98e-05 ***
RBI 2.8334 1.4351 1.974 0.049403 *
Walks 5.2499 1.3094 4.009 7.98e-05 ***
Years 31.9181 4.6512 6.862 5.05e-11 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 350.4 on 257 degrees of freedom
Multiple R-squared: 0.4081, Adjusted R-squared: 0.3966
F-statistic: 35.44 on 5 and 257 DF, p-value: < 2.2e-16The resulting model can be viewed through the following formula.
formula(mod_backward)Salary ~ AtBat + Hits + RBI + Walks + Years
The AIC value of the final model is
AIC(mod_backward)[1] 3836.213
In step() , variable selection is performed based on the AIC value. Therefore, the resulting model does not necessarily have to be the same as the backward elimination model obtained using p-values.
Forward SelectionForward Selection
Forward selection dimulai dari model kecil lalu menambahkan prediktor.Forward selection starts with a small model and adds predictors.
Forward selection bekerja dengan arah yang berlawanan dengan backward elimination. Prosedur dimulai dari model tanpa prediktor, kemudian prediktor ditambahkan satu per satu.
Model tanpa prediktor disebut sebagai null model.
mod_null <- lm(
Salary ~ 1,
data = hitters_sub
)summary(mod_null)Call:
lm(formula = Salary ~ 1, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-468.4 -345.9 -110.9 214.1 1924.1
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 535.93 27.82 19.27 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 451.1 on 262 degrees of freedomModel dengan seluruh prediktor digunakan sebagai batas atas dari peubah yang dapat dipilih.
mod_fullCall:
lm(formula = Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks +
Years, data = hitters_sub)
Coefficients:
(Intercept) AtBat Hits HmRun Runs RBI
-98.432 -2.021 8.484 1.466 -1.186 2.396
Walks Years
5.574 31.549Forward selection berdasarkan AIC dapat dilakukan menggunakan fungsi step() .
mod_forward <- step(
mod_null,
scope = list(
lower = mod_null,
upper = mod_full
),
direction = "forward",
trace = TRUE
)Start: AIC=3215.77
Salary ~ 1
Df Sum of Sq RSS AIC
+ RBI 1 10771083 42548030 3158.4
+ Walks 1 10504833 42814280 3160.1
+ Hits 1 10260491 43058621 3161.6
+ Runs 1 9399158 43919955 3166.8
+ Years 1 8559105 44760007 3171.7
+ AtBat 1 8309469 45009644 3173.2
+ HmRun 1 6273967 47045145 3184.8
<none> 53319113 3215.8
Step: AIC=3158.42
Salary ~ RBI
Df Sum of Sq RSS AIC
+ Years 1 6357053 36190977 3117.9
+ Walks 1 2786136 39761894 3142.6
+ Hits 1 1001317 41546712 3154.2
+ Runs 1 661248 41886782 3156.3
<none> 42548030 3158.4
+ HmRun 1 284863 42263166 3158.7
+ AtBat 1 199200 42348830 3159.2
Step: AIC=3117.86
Salary ~ RBI + Years
Df Sum of Sq RSS AIC
+ Walks 1 2204615 33986362 3103.3
+ Hits 1 1847686 34343291 3106.1
+ Runs 1 1670312 34520664 3107.4
+ AtBat 1 698958 35492019 3114.7
+ HmRun 1 302543 35888434 3117.7
<none> 36190977 3117.9
Step: AIC=3103.33
Salary ~ RBI + Years + Walks
Df Sum of Sq RSS AIC
+ Hits 1 948335 33038027 3097.9
+ Runs 1 378729 33607633 3102.4
<none> 33986362 3103.3
+ HmRun 1 162797 33823565 3104.1
+ AtBat 1 104146 33882216 3104.5
Step: AIC=3097.89
Salary ~ RBI + Years + Walks + Hits
Df Sum of Sq RSS AIC
+ AtBat 1 1477893 31560133 3087.8
<none> 33038027 3097.9
+ Runs 1 30140 33007887 3099.7
+ HmRun 1 63 33037964 3099.9
Step: AIC=3087.85
Salary ~ RBI + Years + Walks + Hits + AtBat
Df Sum of Sq RSS AIC
<none> 31560133 3087.8
+ Runs 1 16092.7 31544041 3089.7
+ HmRun 1 483.3 31559650 3089.8summary(mod_forward)Call:
lm(formula = Salary ~ RBI + Years + Walks + Hits + AtBat, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-856.91 -197.02 -46.80 97.79 2192.63
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -96.4715 74.8190 -1.289 0.198419
RBI 2.8334 1.4351 1.974 0.049403 *
Years 31.9181 4.6512 6.862 5.05e-11 ***
Walks 5.2499 1.3094 4.009 7.98e-05 ***
Hits 7.9456 1.8272 4.348 1.98e-05 ***
AtBat -2.0302 0.5852 -3.469 0.000612 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 350.4 on 257 degrees of freedom
Multiple R-squared: 0.4081, Adjusted R-squared: 0.3966
F-statistic: 35.44 on 5 and 257 DF, p-value: < 2.2e-16Peubah yang terpilih pada model akhir dapat dilihat dari formula model.
formula(mod_forward)Salary ~ RBI + Years + Walks + Hits + AtBat
AIC(mod_forward)[1] 3836.213
Forward selection works in the opposite direction to backward elimination. The procedure starts with a model without predictors, and predictors are then added one at a time.
A model without predictors is referred to as a null model.
mod_null <- lm(
Salary ~ 1,
data = hitters_sub
)summary(mod_null)Call:
lm(formula = Salary ~ 1, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-468.4 -345.9 -110.9 214.1 1924.1
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 535.93 27.82 19.27 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 451.1 on 262 degrees of freedomThe model containing all predictors is used as the upper limit of the variables that can be selected.
mod_fullCall:
lm(formula = Salary ~ AtBat + Hits + HmRun + Runs + RBI + Walks +
Years, data = hitters_sub)
Coefficients:
(Intercept) AtBat Hits HmRun Runs RBI
-98.432 -2.021 8.484 1.466 -1.186 2.396
Walks Years
5.574 31.549Forward selection based on AIC can be performed using the step() function.
mod_forward <- step(
mod_null,
scope = list(
lower = mod_null,
upper = mod_full
),
direction = "forward",
trace = TRUE
)Start: AIC=3215.77
Salary ~ 1
Df Sum of Sq RSS AIC
+ RBI 1 10771083 42548030 3158.4
+ Walks 1 10504833 42814280 3160.1
+ Hits 1 10260491 43058621 3161.6
+ Runs 1 9399158 43919955 3166.8
+ Years 1 8559105 44760007 3171.7
+ AtBat 1 8309469 45009644 3173.2
+ HmRun 1 6273967 47045145 3184.8
<none> 53319113 3215.8
Step: AIC=3158.42
Salary ~ RBI
Df Sum of Sq RSS AIC
+ Years 1 6357053 36190977 3117.9
+ Walks 1 2786136 39761894 3142.6
+ Hits 1 1001317 41546712 3154.2
+ Runs 1 661248 41886782 3156.3
<none> 42548030 3158.4
+ HmRun 1 284863 42263166 3158.7
+ AtBat 1 199200 42348830 3159.2
Step: AIC=3117.86
Salary ~ RBI + Years
Df Sum of Sq RSS AIC
+ Walks 1 2204615 33986362 3103.3
+ Hits 1 1847686 34343291 3106.1
+ Runs 1 1670312 34520664 3107.4
+ AtBat 1 698958 35492019 3114.7
+ HmRun 1 302543 35888434 3117.7
<none> 36190977 3117.9
Step: AIC=3103.33
Salary ~ RBI + Years + Walks
Df Sum of Sq RSS AIC
+ Hits 1 948335 33038027 3097.9
+ Runs 1 378729 33607633 3102.4
<none> 33986362 3103.3
+ HmRun 1 162797 33823565 3104.1
+ AtBat 1 104146 33882216 3104.5
Step: AIC=3097.89
Salary ~ RBI + Years + Walks + Hits
Df Sum of Sq RSS AIC
+ AtBat 1 1477893 31560133 3087.8
<none> 33038027 3097.9
+ Runs 1 30140 33007887 3099.7
+ HmRun 1 63 33037964 3099.9
Step: AIC=3087.85
Salary ~ RBI + Years + Walks + Hits + AtBat
Df Sum of Sq RSS AIC
<none> 31560133 3087.8
+ Runs 1 16092.7 31544041 3089.7
+ HmRun 1 483.3 31559650 3089.8summary(mod_forward)Call:
lm(formula = Salary ~ RBI + Years + Walks + Hits + AtBat, data = hitters_sub)
Residuals:
Min 1Q Median 3Q Max
-856.91 -197.02 -46.80 97.79 2192.63
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -96.4715 74.8190 -1.289 0.198419
RBI 2.8334 1.4351 1.974 0.049403 *
Years 31.9181 4.6512 6.862 5.05e-11 ***
Walks 5.2499 1.3094 4.009 7.98e-05 ***
Hits 7.9456 1.8272 4.348 1.98e-05 ***
AtBat -2.0302 0.5852 -3.469 0.000612 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 350.4 on 257 degrees of freedom
Multiple R-squared: 0.4081, Adjusted R-squared: 0.3966
F-statistic: 35.44 on 5 and 257 DF, p-value: < 2.2e-16The variables selected in the final model can be viewed from the model formula.
formula(mod_forward)Salary ~ RBI + Years + Walks + Hits + AtBat
AIC(mod_forward)[1] 3836.213
Forward dan Backward Stepwise SelectionForward and Backward Stepwise Selection
Bandingkan pencarian subset menggunakan kriteria yang memperhitungkan kompleksitas, bukan hanya kecocokan model.Compare subset searches using criteria that account for complexity, not fit alone.
Forward dan backward selection juga dapat dilakukan menggunakan fungsi regsubsets() dari package
leaps .
Berbeda dengan bagian sebelumnya, seluruh prediktor pada data Hitters akan digunakan pada bagian ini.
Forward Selection
reg_forward <- regsubsets(
Salary ~ .,
data = hitters,
method = "forward",
nvmax = 19
)summary_forward <- summary(reg_forward)Hasil pemilihan peubah pada setiap ukuran model dapat dilihat sebagai berikut.
summary_forward$which(Intercept) AtBat Hits HmRun Runs RBI Walks Years CAtBat CHits CHmRun 1 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 2 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 3 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 4 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 5 TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 6 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 7 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 8 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 9 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 10 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 11 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 12 TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 13 TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 14 TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 15 TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE FALSE 16 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE 17 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE 18 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 19 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE CRuns CRBI CWalks LeagueN DivisionW PutOuts Assists Errors NewLeagueN 1 FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 2 FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 3 FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE 4 FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE 5 FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE 6 FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE 7 FALSE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 8 TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 9 TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 10 TRUE TRUE TRUE FALSE TRUE TRUE TRUE FALSE FALSE 11 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE 12 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE 13 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 14 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 15 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 16 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 17 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 18 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 19 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Beberapa kriteria dapat digunakan untuk menentukan jumlah prediktor pada model.
forward_metric <- tibble(
nvar = 1:length(summary_forward$bic),
rss = summary_forward$rss,
adjr2 = summary_forward$adjr2,
cp = summary_forward$cp,
bic = summary_forward$bic
)forward_metric# A tibble: 19 × 5
nvar rss adjr2 cp bic
<int> <dbl> <dbl> <dbl> <dbl>
1 1 36179679. 0.319 104. -90.8
2 2 30646560. 0.421 50.7 -129.
3 3 29249297. 0.445 38.7 -136.
4 4 27970852. 0.467 27.9 -142.
5 5 27149899. 0.481 21.6 -144.
6 6 26194904. 0.497 14.0 -148.
7 7 25954217. 0.500 13.6 -145.
8 8 25159234. 0.513 7.62 -147.
9 9 24814051. 0.518 6.16 -145.
10 10 24500402. 0.522 5.01 -143.
11 11 24387345. 0.523 5.87 -139.
12 12 24333232. 0.522 7.33 -134.
13 13 24289148. 0.521 8.89 -129.
14 14 24248660. 0.520 10.5 -124.
15 15 24235177. 0.518 12.3 -118.
16 16 24219377. 0.516 14.2 -113.
17 17 24209447. 0.514 16.1 -107.
18 18 24201837. 0.513 18.0 -102.
19 19 24200700. 0.511 20.0 -96.3Menggunakan BIC
Model dengan nilai BIC terkecil dapat dicari menggunakan
which.min(summary_forward$bic)[1] 6
Visualisasi nilai BIC untuk setiap jumlah prediktor.
forward_metric %>%
ggplot(aes(x = nvar, y = bic)) +
geom_line() +
geom_point() +
labs(
x = "Jumlah Prediktor",
y = "BIC"
) +
theme_bw()Koefisien dari model dengan nilai BIC terkecil adalah
best_forward <- which.min(summary_forward$bic)coef(
reg_forward,
id = best_forward
) (Intercept) AtBat Hits Walks CRBI DivisionW
91.5117981 -1.8685892 7.6043976 3.6976468 0.6430169 -122.9515338
PutOuts
0.2643076Backward Selection
reg_backward <- regsubsets(
Salary ~ .,
data = hitters,
method = "backward",
nvmax = 19
)summary_backward <- summary(reg_backward)summary_backward$which(Intercept) AtBat Hits HmRun Runs RBI Walks Years CAtBat CHits CHmRun 1 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 2 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 3 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 4 TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 5 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 6 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 7 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 8 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 9 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 10 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 11 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 12 TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 13 TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 14 TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 15 TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE FALSE 16 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE 17 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE 18 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 19 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE CRuns CRBI CWalks LeagueN DivisionW PutOuts Assists Errors NewLeagueN 1 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 2 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 3 TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE 4 TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE 5 TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE 6 TRUE FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE 7 TRUE FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 8 TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 9 TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 10 TRUE TRUE TRUE FALSE TRUE TRUE TRUE FALSE FALSE 11 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE 12 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE 13 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 14 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 15 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 16 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 17 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 18 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 19 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Kriteria pemilihan model disimpan dalam tabel berikut.
backward_metric <- tibble(
nvar = 1:length(summary_backward$bic),
rss = summary_backward$rss,
adjr2 = summary_backward$adjr2,
cp = summary_backward$cp,
bic = summary_backward$bic
)backward_metric# A tibble: 19 × 5
nvar rss adjr2 cp bic
<int> <dbl> <dbl> <dbl> <dbl>
1 1 36437951. 0.314 107. -89.0
2 2 31203460. 0.410 56.3 -124.
3 3 29407297. 0.442 40.3 -134.
4 4 28450807. 0.458 32.7 -137.
5 5 27509524. 0.474 25.2 -141.
6 6 26674092. 0.488 18.8 -143.
7 7 25933487. 0.500 13.4 -145.
8 8 25159234. 0.513 7.62 -147.
9 9 24814051. 0.518 6.16 -145.
10 10 24500402. 0.522 5.01 -143.
11 11 24387345. 0.523 5.87 -139.
12 12 24333232. 0.522 7.33 -134.
13 13 24289148. 0.521 8.89 -129.
14 14 24248660. 0.520 10.5 -124.
15 15 24235177. 0.518 12.3 -118.
16 16 24219377. 0.516 14.2 -113.
17 17 24209447. 0.514 16.1 -107.
18 18 24201837. 0.513 18.0 -102.
19 19 24200700. 0.511 20.0 -96.3Model dengan nilai BIC terkecil adalah
which.min(summary_backward$bic)[1] 8
Visualisasi nilai BIC.
backward_metric %>%
ggplot(aes(x = nvar, y = bic)) +
geom_line() +
geom_point() +
labs(
x = "Jumlah Prediktor",
y = "BIC"
) +
theme_bw()Koefisien dari model yang memiliki BIC terkecil adalah
best_backward <- which.min(summary_backward$bic)coef(
reg_backward,
id = best_backward
) (Intercept) AtBat Hits Walks CRuns CRBI
117.1520434 -2.0339209 6.8549136 6.4406642 0.7045391 0.5273238
CWalks DivisionW PutOuts
-0.8066062 -123.7798366 0.2753892Forward and backward selection can also be performed using the regsubsets() function from the
leaps package.
Unlike the previous section, all predictors in the Hitters data will be used in this section.
Forward Selection
reg_forward <- regsubsets(
Salary ~ .,
data = hitters,
method = "forward",
nvmax = 19
)summary_forward <- summary(reg_forward)The selected variables for each model size can be viewed as follows.
summary_forward$which(Intercept) AtBat Hits HmRun Runs RBI Walks Years CAtBat CHits CHmRun 1 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 2 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 3 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 4 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 5 TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 6 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 7 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 8 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 9 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 10 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 11 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 12 TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 13 TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 14 TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 15 TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE FALSE 16 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE 17 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE 18 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 19 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE CRuns CRBI CWalks LeagueN DivisionW PutOuts Assists Errors NewLeagueN 1 FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 2 FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 3 FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE 4 FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE 5 FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE 6 FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE 7 FALSE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 8 TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 9 TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 10 TRUE TRUE TRUE FALSE TRUE TRUE TRUE FALSE FALSE 11 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE 12 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE 13 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 14 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 15 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 16 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 17 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 18 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 19 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Several criteria can be used to determine the number of predictors in the model.
forward_metric <- tibble(
nvar = 1:length(summary_forward$bic),
rss = summary_forward$rss,
adjr2 = summary_forward$adjr2,
cp = summary_forward$cp,
bic = summary_forward$bic
)forward_metric# A tibble: 19 × 5
nvar rss adjr2 cp bic
<int> <dbl> <dbl> <dbl> <dbl>
1 1 36179679. 0.319 104. -90.8
2 2 30646560. 0.421 50.7 -129.
3 3 29249297. 0.445 38.7 -136.
4 4 27970852. 0.467 27.9 -142.
5 5 27149899. 0.481 21.6 -144.
6 6 26194904. 0.497 14.0 -148.
7 7 25954217. 0.500 13.6 -145.
8 8 25159234. 0.513 7.62 -147.
9 9 24814051. 0.518 6.16 -145.
10 10 24500402. 0.522 5.01 -143.
11 11 24387345. 0.523 5.87 -139.
12 12 24333232. 0.522 7.33 -134.
13 13 24289148. 0.521 8.89 -129.
14 14 24248660. 0.520 10.5 -124.
15 15 24235177. 0.518 12.3 -118.
16 16 24219377. 0.516 14.2 -113.
17 17 24209447. 0.514 16.1 -107.
18 18 24201837. 0.513 18.0 -102.
19 19 24200700. 0.511 20.0 -96.3Using BIC
The model with the smallest BIC value can be identified using
which.min(summary_forward$bic)[1] 6
Visualization of the BIC value for each number of predictors.
forward_metric %>%
ggplot(aes(x = nvar, y = bic)) +
geom_line() +
geom_point() +
labs(
x = "Number of Predictors",
y = "BIC"
) +
theme_bw()The coefficients of the model with the smallest BIC value are
best_forward <- which.min(summary_forward$bic)coef(
reg_forward,
id = best_forward
) (Intercept) AtBat Hits Walks CRBI DivisionW
91.5117981 -1.8685892 7.6043976 3.6976468 0.6430169 -122.9515338
PutOuts
0.2643076Backward Selection
reg_backward <- regsubsets(
Salary ~ .,
data = hitters,
method = "backward",
nvmax = 19
)summary_backward <- summary(reg_backward)summary_backward$which(Intercept) AtBat Hits HmRun Runs RBI Walks Years CAtBat CHits CHmRun 1 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 2 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 3 TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 4 TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 5 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 6 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 7 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 8 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 9 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 10 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 11 TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE 12 TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 13 TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 14 TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE 15 TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE FALSE 16 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE 17 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE 18 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 19 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE CRuns CRBI CWalks LeagueN DivisionW PutOuts Assists Errors NewLeagueN 1 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 2 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 3 TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE 4 TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE 5 TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE 6 TRUE FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE 7 TRUE FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 8 TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 9 TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 10 TRUE TRUE TRUE FALSE TRUE TRUE TRUE FALSE FALSE 11 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE 12 TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE 13 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 14 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 15 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 16 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE 17 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 18 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 19 TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
The model selection criteria are stored in the following table.
backward_metric <- tibble(
nvar = 1:length(summary_backward$bic),
rss = summary_backward$rss,
adjr2 = summary_backward$adjr2,
cp = summary_backward$cp,
bic = summary_backward$bic
)backward_metric# A tibble: 19 × 5
nvar rss adjr2 cp bic
<int> <dbl> <dbl> <dbl> <dbl>
1 1 36437951. 0.314 107. -89.0
2 2 31203460. 0.410 56.3 -124.
3 3 29407297. 0.442 40.3 -134.
4 4 28450807. 0.458 32.7 -137.
5 5 27509524. 0.474 25.2 -141.
6 6 26674092. 0.488 18.8 -143.
7 7 25933487. 0.500 13.4 -145.
8 8 25159234. 0.513 7.62 -147.
9 9 24814051. 0.518 6.16 -145.
10 10 24500402. 0.522 5.01 -143.
11 11 24387345. 0.523 5.87 -139.
12 12 24333232. 0.522 7.33 -134.
13 13 24289148. 0.521 8.89 -129.
14 14 24248660. 0.520 10.5 -124.
15 15 24235177. 0.518 12.3 -118.
16 16 24219377. 0.516 14.2 -113.
17 17 24209447. 0.514 16.1 -107.
18 18 24201837. 0.513 18.0 -102.
19 19 24200700. 0.511 20.0 -96.3The model with the smallest BIC value is
which.min(summary_backward$bic)[1] 8
Visualization of the BIC values.
backward_metric %>%
ggplot(aes(x = nvar, y = bic)) +
geom_line() +
geom_point() +
labs(
x = "Number of Predictors",
y = "BIC"
) +
theme_bw()The coefficients of the model with the smallest BIC value are
best_backward <- which.min(summary_backward$bic)coef(
reg_backward,
id = best_backward
) (Intercept) AtBat Hits Walks CRuns CRBI
117.1520434 -2.0339209 6.8549136 6.4406642 0.7045391 0.5273238
CWalks DivisionW PutOuts
-0.8066062 -123.7798366 0.2753892AIC dan BICAIC and BIC
Ubah jumlah parameter k. Ilustrasi n = 263, RSS = 1000; intersep dihitung dalam k.Change the number of parameters k. Illustration with n = 263 and RSS = 1000; k includes the intercept.
Data ilustratif, bukan hasil estimasi R pada dataset praktikum.Illustrative data, not estimated R results for the practicum dataset.
Perbandingan Forward dan Backward SelectionComparison of Forward and Backward Selection
Forward dan backward tidak harus memilih subset yang sama. Bandingkan formula dan ukuran evaluasi.Forward and backward selection need not choose the same subset. Compare formulas and evaluation measures.
Jumlah peubah yang dipilih berdasarkan BIC dari kedua metode dapat dibandingkan.
best_forward[1] 6
best_backward[1] 8
Peubah pada masing-masing model adalah
coef(
reg_forward,
id = best_forward
) (Intercept) AtBat Hits Walks CRBI DivisionW
91.5117981 -1.8685892 7.6043976 3.6976468 0.6430169 -122.9515338
PutOuts
0.2643076coef(
reg_backward,
id = best_backward
) (Intercept) AtBat Hits Walks CRuns CRBI
117.1520434 -2.0339209 6.8549136 6.4406642 0.7045391 0.5273238
CWalks DivisionW PutOuts
-0.8066062 -123.7798366 0.2753892Hasil forward selection dan backward selection tidak harus menghasilkan kombinasi peubah yang sama. Hal ini disebabkan kedua metode melakukan pencarian model dari arah yang berbeda.
Forward selection dimulai dari model tanpa prediktor dan menambahkan peubah secara bertahap, sedangkan backward selection dimulai dari model penuh dan mengeluarkan peubah secara bertahap.
The number of variables selected based on BIC from both methods can be compared.
best_forward[1] 6
best_backward[1] 8
The variables in each model are
coef(
reg_forward,
id = best_forward
) (Intercept) AtBat Hits Walks CRBI DivisionW
91.5117981 -1.8685892 7.6043976 3.6976468 0.6430169 -122.9515338
PutOuts
0.2643076coef(
reg_backward,
id = best_backward
) (Intercept) AtBat Hits Walks CRuns CRBI
117.1520434 -2.0339209 6.8549136 6.4406642 0.7045391 0.5273238
CWalks DivisionW PutOuts
-0.8066062 -123.7798366 0.2753892Forward selection and backward selection do not necessarily produce the same combination of variables. This is because the two methods search for the model from different directions.
Forward selection starts with a model without predictors and gradually adds variables, whereas backward selection starts with the full model and gradually removes variables.
Pemeriksaan Asumsi ModelChecking Model Assumptions
Diagnostik residual menilai kesesuaian model linear dan observasi berpengaruh.Residual diagnostics assess linear model adequacy and influential observations.
Setelah diperoleh model, selanjutnya dilakukan pemeriksaan terhadap residual model.
Pada bagian ini digunakan model hasil backward selection berdasarkan AIC.
par(mfrow = c(2, 2))
plot(mod_backward)par(mfrow = c(1, 1))Normalitas Residual
Normalitas residual dapat dilihat menggunakan Q-Q plot dan diuji menggunakan Shapiro-Wilk.
shapiro.test(residuals(mod_backward))Shapiro-Wilk normality test data: residuals(mod_backward) W = 0.88439, p-value = 2.978e-13
Untuk ukuran sampel yang cukup besar, hasil pengujian perlu dilihat bersama dengan pola pada Q-Q plot dan tidak hanya berdasarkan p-value.
Homoskedastisitas
Pola residual terhadap fitted value dapat digunakan untuk melihat apakah ragam residual relatif konstan.
plot(
fitted(mod_backward),
residuals(mod_backward),
xlab = "Fitted Value",
ylab = "Residual"
)abline(h = 0, lty = 2)Observasi Berpengaruh
Cook’s distance dapat digunakan untuk melihat observasi yang memiliki pengaruh besar terhadap hasil pemodelan.
cook <- cooks.distance(mod_backward)plot(
cook,
type = "h",
ylab = "Cook's Distance"
)abline(
h = 4 / nrow(hitters_sub),
lty = 2
)Observasi dengan Cook’s distance terbesar dapat dilihat menggunakan
order(
cook,
decreasing = TRUE
)[1:5][1] 173 62 127 77 230
After obtaining the model, the model residuals are examined.
In this section, the model obtained from backward selection based on AIC is used.
par(mfrow = c(2, 2))
plot(mod_backward)par(mfrow = c(1, 1))Normality of Residuals
Residual normality can be examined using a Q-Q plot and tested using the Shapiro-Wilk test.
shapiro.test(residuals(mod_backward))Shapiro-Wilk normality test data: residuals(mod_backward) W = 0.88439, p-value = 2.978e-13
For a sufficiently large sample size, the test results should be considered together with the pattern shown in the Q-Q plot and not solely based on the p-value.
Homoscedasticity
The pattern of residuals against fitted values can be used to examine whether the residual variance is relatively constant.
plot(
fitted(mod_backward),
residuals(mod_backward),
xlab = "Fitted Value",
ylab = "Residual"
)abline(h = 0, lty = 2)Influential Observations
Cook’s distance can be used to identify observations that have a large influence on the modeling results.
cook <- cooks.distance(mod_backward)plot(
cook,
type = "h",
ylab = "Cook's Distance"
)abline(
h = 4 / nrow(hitters_sub),
lty = 2
)The observations with the largest Cook’s distance values can be identified using
order(
cook,
decreasing = TRUE
)[1:5][1] 173 62 127 77 230
PrediksiPrediction
Gunakan model terpilih untuk menghitung prediksi pada nilai prediktor baru.Use the selected model to predict at new predictor values.
Model regresi yang telah diperoleh dapat digunakan untuk menghasilkan nilai prediksi.
pred <- predict(
mod_backward,
newdata = hitters_sub
)Nilai aktual dan prediksi dapat dibandingkan sebagai berikut.
hasil_prediksi <- tibble(
aktual = hitters_sub$Salary,
prediksi = pred
)
head(hasil_prediksi)# A tibble: 6 × 2 aktual prediksi <dbl> <dbl> 1 475 667. 2 480 663. 3 500 783. 4 91.5 283. 5 750 720. 6 70 18.7
Visualisasi nilai aktual dan prediksi.
hasil_prediksi %>%
ggplot(aes(x = aktual, y = prediksi)) +
geom_point(alpha = 0.6) +
geom_abline(
intercept = 0,
slope = 1,
linetype = 2
) +
labs(
x = "Salary Aktual",
y = "Salary Prediksi"
) +
theme_bw()The fitted regression model can be used to generate predicted values.
pred <- predict(
mod_backward,
newdata = hitters_sub
)The actual and predicted values can be compared as follows.
hasil_prediksi <- tibble(
aktual = hitters_sub$Salary,
prediksi = pred
)
head(hasil_prediksi)# A tibble: 6 × 2 aktual prediksi <dbl> <dbl> 1 475 667. 2 480 663. 3 500 783. 4 91.5 283. 5 750 720. 6 70 18.7
Visualization of the actual and predicted values.
hasil_prediksi %>%
ggplot(aes(x = aktual, y = prediksi)) +
geom_point(alpha = 0.6) +
geom_abline(
intercept = 0,
slope = 1,
linetype = 2
) +
labs(
x = "Actual Salary",
y = "Predicted Salary"
) +
theme_bw()Evaluasi ModelModel Evaluation
Evaluasi kecocokan dan kesalahan prediksi dengan memahami data yang digunakan dalam evaluasi.Evaluate fit and prediction error while identifying which data are used for assessment.
Root Mean Squared Error dapat dihitung menggunakan
rmse <- sqrt(
mean(
(hitters_sub$Salary - pred)^2
)
)rmse[1] 346.4109
Nilai (R^2) model dapat diperoleh dari
summary(mod_backward)$r.squared[1] 0.4080897
Sedangkan adjusted (R^2) adalah
summary(mod_backward)$adj.r.squared[1] 0.3965739
Root Mean Squared Error can be calculated using
rmse <- sqrt(
mean(
(hitters_sub$Salary - pred)^2
)
)rmse[1] 346.4109
The (R^2) value of the model can be obtained from
summary(mod_backward)$r.squared[1] 0.4080897
The adjusted (R^2) is
summary(mod_backward)$adj.r.squared[1] 0.3965739
LatihanExercise
Terapkan kembali prosedur regresi dan seleksi model pada latihan yang disediakan.Apply the regression and model selection procedures to the exercise.
Gunakan seluruh peubah pada data Hitters untuk membentuk model regresi dengan Salary sebagai peubah respon.
1. Bentuk model regresi linear menggunakan seluruh prediktor. 2. Lakukan backward selection. 3. Lakukan forward selection. 4. Tentukan model berdasarkan BIC. 5. Bandingkan peubah yang terpilih dari forward dan backward selection. 6. Lakukan pemeriksaan diagnostik terhadap model yang diperoleh. 7. Berikan interpretasi terhadap hasil analisis.
Use all variables in the Hitters data to fit a regression model with Salary as the response variable.
1. Fit a linear regression model using all predictors. 2. Perform backward selection. 3. Perform forward selection. 4. Determine the model based on BIC. 5. Compare the variables selected by forward and backward selection. 6. Perform diagnostic checks on the resulting model. 7. Provide an interpretation of the analysis results.