Smarket<-read_csv("data/Smarket.csv")#> Rows: 1250 Columns: 9#> ── Column specification ────────────────────────────────────────────────────────#> Delimiter: ","#> chr (1): Direction#> dbl (8): Year, Lag1, Lag2, Lag3, Lag4, Lag5, Volume, Today#> #> ℹ Use `spec()` to retrieve the full column specification for this data.#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.Smarket$Direction<-factor(Smarket$Direction)head(Smarket)#> # A tibble: 6 × 9#> Year Lag1 Lag2 Lag3 Lag4 Lag5 Volume Today Direction#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <fct> #> 1 2001 0.381 -0.192 -2.62 -1.06 5.01 1.19 0.959 Up #> 2 2001 0.959 0.381 -0.192 -2.62 -1.06 1.30 1.03 Up #> 3 2001 1.03 0.959 0.381 -0.192 -2.62 1.41 -0.623 Down #> 4 2001 -0.623 1.03 0.959 0.381 -0.192 1.28 0.614 Up #> 5 2001 0.614 -0.623 1.03 0.959 0.381 1.21 0.213 Up #> 6 2001 0.213 0.614 -0.623 1.03 0.959 1.35 1.39 Up
Code
lda_spec<-discrim_linear()%>%set_mode("classification")%>%set_engine("MASS")lda_fit<-lda_spec%>%fit(Direction~Lag1+Lag2, data =Smarket)lda_fit#> parsnip model object#> #> Call:#> lda(Direction ~ Lag1 + Lag2, data = data)#> #> Prior probabilities of groups:#> Down Up #> 0.4816 0.5184 #> #> Group means:#> Lag1 Lag2#> Down 0.05068605 0.03229734#> Up -0.03969136 -0.02244444#> #> Coefficients of linear discriminants:#> LD1#> Lag1 -0.7567605#> Lag2 -0.4707872
Code
predict(lda_fit, new_data =Smarket)#> # A tibble: 1,250 × 1#> .pred_class#> <fct> #> 1 Up #> 2 Down #> 3 Down #> 4 Up #> 5 Up #> 6 Up #> 7 Down #> 8 Up #> 9 Up #> 10 Down #> # ℹ 1,240 more rowspredict(lda_fit, new_data =Smarket, type ="prob")#> # A tibble: 1,250 × 2#> .pred_Down .pred_Up#> <dbl> <dbl>#> 1 0.486 0.514#> 2 0.503 0.497#> 3 0.510 0.490#> 4 0.482 0.518#> 5 0.485 0.515#> 6 0.492 0.508#> 7 0.509 0.491#> 8 0.490 0.510#> 9 0.477 0.523#> 10 0.505 0.495#> # ℹ 1,240 more rowsaugment(lda_fit, new_data =Smarket)%>%conf_mat(truth =Direction, estimate =.pred_class)#> Truth#> Prediction Down Up#> Down 114 102#> Up 488 546augment(lda_fit, new_data =Smarket)%>%accuracy(truth =Direction, estimate =.pred_class)#> # A tibble: 1 × 3#> .metric .estimator .estimate#> <chr> <chr> <dbl>#> 1 accuracy binary 0.528