U.UNIQUE / PRACTICUM NOTESSTATISTICS & DATA SCIENCE
IPB UNIVERSITYPRACTICUM 04

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.

R
# install.packages("ISLR2")
# install.packages("tidyverse")
# install.packages("broom")
# install.packages("car")
# install.packages("leaps")

Please install the packages if they have not been installed.

R
# install.packages("ISLR2")
# install.packages("tidyverse")
# install.packages("broom")
# install.packages("car")
# install.packages("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.

R
data("Hitters")

Melihat dimensi data.

R
dim(Hitters)
[1] 322  20

Melihat nama peubah yang tersedia.

R
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.

R
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         A

Melihat struktur data.

R
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 .

R
sum(is.na(Hitters$Salary))
[1] 59

Observasi yang memiliki nilai hilang akan dikeluarkan terlebih dahulu.

R
hitters <- Hitters %>%
  drop_na()

Periksa kembali ukuran data dan jumlah missing value.

R
dim(hitters)
[1] 263  20

Untuk mempermudah ilustrasi, pada bagian awal hanya digunakan beberapa peubah prediktor.

R
hitters_sub <- hitters %>%
  select(
    Salary,
    AtBat,
    Hits,
    HmRun,
    Runs,
    RBI,
    Walks,
    Years
  )

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.

R
data("Hitters")

View the dimensions of the data.

R
dim(Hitters)
[1] 322  20

View the available variable names.

R
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.

R
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         A

View the structure of the data.

R
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.

R
sum(is.na(Hitters$Salary))
[1] 59

Observations containing missing values will first be removed.

R
hitters <- Hitters %>%
  drop_na()

Check the size of the data and the number of missing values again.

R
dim(hitters)
[1] 263  20

To simplify the illustration, only several predictor variables are used in the initial section.

R
hitters_sub <- hitters %>%
  select(
    Salary,
    AtBat,
    Hits,
    HmRun,
    Runs,
    RBI,
    Walks,
    Years
  )

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.

R
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.000

Selanjutnya dilihat hubungan antar peubah numerik menggunakan korelasi.

R
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.

R
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'
R output figure

Before fitting the regression model, a summary of each variable is first examined.

R
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.000

Next, the relationships among numerical variables are examined using correlations.

R
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.

R
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'
R output figure

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 .

R
mod_full <- lm(
  Salary ~ AtBat + Hits + HmRun + Runs +
    RBI + Walks + Years,
  data = hitters_sub
)

Output 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() .

R
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() .

R
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 .

R
mod_full <- lm(
  Salary ~ AtBat + Hits + HmRun + Runs +
    RBI + Walks + Years,
  data = hitters_sub
)

The 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.

R
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.

R
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.

R
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.

R
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 .

R
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-16

Untuk melihat pengaruh penghapusan satu peubah dari model dapat digunakan fungsi drop1() .

R
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 ' ' 1

Perhatikan 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 .

R
mod_b1 <- update(
  mod_full,
  . ~ . - HmRun
)

Selanjutnya dilakukan pemeriksaan kembali.

R
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 ' ' 1

Apabila 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.

R
mod_b2 <- update(
  mod_b1,
  . ~ . - Runs
)

Proses 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.

R
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.1

Model yang dihasilkan dapat dilihat melalui formula berikut.

R
formula(mod_backward)
Salary ~ AtBat + Hits + RBI + Walks + Years

Nilai AIC dari model akhir adalah

R
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 .

R
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-16

The effect of removing one variable from the model can be examined using the drop1() function.

R
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 ' ' 1

Observe 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 .

R
mod_b1 <- update(
  mod_full,
  . ~ . - HmRun
)

The model is then examined again.

R
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 ' ' 1

If 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.

R
mod_b2 <- update(
  mod_b1,
  . ~ . - Runs
)

The 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.

R
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.1

The resulting model can be viewed through the following formula.

R
formula(mod_backward)
Salary ~ AtBat + Hits + RBI + Walks + Years

The AIC value of the final model is

R
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.

R
mod_null <- lm(
  Salary ~ 1,
  data = hitters_sub
)

Model dengan seluruh prediktor digunakan sebagai batas atas dari peubah yang dapat dipilih.

R
mod_full
Call:
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.549

Forward selection berdasarkan AIC dapat dilakukan menggunakan fungsi step() .

R
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.8

Peubah yang terpilih pada model akhir dapat dilihat dari formula model.

R
formula(mod_forward)
Salary ~ RBI + Years + Walks + Hits + AtBat

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.

R
mod_null <- lm(
  Salary ~ 1,
  data = hitters_sub
)

The model containing all predictors is used as the upper limit of the variables that can be selected.

R
mod_full
Call:
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.549

Forward selection based on AIC can be performed using the step() function.

R
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.8

The variables selected in the final model can be viewed from the model formula.

R
formula(mod_forward)
Salary ~ RBI + Years + Walks + Hits + AtBat

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

R
reg_forward <- regsubsets(
  Salary ~ .,
  data = hitters,
  method = "forward",
  nvmax = 19
)

Hasil pemilihan peubah pada setiap ukuran model dapat dilihat sebagai berikut.

R
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.

R
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
)

Menggunakan BIC

