---
title: "SVEMnet Vignette"
author: 
  - Andrew T. Karl
date: "`r format(Sys.time(), '%B %d, %Y')`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{SVEMnet Vignette}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

# Version
version `r utils::packageVersion("SVEMnet")`

# Summary

`SVEMnet` implements Self-Validated Ensemble Models (SVEM, Lemkus et al. 2021) and the SVEM whole model test (Karl 2024) using Elastic Net regression via the `glmnet` package Friedman et al. (2010). This vignette provides an overview of the package’s functionality and usage.


# Preface - Note from the author

The motivation to create the `SVEMnet` package was primarily to have a personal sandbox to explore SVEM performance in different scenarios and with various modifications to its structure. As noted in the documentation, I used `GPT o1-preview` to help form the code structure of the package and to code the Roxygen structure of the documentation. I have subsequently used more recent versions for auditing. The SVEM significance test R code comes from the supplementary material of Karl (2024). I wrote that code by hand and validated each step (not including the creation of the SVEM predictions) against corresponding results in JMP (the supplementary material of Karl (2024) provides the matching JSL script). For the `SVEMnet()` code, assuming only a single value of alpha for `glmnet` is being tested, the heart of the SVEM code is simply


```r
#partial code for illustration of the SVEM loop
coef_matrix <- matrix(NA, nrow = nBoot, ncol = p + 1)
 for (i in 1:nBoot) {
      U <- runif(n)
      w_train <- -log(U)
      w_valid <- -log(1 - U)
      #match glmnet normalization of training weight vector
      w_train <- w_train * (n / sum(w_train))
      w_valid <- w_valid * (n / sum(w_valid))
      glmnet(
          X, y_numeric,
          alpha = alpha,
          weights = w_train,
          intercept = TRUE,
          standardize = standardize,
          maxit = 1e6,
          nlambda = 500
      )
      predict(fit, newx = X)
      val_errors <- colSums(w_valid * (y_numeric - pred_valid)^2)
      k_values <- fit$df
      n_obs <- length(y_numeric)
      aic_values <- n_obs * log(val_errors / n_obs) + 2 * k_values
         # Choose lambda
      if (objective == "wSSE") {
        idx_min <- which.min(val_errors)
        lambda_opt <- fit$lambda[idx_min]
        val_error <- val_errors[idx_min]
      } else if (objective == "wAIC") {
        idx_min <- which.min(aic_values)
        lambda_opt <- fit$lambda[idx_min]
        val_error <- aic_values[idx_min]
      }
      coef_matrix[i, ] <- as.vector(coef(fit, s = lambda_opt))
}
```
However, to get this to a stable implementation that includes error and warning handling and structure to pass to S3 methods for `predict()`, `coef()`, `plot()`, etc, it was only practical for me to utilize help from GPT o1-preview. I simply would not have taken the time to add that structure otherwise, and my implementation would have been inferior. I reviewed any of the code that was generated from this tool before integrating it, and corrected its occasional mistakes. If someone would like to create a purely human-written set of code for a similar purpose, let me know and I will be happy to add links to your package and a description to the `SVEMnet` documentation.

Later revisions make use of later versions of GPT for code auditing, stress testing, and simulaiton. Many of the later entries in this vignette were written with GPT (code, analysis, summary). 

# SVEMnet Example 1

```{r,fig.width=6, fig.height=4}
library(SVEMnet)

# Example data
data <- iris
svem_model <- SVEMnet(Sepal.Length ~ ., data = data, nBoot = 300)
coef(svem_model)
```


Generate a plot of actual versus predicted values:

```{r,fig.width=6, fig.height=4}
plot(svem_model)
```


Predict outcomes for new data using the `predict()` function:

```{r}
predictions <- predict(svem_model, data)
print(predictions)
```


## Whole Model Significance Testing

This is the serial version of the significance test. It is slower but the code is less complicated to read than the faster parallel version.

```r
test_result <- svem_significance_test(Sepal.Length ~ ., data = data)
print(test_result)
plot(test_result)
SVEM Significance Test p-value:
[1] 0
```

