IV. Principal Component Analysis (PCA)


Exploratory Data Analysis & Unsupervised Learning

     

Lecturer: Dr. HAS Sothea
..Instructor: Ms. UANN Sreyvi

Resources

1 Motivation

1.1 Motivation

California Housing Prices dataset

  • The data contains information of neighborhoods from the 1990 California census.
  • Dimension: (20640, 10).
latitude total_rooms population median_income median_house_value ocean_proximity
0 37.88 880.0 322.0 8.3252 452600.0 NEAR BAY
1 37.86 7099.0 2401.0 8.3014 358500.0 NEAR BAY
2 37.85 1467.0 496.0 7.2574 352100.0 NEAR BAY
3 37.85 1274.0 558.0 5.6431 341300.0 NEAR BAY
4 37.85 1627.0 565.0 3.8462 342200.0 NEAR BAY
  • How are the size and economic of neighborhoods related?
  • How are the previous related to their locations?
  • Correlation matrix
Code
# import matplotlib.pyplot as plt
# import seaborn as sns
import plotly.express as px
corr = data.select_dtypes(include="number").corr().round(2)
fig_corr = px.imshow(
    corr, x=corr.columns, y=corr.columns,
    text_auto=True,
    color_continuous_scale='RdBu_r',
    range_color=[-1, 1],
    title="Correlation matrix of numeric columns"
)
fig_corr.update_layout(
    {'paper_bgcolor': 'rgba(0,0,0,0)',
    'plot_bgcolor': 'rgba(0,0,0,0)'},
    width=470, height=400,
    xaxis_title="Variables",
    yaxis_title="Variables"
)
# 2. Add the royal blue frame by mirroring the x and y axes
fig_corr.update_xaxes(
    showline=True, 
    linewidth=1, 
    linecolor='gray', 
    mirror=True,  # Mirrors the bottom x-axis line to the top
    showgrid=True, gridwidth=1, gridcolor=LIGHT_GRAY
)
fig_corr.update_yaxes(
    showline=True, 
    linewidth=1, 
    linecolor='gray', 
    mirror=True,  # Mirrors the left y-axis line to the right
    showgrid=True, gridwidth=1, gridcolor=LIGHT_GRAY
)
fig_corr.show()
  • Recall: correlation matrix:
    • Summarizes linear relation between columns.
    • Absolute values \(\approx 1\) indicate strong linear relation.
    • Weak values \(\approx 0\) suggest non-linear relation, or may be affected by
      • Outliers (see TP2 Solution),
      • Lacks of data points,
      • Confounding variables…
  • Correlation matrix
Code
fig_corr.show()
  • High correlations among columns suggest similar information therefore can be compressed/reduced.
  • Geometrically, the pattern of data can be represented in simpler/smaller dimension.
  • PCA’s Objectives:
    • Detect important directions of data cloud
    • Represent the data in terms of these dimensions.
  • Application: Dimensionality reduction, data visualization & compression, feature clustering & extraction, noise reduction, etc.

2 Principal Directions (PDs) & Components (PCs)

2.1 PDs & PCs

Principal Directions (PDs)

  • Given data matrix: \(D\in\mathbb{R}^{n\times d}\),
X Y Z
0 0.041 1.192 1.591
1 -1.439 2.870 1.992
2 1.661 2.043 4.787
3 -2.891 0.794 -1.043
4 1.618 3.229 3.470
5 2.310 2.082 3.454

Principal Directions (PDs)

  • Principal Directions (PDs) are the so-called important directions mentioned in PCA’s objectives.