Model dengan nilai BIC terkecil dapat dicari menggunakan

R
which.min(summary_forward$bic)
[1] 6

Visualisasi nilai BIC untuk setiap jumlah prediktor.

R
forward_metric %>%
  ggplot(aes(x = nvar, y = bic)) +
  geom_line() +
  geom_point() +
  labs(
    x = "Jumlah Prediktor",
    y = "BIC"
  ) +
  theme_bw()
R output figure

Koefisien dari model dengan nilai BIC terkecil adalah

R
best_forward <- which.min(summary_forward$bic)

Backward Selection

R
reg_backward <- regsubsets(
  Salary ~ .,
  data = hitters,
  method = "backward",
  nvmax = 19
)

Kriteria pemilihan model disimpan dalam tabel berikut.

R
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
)

Model dengan nilai BIC terkecil adalah

R
which.min(summary_backward$bic)
[1] 8

Visualisasi nilai BIC.

R
backward_metric %>%
  ggplot(aes(x = nvar, y = bic)) +
  geom_line() +
  geom_point() +
  labs(
    x = "Jumlah Prediktor",
    y = "BIC"
  ) +
  theme_bw()
R output figure

Koefisien dari model yang memiliki BIC terkecil adalah

R
best_backward <- which.min(summary_backward$bic)

Forward 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

R
reg_forward <- regsubsets(
  Salary ~ .,
  data = hitters,
  method = "forward",
  nvmax = 19
)

The selected variables for each model size can be viewed as follows.

R
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.

R
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
)

Using BIC

The model with the smallest BIC value can be identified using

R
which.min(summary_forward$bic)
[1] 6

Visualization of the BIC value for each number of predictors.

R
forward_metric %>%
  ggplot(aes(x = nvar, y = bic)) +
  geom_line() +
  geom_point() +
  labs(
    x = "Number of Predictors",
    y = "BIC"
  ) +
  theme_bw()
R output figure

The coefficients of the model with the smallest BIC value are

R
best_forward <- which.min(summary_forward$bic)

Backward Selection

R
reg_backward <- regsubsets(
  Salary ~ .,
  data = hitters,
  method = "backward",
  nvmax = 19
)

The model selection criteria are stored in the following table.

R
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
)

The model with the smallest BIC value is

R
which.min(summary_backward$bic)
[1] 8

Visualization of the BIC values.

R
backward_metric %>%
  ggplot(aes(x = nvar, y = bic)) +
  geom_line() +
  geom_point() +
  labs(
    x = "Number of Predictors",
    y = "BIC"
  ) +
  theme_bw()
R output figure

The coefficients of the model with the smallest BIC value are

R
best_backward <- which.min(summary_backward$bic)

AIC 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.

R
best_forward
[1] 6

Peubah pada masing-masing model adalah

R
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.2643076

Hasil 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.

R
best_forward
[1] 6

The variables in each model are

R
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.2643076

Forward 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.

R
par(mfrow = c(2, 2))
plot(mod_backward)
R output figure

Normalitas Residual

Normalitas residual dapat dilihat menggunakan Q-Q plot dan diuji menggunakan Shapiro-Wilk.

R
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.

R
plot(
  fitted(mod_backward),
  residuals(mod_backward),
  xlab = "Fitted Value",
  ylab = "Residual"
)

Observasi Berpengaruh

Cook’s distance dapat digunakan untuk melihat observasi yang memiliki pengaruh besar terhadap hasil pemodelan.

R
cook <- cooks.distance(mod_backward)

Observasi dengan Cook’s distance terbesar dapat dilihat menggunakan

R
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.

R
par(mfrow = c(2, 2))
plot(mod_backward)
R output figure

Normality of Residuals

Residual normality can be examined using a Q-Q plot and tested using the Shapiro-Wilk test.

R
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.

R
plot(
  fitted(mod_backward),
  residuals(mod_backward),
  xlab = "Fitted Value",
  ylab = "Residual"
)

Influential Observations

Cook’s distance can be used to identify observations that have a large influence on the modeling results.

R
cook <- cooks.distance(mod_backward)

The observations with the largest Cook’s distance values can be identified using

R
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.

R
pred <- predict(
  mod_backward,
  newdata = hitters_sub
)

Nilai aktual dan prediksi dapat dibandingkan sebagai berikut.

R
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.

R
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()
R output figure

The fitted regression model can be used to generate predicted values.

R
pred <- predict(
  mod_backward,
  newdata = hitters_sub
)

The actual and predicted values can be compared as follows.

R
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.

R
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()
R output figure

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

R
rmse <- sqrt(
  mean(
    (hitters_sub$Salary - pred)^2
  )
)

Nilai (R^2) model dapat diperoleh dari

R
summary(mod_backward)$r.squared
[1] 0.4080897

Sedangkan adjusted (R^2) adalah

R
summary(mod_backward)$adj.r.squared
[1] 0.3965739

Root Mean Squared Error can be calculated using

R
rmse <- sqrt(
  mean(
    (hitters_sub$Salary - pred)^2
  )
)

The (R^2) value of the model can be obtained from

R
summary(mod_backward)$r.squared
[1] 0.4080897

The adjusted (R^2) is

R
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.

PENULISAUTHOR
Unique Desyrre A. Resiloy