```{r, echo=FALSE, out.width='100%', fig.cap="Whole model test result"}
knitr::include_graphics("figures/whole_model_test.png")
```
Note that there is a parallelized version that runs much faster

```r
test_result <- svem_significance_test_parallel(Sepal.Length ~ ., data = data)
print(test_result)
plot(test_result)
SVEM Significance Test p-value:
[1] 0
```

# SVEMnet Example 2
```r
# Simulate data
set.seed(1)
n <- 25
X1 <- runif(n)
X2 <- runif(n)
X3 <- runif(n)
X4 <- runif(n)
X5 <- runif(n)

#y only depends on X1 and X2
y <- 1 + X1 +  X2 + X1 * X2 + X1^2 + rnorm(n)
data <- data.frame(y, X1, X2, X3, X4, X5)

# Perform the SVEM significance test
test_result <- svem_significance_test_parallel(
  y ~ (X1 + X2 + X3)^2 + I(X1^2) + I(X2^2) + I(X3^2),
  data = data

)

# View the p-value
print(test_result)
SVEM Significance Test p-value:
[1] 0.009399093


test_result2 <- svem_significance_test_parallel(
  y ~ (X1 + X2 )^2 + I(X1^2) + I(X2^2),
  data = data
)

# View the p-value
print(test_result2)
SVEM Significance Test p-value:
[1] 0.006475736

#note that the response does not depend on X4 or X5
test_result3 <- svem_significance_test_parallel(
  y ~ (X4 + X5)^2 + I(X4^2) + I(X5^2),
  data = data
)

# View the p-value
print(test_result3)
SVEM Significance Test p-value:
[1] 0.8968502

# Plot the Mahalanobis distances
plot(test_result,test_result2,test_result3)
```
```{r, echo=FALSE, out.width='100%', fig.cap="Whole Model Test Results for Example 2"}
knitr::include_graphics("figures/whole_model_2.png")
```



# 21DEC2024: Add glmnet.cv wrapper

Newly added wrapper for cv.glmnet() to compare performance of SVEM to glmnet's native CV implementation.

# 22AUG2025: Simulation — choosing the default SVEMnet objective (lasso)

Including 0 in glmnet_alpha (ridge) seems to make the fits less stable. Changing default to lasso (alpha=1). It might be reasonable to use c(0.5, 1).

**What we tested.** We compared SVEMnet objectives with **lasso** (α = 1) — `wAIC`, `wBIC`, and `wSSE` — against a benchmark `glmnet_cv_lasso`.  
**Design range.** Simulated mixture surface with random coefficients; Theoretical R² ∈ {0.3, 0.5, 0.7, 0.9}; sample sizes **n_total ∈ {15, 25, 35, …, 95}**.  
**Metrics.** Holdout **NRASE** and **NAAE**, both **normalized per run** by the holdout SD of the true response; tie-aware **win rate**; **average rank** (lower = better); and **paired, per-run** differences between AIC and BIC. Analyses are **stratified** at **n_total ≤ 40** vs **n_total > 40**.

**Key findings from this run (values will vary with a new seed):**
- **Overall:** glmnet_cv_lasso and SVEM_wAIC_lasso were close (mean NRASE ≈ **0.526** vs **0.532**), BIC higher (**0.543**), and wSSE highest (**0.646**).
- **Small n (n_total ≤ 40):** **BIC** had the best mean NRASE (≈ **0.683**), then glmnet (≈ **0.717**), then **AIC** (≈ **0.747**); wSSE lagged (≈ **1.01**). AIC–BIC paired mean Δ ≈ **+0.063** (AIC worse; p ≈ 0.016).  
  → **BIC is safer/better at very small n.**
- **Larger n (n_total > 40):** **AIC** dominated (**≈ 0.425**) vs glmnet (**≈ 0.430**) and BIC (**≈ 0.473**); wSSE in between (**≈ 0.462**). AIC–BIC paired mean Δ ≈ **−0.048** (AIC better; p ≪ 1e−30).  
  → **AIC is superior once n grows.**
- **wSSE (lasso)** under-performed both AIC and BIC in this setup and can be excluded from default consideration.