Definition: Principal Directions \(\vec{u}_k\)

  • The 1st PD \(\color{red}{\vec{u}_1}\in\mathbb{R}^d\) is the unit vector or direction that the data spreads or varies the most: \(\color{red}{\vec{u}_1}=\arg\max_{\color{purple}{\vec{u}}\in\mathbb{R}^d:\|\color{purple}{\vec{u}}\|^2=1}\|D\color{purple}{\vec{u}}\|^2.\)
  • The 2nd PD \(\color{green}{\vec{u}_2}\in\mathbb{R}^d\) is the unit direction perpendicular to \(\color{red}{\vec{u}_1}\) and captures 2nd largest variation of the data: \(\color{green}{\vec{u}_2}=\arg\max_{\vec{u}\in\mathbb{R}^d:\|\color{purple}{\vec{u}}\|^2=1,\color{purple}{\vec{u}}\perp \color{red}{\vec{u}_1}}\|D\color{purple}{\vec{u}}\|^2.\)
  • The \(k\)-th PD \(\color{blue}{\vec{u}_k}\in\mathbb{R}^d\) (\(3\leq k\leq d\)) is the unit direction that is perpendicular to \(S_{k-1}=\{\color{red}{\vec{u}_1},\color{green}{\vec{u}_2},\dots,\color{purple}{\vec{u}_{k-1}}\}\) and captures the \(k\)-th largest variation of the data: \(\color{blue}{\vec{u}_k}=\arg\max_{\color{purple}{\vec{u}}\in\mathbb{R}^d:\|\color{purple}{\vec{u}}\|^2=1,\color{purple}{\vec{u}}\perp S_{k-1}}\|D\color{purple}{\vec{u}}\|^2.\)

Principal Components (PCs)

  • Principal Directions (PDs) are the so-called important directions mentioned in PCA’s objectives.

Definition: Principal Components \(\text{PC}_j\)

  • Let \(\color{blue}{U}\) be a \(d\times d\) matrix with all PDs columns, i.e., \[\color{blue}{U}=[\color{red}{\vec{u}_1}|\color{green}{\vec{u}_2}|\dots |\color{blue}{\vec{u}_d}],\] then \(\color{red}{\tilde{D}}=D\color{blue}{U}\) is the rotated data with the following properties:
    • Independent cols: \(\color{blue}{\tilde{D_j}}\perp \color{blue}{\tilde{D_k},\forall j\neq k}\).
    • For any \(j=1,2,...,d:\color{blue}{\tilde{D_j}}\) is the column with \(j\)-th largest variation.
    • Total var: \(\sum_{j=1}^d\|\color{blue}{\tilde{D_j}}\|^2=\sum_{j=1}^d\|D_j\|^2.\)
  • The columns \(\color{blue}{\tilde{D_j}}\)’s are called Principal Components (PCs) of \(D\) denoted by \(\color{blue}{\text{PC}_j}\).

How to find PDs & PCs

  • Perform PCA comes down to computing rotated data \(\color{red}{\tilde{D}}=D\color{blue}{U}\) or computing \(\color{blue}{U}\).

Principal Direction Problem

  • Without loss of generality, we assume that the data is centered (\(\overline{D}_j=0\),\(\forall j=1,\dots,d\)).
  1. The 1st PD \(\color{red}{\vec{u}_1}\) is the eigenvector of matrix \(A=D^TD\) with the largest eigenvalue \(\color{red}{\lambda_1}\geq 0\), i.e., \((\color{red}{\vec{u}_1},\color{red}{\lambda_1})\) solves \(A\color{red}{\vec{u}_1}=\color{red}{\lambda_1\vec{u}_1}\).
  2. The 2nd PD \(\color{green}{\vec{u}_2}\) is the eigenvector of matrix \(A=D^TD\) with the 2nd largest eigenvalue \(\color{green}{\lambda_2}\geq 0\), i.e., \((\color{green}{\vec{u}_2},\color{green}{\lambda_2})\) solves \(A\color{green}{\vec{u}_2}=\color{green}{\lambda_2\vec{u}_2}\).
  3. The \(k\)-th PD \(\color{blue}{\vec{u}_k}\) is the eigenvector of matrix \(A=D^TD\) with the \(k\)-th largest eigenvalue \(\color{blue}{\lambda_k}\geq 0\), i.e., \((\color{blue}{\vec{u}_k},\color{blue}{\lambda_k})\) solves \(A\color{blue}{\vec{u}_k}=\color{blue}{\lambda_k\vec{u}_k}\).

