---
title: "Feature Reduction (PCA, cMDS, ICA...)"
output: 
  github_document:
    toc: true
    fig_width: 10.08
    fig_height: 6
  rmarkdown::html_vignette:
    toc: true
    fig_width: 10.08
    fig_height: 6
tags: [r, parameters, variable extraction, feature extraction, dimension extraction]
vignette: >
  %\VignetteIndexEntry{Feature Reduction (PCA, cMDS, ICA, ...)}
  \usepackage[utf8]{inputenc}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  chunk_output_type: console
bibliography: bibliography.bib
---

```{r message=FALSE, warning=FALSE, include=FALSE}
library(knitr)
options(knitr.kable.NA = '')
options(digits = 2)
knitr::opts_chunk$set(comment = "#>")

if (!requireNamespace("dplyr", quietly = TRUE) ||
    !requireNamespace("psych", quietly = TRUE)) {
  knitr::opts_chunk$set(eval = FALSE)
} else {
  library(parameters)
  library(dplyr)
}

set.seed(333)
```




Also known as [**feature extraction** or **dimension reduction**](https://en.wikipedia.org/wiki/Feature_extraction) in machine learning, the goal of variable reduction is to **reduce the number of predictors** by derivating, from a set of measured data, new variables intended to be informative and non-redundant. This method can be used to **simplify models**, which can benefit model interpretation, shorten fitting time, and improve generalization (by reducing overfitting).


## Quick and Exploratory Method

Let's start by fitting a multiple regression with the `attitude` dataset, available is base R, to predict the overall **rating** by employees of their organization with the remaining variables (handling of employee **complaints**, special **privileges**, opportunity of **learning**, **raises**, a feedback considered too **critical** and opportunity of **advancement**).

```{r message=FALSE, warning=FALSE}
model <- lm(rating ~ ., data = attitude)
parameters(model)
```

We can explore a reduction of the number of parameters with the `reduce_parameters()` function. 

```{r message=FALSE, warning=FALSE}
newmodel <- reduce_parameters(model)
parameters(newmodel)
```

This quickly *hints* toward the fact that the model could be represented via **two "latent" dimensions**, one correlated with all the positive things that a company has to offer, and the other one related to the amount of negative critiques received by the employees. These two dimensions have a positive and negative relationship with the company rating, respectively.

> What does `reduce_parameters()` exactly do?

This function performs a reduction in the parameters space (the number of variables). It starts by creating a new set of variables, based on a given method (the default method is "**PCA**", but other are available via the `method` argument, such as "**cMDS**", "**DRR**" or "**ICA**"). Then, it names this new dimensions using the original variables that *correlate* the most with it. For instance, a variable named 'V1_0.97/V4_-0.88' means that the V1 and the V4 variables correlate maximally (with respective coefficients of .97 and -.88) with this dimension.

```{r message=FALSE, warning=FALSE}
reduce_parameters(model, method = "cMDS") %>% 
  parameters()
```

A different method (**Classical Multidimensional Scaling - cMDS**) suggests that negative critiques do not have a significant impact on the rating, and that the lack of opportunities of career advancement is a separate dimension with an importance on its own.

Although this function can be useful in exploratory data analysis, it's best to perform the dimension reduction step in a **separate and dedicated stage**, as this is a very important process in the data analysis workflow.


## Principal Component Analysis (PCA)

PCA is a widely used procedure that lies in-between dimension reduction and structural modelling. Indeed, one of the way of reducing the number of predictors is to extract a new set of uncorrelated variables that will *represent* variance of your initial dataset. But how the original variables relate between themselves can also be a question on its own.

We can apply the `principal_components()` function to do the the predictors of the model:

```{r message=FALSE, warning=FALSE}
pca <- principal_components(insight::get_predictors(model), n = "auto")
pca
```

The `principal_component()` function automatically selected one component (if the number of components is not specified, this function uses [`n_factors()`](https://easystats.github.io/parameters/reference/n_factors.html) to estimate the optimal number to keep) and returned the **loadings**, i.e., the relationship with all of the original variables. 

As we can see here, it seems that our new component captured the essence (more than half of the total variance present in the original dataset) of all our other variables together. We can **extract** the values of this component for each of our observation using the `predict()` method and add in the response variable of our initial dataset.

```{r message=FALSE, warning=FALSE}
newdata <- predict(pca)
newdata$rating <- attitude$rating
```

We can know update the model with this new component:
```{r message=FALSE, warning=FALSE}
update(model, rating ~ PC1, data = newdata) %>% 
  parameters()
```


### Using the `psych` package for PCA

You can also use different packages for models, such as [`psych`](https://cran.r-project.org/package=psych) [@revelle2018] or [`FactoMineR`](http://factominer.free.fr/) for PCA or Exploratory Factor Analysis (EFA), as it allows for more flexibility, control and details when running such procedures. Thus, the functions from this package are **fully supported** by `parameters` through the `model_parameters()` function.

As such, the above analysis can be fully reproduced as follows:

```{r message=FALSE, warning=FALSE}
library(psych)

# Fit the PCA
pca <- psych::principal(attitude, nfactors = 1) %>% 
  model_parameters()
pca
```

*Note:* By default, `psych::principal()` uses a **varimax** rotation to extract rotated components, possibly leading to discrepancies in the results.

Finally, refit the model:

```{r message=FALSE, warning=FALSE}
df <- cbind(attitude, predict(pca))

update(model, rating ~ PC1, data = df) %>% 
  model_parameters()
```

# References