```
```{r show-file6, echo=FALSE, results='asis'}
raw_file6 <- readLines("bic_sim.R")
cat("```r\n")
cat(raw_file6, sep="\n")
cat("\n```\n")
```


## References and Citations


1. **Lemkus, T., Gotwalt, C., Ramsey, P., & Weese, M. L. (2021).** *Self-Validated Ensemble Models for Elastic Net Regression*.  
   *Chemometrics and Intelligent Laboratory Systems*, 219, 104439.  
   DOI: [10.1016/j.chemolab.2021.104439](https://doi.org/10.1016/j.chemolab.2021.104439)

2. **Karl, A. T. (2024).** *A Randomized Permutation Whole-Model Test for SVEM*.  
   *Chemometrics and Intelligent Laboratory Systems*, 249, 105122.  
   DOI: [10.1016/j.chemolab.2024.105122](https://doi.org/10.1016/j.chemolab.2024.105122)

3. **Friedman, J. H., Hastie, T., & Tibshirani, R. (2010).** *Regularization Paths for Generalized Linear Models via Coordinate Descent*.  
   *Journal of Statistical Software*, 33(1), 1–22.  
   DOI: [10.18637/jss.v033.i01](https://doi.org/10.18637/jss.v033.i01)

4. **Gotwalt, C., & Ramsey, P. (2018).** *Model Validation Strategies for Designed Experiments Using Bootstrapping Techniques With Applications to Biopharmaceuticals*.  
   *JMP Discovery Conference*.  
   [Link](https://community.jmp.com/t5/Abstracts/Model-Validation-Strategies-for-Designed-Experiments-Using/ev-p/849873/redirect_from_archived_page/true)

5. **Ramsey, P., Gaudard, M., & Levin, W. (2021).** *Accelerating Innovation with Space-Filling Mixture Designs, Neural Networks, and SVEM*.  
   *JMP Discovery Conference*.  
   [Link](https://community.jmp.com/t5/Abstracts/Accelerating-Innovation-with-Space-Filling-Mixture-Designs/ev-p/756841)

6. **Ramsey, P., & Gotwalt, C. (2018).** *Model Validation Strategies for Designed Experiments Using Bootstrapping Techniques With Applications to Biopharmaceuticals*.  
   *JMP Discovery Summit Europe*.  
   [Link](https://community.jmp.com/t5/Abstracts/Model-Validation-Strategies-for-Designed-Experiments-Using/ev-p/849647/redirect_from_archived_page/true)

7. **Ramsey, P., Levin, W., Lemkus, T., & Gotwalt, C. (2021).** *SVEM: A Paradigm Shift in Design and Analysis of Experiments*.  
   *JMP Discovery Summit Europe*.  
   [Link](https://community.jmp.com/t5/Abstracts/SVEM-A-Paradigm-Shift-in-Design-and-Analysis-of-Experiments-2021/ev-p/756634)

8. **Ramsey, P., & McNeill, P. (2023).** *CMC, SVEM, Neural Networks, DOE, and Complexity: It's All About Prediction*.  
   *JMP Discovery Conference*.

9. **Karl, A., Wisnowski, J., & Rushing, H. (2022).** *JMP Pro 17 Remedies for Practical Struggles with Mixture Experiments*.  
   *JMP Discovery Conference*.  
  [Link](https://doi.org/10.13140/RG.2.2.34598.40003/1)

10. **Xu, L., Gotwalt, C., Hong, Y., King, C. B., & Meeker, W. Q. (2020).** *Applications of the Fractional-Random-Weight Bootstrap*.  
    *The American Statistician*, 74(4), 345–358.  
   [Link](https://doi.org/10.1080/00031305.2020.1731599)

11. **Karl, A. T. (2024).** *SVEMnet: Self-Validated Ensemble Models with Elastic Net Regression*.  
    R package

12. **JMP Help Documentation** *Overview of Self-Validated Ensemble Models*.  
    [Link](https://www.jmp.com/support/help/en/18.1/?utm_source=help&utm_medium=redirect#page/jmp/overview-of-selfvalidated-ensemble-models.shtml)