Solution to Principal Directions \(\vec{u}_k\)

  • PDs \(\color{red}{\vec{u}_1},\dots,\color{blue}{\vec{u}_d}\) are the 1st, …, \(d\)-th eigenvectors of matrix \(A=D^TD\) with eigenvalues \(\color{red}{\lambda_1}\geq\dots\geq\color{blue}{\lambda_d}\geq 0\) respectively.
  • Principal components are the columns of

\[\begin{align*} \underbrace{\color{red}{\tilde{D}}}_{n\times d}&=\underbrace{D}_{n\times d}\times\underbrace{\color{blue}{U}}_{n\times d}\\ &=\begin{bmatrix} x_{11} & \dots & x_{1d}\\ x_{21} & \dots & x_{2d}\\ x_{31} & \dots & x_{3d}\\ \vdots & \ddots & \vdots\\ x_{n1} & \dots & x_{nd}\end{bmatrix} \begin{bmatrix} \color{red}{u_{11}} & \dots & \color{blue}{u_{1d}}\\ \color{red}{u_{21}} & \dots & \color{blue}{u_{2d}}\\ \vdots & \ddots & \vdots\\ \color{red}{u_{d1}} & \dots & \color{blue}{u_{dd}}\end{bmatrix} \end{align*}\]

  • The \(\color{blue}{\text{PC}_j}\) is the combination of original columns of \(D_k\)’s, i.e., \(\color{blue}{\text{PC}_j}=\sum_{k=1}^du_{kj}D_k.\)

Implementation of PCA

Unnormalized PCA

  • Given data: \(D\in\mathbb{R}^{n\times d}\)
  • Centering \(D_c=\underbrace{D}_{n\times d} -\underbrace{\mathbb{1}_n}_{n\times n}\overbrace{D}^{n\times d}/n.\)
  • Perform Eigenvalue Decomposition on covariance matrix \(V=D_c^TD_c/(n-1)\), i.e., \[V=\color{blue}{U}\Lambda \color{blue}{U}^T,\]
    • \(\color{blue}{U}\): matrix of eigenvectors
    • \(\Lambda=\text{diag}(\color{red}{\lambda_1},\dots,\color{blue}{\lambda_d})\): diagonal matrix of eigenvalues \(\color{red}{\lambda_1}\geq \dots\geq \color{blue}{\lambda_d}\geq 0\).

Normalized PCA

  • Given data: \(D\in\mathbb{R}^{n\times d}\)
  • Standardizing: compute std matrix \(\color{red}{\Sigma}=\text{diag}(\widehat{\sigma}_1,\dots,\widehat{\sigma}_d)\) and standardized data \(Z=(\underbrace{D}_{n\times d} -\underbrace{\mathbb{1}_n}_{n\times n}\overbrace{D}^{n\times d}/n)\color{red}{\Sigma^{-1}}.\)
  • Perform Eigenvalue Decomposition on correlation matrix \(C=Z^TZ/(n-1)\), i.e., \[C=\color{blue}{U}\Lambda \color{blue}{U}^T.\]
  • Rotated data: \(\color{red}{\tilde{D}}=D\color{blue}{U}.\) [👉 Demo]

Geometric Interpretation of PCA

PCA Process and Geometric Interpretation.

3 Dimensional Reduction Reconstruction

3.1 Reduction/Reconstruction

Dimensional Reduction

  • Reduction to \(\color{red}{k}<d\) dimensions is done by \(\color{red}{\tilde{D}_k}=\color{red}{\tilde{D}}[:,:\color{red}{k}].\)
  • Quality of representation on each direction: \(\left[\frac{\lambda_1}{\sum_{j=1}^d\lambda_j},\dots,\frac{\lambda_{\color{red}{k}}}{\sum_{j=1}^d\lambda_j}\right].\)
  • Variance explained by \(\color{red}{k}\) dimensions: \(\frac{\sum_{j=1}^{\color{red}{k}}\lambda_j}{\sum_{j=1}^d\lambda_j}\times 100.\)
  • For visualization, one can choose \(\color{red}{k}=2\) or \(3\). [👉 Demo]
