PCA-Based Dimensionality Reduction with Standardization

  • Share this:

Code introduction


This function uses PCA (Principal Component Analysis) to reduce the dimensionality of the data. First, it standardizes the data using StandardScaler, and then applies PCA to select the specified number of principal components.


Technology Stack : scikit-learn, numpy

Code Type : Function

Code Difficulty : Intermediate


                
                    
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import numpy as np

def reduce_dimensionality(data, n_components):
    # Standardize the data
    scaler = StandardScaler()
    scaled_data = scaler.fit_transform(data)
    
    # Apply PCA to reduce dimensionality
    pca = PCA(n_components=n_components)
    reduced_data = pca.fit_transform(scaled_data)
    
    return reduced_data