* Total variation of X: 17.79
X Y Z
0 0.041 1.192 1.591
1 -1.439 2.870 1.992
2 1.661 2.043 4.787
3 -2.891 0.794 -1.043
4 1.618 3.229 3.470
* Total variation of proj: 15.2
PC1 PC2 PC3
0 -2.424 -0.173 -0.197
1 -2.287 2.086 -0.406
2 1.239 -0.292 -0.558
3 -6.119 1.163 -0.709
4 0.509 0.555 0.818

Dimensional Reduction

  • Reduction to \(\color{red}{k}<d\) dimensions is done by \(\color{red}{\tilde{D}_k}=\color{red}{\tilde{D}}[:,:\color{red}{k}].\)
  • Quality of representation on each direction: \(\left[\frac{\lambda_1}{\sum_{j=1}^d\lambda_j},\dots,\frac{\lambda_{\color{red}{k}}}{\sum_{j=1}^d\lambda_j}\right].\)
  • Variance explained by \(\color{red}{k}\) dimensions: \(\frac{\sum_{j=1}^{\color{red}{k}}\lambda_j}{\sum_{j=1}^d\lambda_j}\times 100.\)
  • For visualization, one can choose \(\color{red}{k}=2\) or \(3\). [👉 Demo]
  • Application on California Housing:
  • Variance explained by 2 PCs: 79.86%.

Dimensional Reduction

  • Reduction to \(\color{red}{k}<d\) dimensions is done by \(\color{red}{\tilde{D}_k}=\color{red}{\tilde{D}}[:,:\color{red}{k}].\)
  • Quality of representation on each direction: \(\left[\frac{\lambda_1}{\sum_{j=1}^d\lambda_j},\dots,\frac{\lambda_{\color{red}{k}}}{\sum_{j=1}^d\lambda_j}\right].\)
  • Variance explained by \(\color{red}{k}\) dimensions: \(\frac{\sum_{j=1}^{\color{red}{k}}\lambda_j}{\sum_{j=1}^d\lambda_j}\times 100.\)
  • For visualization, one can choose \(\color{red}{k}=2\) or \(3\). [👉 Demo]

Reconstruction

  • The reconsution is defined by: \[\color{green}{D_k^{\text{rec}}}=\color{red}{\tilde{D}_k}\color{blue}{U[:,:k]^T}.\]
  • Low-rank approximation shows that this reconstruction \(\color{green}{D_k^{\text{rec}}}\) is the best \(k\)-rank approximation of \(D\) w.r.t. Frobenius norm, i.e., \[\color{green}{D_k^{\text{rec}}}=\arg\min_{M_k:r(M_k)\leq k}\|X-M_k\|_F,\] where \(\|D\|_F=\sqrt{\sum_{i,j}D_{ij}^2}\) is the Frobenius norm.

Summary

  • PCA captures and arranges directions with largest, 2nd largest,… variation into the 1st, 2nd, … column using Spectral Theorem (Eigenvalue decomposition).
  • These directions are contained in the eigenvector matrix of Covariance (unnormalized) or Correlation matrix (normalized) of the data.
  • The variation along each direction is given by the corresponding eigenvalues: \(\lambda_1>\dots>\lambda_d\).
  • Our goal is to explore dimensional reduction and reconstruction power of PCA, however, it can be used in Data Analysis, EDA, Data Summary…
  • Remark: Many highly correlated columns indicates effective dimensional reduction (the first two PCs can capture significant variation).

4 Correlation Circle

4.1 Correlation Circles

  • Besides dimensional reduction, PCA can also be used to summarize data.
  • How would you explain this graph?
  • 🔑 The connection between PCs and the original columns.
  • Correlation Circle is the key.
  • One can compute correlations between original data with PCs:
Code
d = len(quan_cols)
combined_data = pd.concat([pd.DataFrame(Z[:,:2], columns=['PC'+str(i+1) for i in range(2)]), pd.DataFrame(X[:,2:], columns = quan_cols[2:])], axis=1)
Corr_matrix = combined_data.corr()[['PC'+str(i+1) for i in range(2)]].iloc[2:,:]
Corr_matrix
PC1 PC2
housing_median_age -0.426668 0.048696
total_rooms 0.963481 0.087248
total_bedrooms 0.971857 -0.077096
population 0.930272 -0.113646
households 0.975068 -0.059403
median_income 0.107198 0.912892
median_house_value 0.084727 0.913812
Code
fig_cir = go.Figure()
circle = go.Scatter(
    x=np.cos(np.linspace(0, 2 * np.pi, 100)),
    y=np.sin(np.linspace(0, 2 * np.pi, 100)),
    mode='lines',
    name='Unit Circle',
    line=dict(color='black', dash='dash')
)
fig_cir.add_trace(circle)
fig_cir.add_trace(go.Scatter(
    x=[-1,1],
    y = [0,0],
    mode="lines", line=dict(color='black', dash='dash')
))
fig_cir.add_trace(go.Scatter(
    x=[0,0],
    y = [-1,1],
    mode="lines", line=dict(color='black', dash='dash')
))

loc = ['top right', 'top left', 'bottom right', 'bottom left', 'top right', 'top left', 'bottom right']

# Add loading vectors
for i, feature in enumerate(quan_cols[2:]):
    fig_cir.add_trace(go.Scatter(
        x=[0, Corr_matrix.iloc[i, 0]],
        y=[0, Corr_matrix.iloc[i, 1]],
        mode='lines+text',
        text=[None, feature],
        textposition=[loc[i]],
        name=feature,
        showlegend=True
    ))

# Set the layout
fig_cir.update_layout(
    {'paper_bgcolor': 'rgba(0,0,0,0)',
    'plot_bgcolor': 'rgba(0,0,0,0)'},
    title='Correlation Circle',
    xaxis=dict(title='PC1 ('+str(np.round(pca.explained_variance_ratio_[0]*100,2)) + '%)', range=[-1.2, 1.2]),
    yaxis=dict(title='PC2 ('+str(np.round(pca.explained_variance_ratio_[1]*100,2)) + '%)', range=[-1.2, 1.2]),
    showlegend=False,
    width=400,
    height=400
)
fig_cir.update_xaxes(
    showline=True, 
    linewidth=1, 
    linecolor='gray', 
    mirror=True,  # Mirrors the bottom x-axis line to the top
    showgrid=True, gridwidth=1, gridcolor=LIGHT_GRAY
)
fig_cir.update_yaxes(
    showline=True, 
    linewidth=1, 
    linecolor='gray', 
    mirror=True,  # Mirrors the left y-axis line to the right
    showgrid=True, gridwidth=1, gridcolor=LIGHT_GRAY
)
fig_cir.show()

Interpretation

  • Long variables indicate large correlation with the PCs therefore well represented by the PCs.
  • Highly correlated original variables are mostly aligned.
  • Those that are nearly perpendicular, tend to be decorrelated.
  • PC1 is strong related to neighborhood size variables.
  • PC2 is strong reated to financial condition variables.
  • Correlation circles can be used to summarize the Biplot of individuals.
  • Correlation circles can summarize the relationship between original variables, between original variables and PCs and help interpreting the Biplot.
  • ⚠️ Caution: Interpretation of PCs may be misleading! It’s intuition not the fact!

5 Contribution Scores

5.1 Variable contributions

  • From the Correlation Circle, we can compute the contribution of original variable \(\color{blue}{D_j}\) on \(\color{red}{\text{PC}_k}\) by \[\text{Ctr}(\color{blue}{D_j},\color{red}{\text{PC}_k})=r_{\color{blue}{j}\color{red}{k}}^2/\color{red}{\lambda_k}=\text{corr}^2(\color{blue}{D_j},\color{red}{\text{PC}_k})/\color{red}{\lambda_k}.\]
Code
corr_mat = Corr_matrix.to_numpy()
ctr_var = corr_mat ** 2 @ np.diag(1/pca.explained_variance_[:2])
ctr_var = pd.DataFrame(ctr_var,
    columns=[f'PC{i+1}' for i in range(2)],
    index=quan_cols[2:])
ctr_var.iloc[:6,:2].round(3)
PC1 PC2
housing_median_age 0.047 0.001
total_rooms 0.239 0.004
total_bedrooms 0.243 0.003
population 0.222 0.008
households 0.244 0.002
median_income 0.003 0.490
Code
ctr_var.iloc[6:,:2].round(3)
PC1 PC2
median_house_value 0.002 0.491
  • The \(4\) Neighborhood Size variables contribute toally 94.84% of the total variation of PC1.
  • The \(2\) Financial Condition variables contribute toally 98.09% of the total variation of PC2.

5.2 Observation contributions

  • The contribution of individual \(i\) on PC \(\color{red}{k}\) is defined by \[\text{Ctr}(\text{x}_i, \color{red}{\text{PC}_k})=\frac{[D\color{blue}{U}]_{i\color{red}{k}}^2}{\sum_{\color{purple}{\ell}=1}^n[D\color{blue}{U}]_{\color{purple}{\ell}\color{red}{k}}^2}=\frac{[D\color{blue}{U}]_{i\color{red}{k}}^2}{(n-1)\color{red}{\lambda_k}}\]
Code
Z = pd.DataFrame(Z, columns=['PC'+str(i+1) for i in range(X[:,2:].shape[1])])
scores = Z ** 2/((data.shape[0]-1) * pca.explained_variance_) * 100
df_contr = pd.DataFrame(
    {
        'Contribution on PC1': scores['PC1'],
        'Contribution on PC2': scores['PC2'],
        'Individual': Z.index
    }
)
fig_cont = px.scatter(df_contr, 
    x='Contribution on PC1', y='Contribution on PC2', 
    hover_name=df_contr.Individual, 
    size=df_contr['Contribution on PC1']+df_contr['Contribution on PC2'],
    color=df_contr['Contribution on PC1']+df_contr['Contribution on PC2'])
fig_cont.update_layout(
    {'paper_bgcolor': 'rgba(0,0,0,0)',
    'plot_bgcolor': 'rgba(0,0,0,0)'},
    height=260, width=460, 
    title="Contribution of individuals on PCs")
fig_cont.update_xaxes(
    showline=True, 
    linewidth=1, 
    linecolor='gray', 
    mirror=True,  # Mirrors the bottom x-axis line to the top
    showgrid=True, gridwidth=1, gridcolor=LIGHT_GRAY
)
fig_cont.update_yaxes(
    showline=True, 
    linewidth=1, 
    linecolor='gray', 
    mirror=True,  # Mirrors the left y-axis line to the right
    showgrid=True, gridwidth=1, gridcolor=LIGHT_GRAY
)
fig_cont.show()
  • Neighborhood 9782 has highest contribution of 1.32% on PC1, i.e., it may be the largest or smallest block.
  • Neighborhood 16013 has highest contribution of 0.11% on PC2, i.e., it may be the wealthiest or poorest block.

5.3 Squared Consine Scores

  • Question: Is the obs. \(i\) accurately represented by PC \(\color{red}{k}\)?
  • Answer: \(\cos^2(\text{x}_i, \color{red}{\text{PC}_k})=\frac{z_{i\color{red}{k}}^2}{\sum_{\color{purple}{p}=1}^nz_{i\color{purple}{p}}^2}=\frac{z_{i\color{red}{k}}^2}{\|z_i\|^2}\), with \(z_i=\color{blue}{U}^T\text{x}_i=\begin{pmatrix} \vdots \\ z_{i\color{red}{k}}\\ \vdots\end{pmatrix}\).
Code
Z2 = Z ** 2
cos2 = np.diag(1/Z2.sum(axis=1)) @ Z2 * 100
df_cos2 = pd.DataFrame(
    {
        'Representation score of obs. (PC1)': cos2.iloc[:,0],
        'Representation score of obs. (PC2)': cos2.iloc[:,1],
        'Individual': Z.index
    }
)
fig_cos2 = px.scatter(df_cos2, 
    x='Representation score of obs. (PC1)', y='Representation score of obs. (PC2)', 
    hover_name=df_cos2.Individual,
    size=[2]*df_cos2.shape[0],
    size_max=5,
    color=df_cos2['Representation score of obs. (PC1)']+df_cos2['Representation score of obs. (PC2)'])
fig_cos2.update_layout(
    {'paper_bgcolor': 'rgba(0,0,0,0)',
    'plot_bgcolor': 'rgba(0,0,0,0)'},
    height=250, width=460, 
    title=r"$\cos^2\text{ of observations on PCs}$")
fig_cos2.update_xaxes(
    showline=True, 
    linewidth=5, 
    linecolor='gray', 
    mirror=True,  # Mirrors the bottom x-axis line to the top
    showgrid=True, gridwidth=1, gridcolor=LIGHT_GRAY
)
fig_cos2.update_yaxes(
    showline=True, 
    linewidth=1, 
    linecolor='gray', 
    mirror=True,  # Mirrors the left y-axis line to the right
    showgrid=True, gridwidth=1, gridcolor=LIGHT_GRAY
)
fig_cos2.show()
  • Neighborhood 875 has highest \(\cos^2=\) 99.72% with PC1, i.e., it’s well represented/explained by PC1.
  • Neighborhood 18091 has highest \(\cos^2=\) 99.61% with PC2, i.e., it’s best explained by PC2.

6 Variable Clustering

6.1 Variable Clustering

  1. Start: Perform PCA on all variables \(\color{purple}{C}=[D_j]\) (1 cluster) to obtain eigenpairs: \(\color{blue}{U},\Sigma\). Let \(\color{purple}{d_C}=\#\color{purple}{C}\) and \(\color{blue}{U_2}=\color{blue}{U[:,:2]}\).
  2. While \(\lambda_2>\) MAXEIGEN do:
  • Orthoblique Rotatioin: Compute rotation matrix \(\color{red}{T}\in\mathbb{R}^{2\times 2}\) defined by \[\color{red}{T}=\arg\max_{V:V^TV=I_2}\sum_{i=1}^{\color{purple}{d_C}}\sum_{j=1}^2[\color{blue}{U_2}V]_{ij}^4.\]
  • Compute the rotated data: \(\color{red}{R}=\color{purple}{C}\color{red}{T}\).
  • Reassign variables to new cluster: For any variable \(D_j\):
    • If \(r^2(D_j,\color{red}{R}_1)>r^2(D_j,\color{red}{R}_2)\), then \(D_j\rightarrow C_1\),
    • else \(D_j\rightarrow C_2\).
  1. Set \(\color{purple}{C}\) to be each of the \(C_1\) and \(C_2\).
  2. Repeat 1-3.

Note: Common choices of MAXEIGEN are \(0.7\) or \(1.0\).

Summary of VARCLUS
  • It can helps mitigating severe multicollinearity, performing feature selection, enhacing model interpretability & deplolyment…
  • The performance may be different according to the stopping criterion.

Application

  • VARCLUS on California Housing Price dataset with MAXEIGEN = 0.7.
  • Here, the R-square scores are defined as:
    • \(\text{RS_own}_k(X_j)=\text{corr}^2(X_j,\text{PC1}_k)\),
    • \(\text{RS_NC}_k(X_j)=\max_{\ell\neq k}\{\text{corr}^2(X_j,\text{PC1}_\ell)\}\)
    • Unexplained variance: RS_Ratio\(=\frac{\text{RS_NC}}{\text{RS_own}+\text{RS_NC}}.\)
Code
from varclushi import VarClusHi
df_house = data[quan_cols[2:]]
scaler = StandardScaler().fit(df_house)
X = scaler.transform(df_house)
X = pd.DataFrame(X, columns=quan_cols[2:])
vc = VarClusHi(df=X, maxeigval2=0.7)
vc.varclus()
vc.rsquare
Cluster Variable RS_Own RS_NC RS_Ratio
0 0 total_rooms 0.919438 0.130053 9.260583e-02
1 0 total_bedrooms 0.961261 0.102689 4.317264e-02
2 0 population 0.886009 0.087490 1.249208e-01
3 0 households 0.970140 0.091668 3.287341e-02
4 1 median_income 0.844178 0.013990 1.580331e-01
5 1 median_house_value 0.844178 0.011328 1.576076e-01
6 2 housing_median_age 1.000000 0.109511 2.493512e-16

🥳 Yeahhhh….









Let’s Party… 🥂