Skip to main content

SVD and Truncated SVD Explained: Theory, Python Examples, and Applications in Machine Learning & Deep Learning

Singular Value Decomposition (SVD) is a matrix factorization method widely used in mathematics, engineering, and economics. Since it's a crucial concept applied in accelerating matrix computations and data compression, it's worth studying at least once.

SVD (Singular Value Decomposition) Theory

Singular Value Decomposition (SVD) is a matrix factorization technique applicable to any real or complex matrix. Any matrix A (m×n) can be decomposed as follows:

$A = U * \Sigma * V^T$

  • U: Orthogonal matrix composed of left singular vectors $(m \times m)$
  • Σ: Diagonal matrix $(m \times n)$ with singular values on the diagonal
  • $V^T$: Transposed matrix of right singular vectors $(n \times n)$

The singular values represent the energy or information content of matrix A, enabling tasks like dimensionality reduction or noise filtering.

Truncated SVD

Truncated SVD approximates the original matrix using only the top k singular values and corresponding singular vectors:

$A \approx U_k * \Sigma_k * V_k^T$

This technique is useful for reducing dimensionality while retaining most of the information, especially in sparse matrices, text data, and image processing.


Implementing SVD and Truncated SVD in Python

import numpy as np

def compute_svd(A):
    AT_A = np.dot(A.T, A)
    eigvals, V = np.linalg.eigh(AT_A)
    idx = np.argsort(eigvals)[::-1]
    eigvals = eigvals[idx]
    V = V[:, idx]
    singular_values = np.sqrt(eigvals)
    Σ = np.diag(singular_values)
    U = np.dot(A, V) / singular_values
    return U, Σ, V.T

A = np.array([[3, 2], [2, 3]])
U, Σ, VT = compute_svd(A)
print("U:\n", U)
print("Σ:\n", Σ)
print("V^T:\n", VT)

Output:

U:
 [[ 0.70710678 -0.70710678]
 [ 0.70710678  0.70710678]]
Σ:
 [[5. 0.]
 [0. 1.]]
V^T:
 [[ 0.70710678  0.70710678]
 [-0.70710678  0.70710678]]

Truncated SVD with Scikit-learn

from sklearn.decomposition import TruncatedSVD
import numpy as np

X = np.array([[3, 2, 2], [2, 3, -2]])
svd = TruncatedSVD(n_components=2)
X_reduced = svd.fit_transform(X)
print("Reduced X:\n", X_reduced)
print("Components:\n", svd.components_)

Output:

Reduced X:
 [[ 3.53553391  2.12132034]
 [ 3.53553391 -2.12132034]]
Components:
 [[ 7.07106781e-01  7.07106781e-01  4.33680869e-18]
 [ 2.35702260e-01 -2.35702260e-01  9.42809042e-01]]

Truncated SVD is particularly suitable for sparse data (e.g., TF-IDF matrices, user-item matrices), and unlike PCA, it does not require mean-centering the data.


Applications of Truncated SVD in Deep Learning / Machine Learning

1. Dimensionality Reduction

Used to compress high-dimensional data (e.g., text, images) into lower dimensions, reducing computation and improving generalization.

2. Natural Language Processing (NLP)

  • LSA (Latent Semantic Analysis): Applies Truncated SVD to a document-word matrix to extract semantic relationships between words.
  • Word Embedding Preprocessing: Used to reduce the dimensionality of vectors like FastText and GloVe for memory optimization.

3. Recommendation Systems

Truncated SVD is applied to sparse user-item matrices to learn latent factor models, used in systems like Netflix and YouTube.

4. Model Compression in Deep Learning

LoRA (Low-Rank Adaptation) is a technique for efficient fine-tuning of large language models (e.g., GPT, BERT). It approximates weight matrices using a low-rank form:

W ≈ W0 + A * B  # A and B are low-rank matrices

A and B are learnable, allowing quick adaptation without retraining the entire model. LoRA is a representative method inspired by the principles of SVD.

5. Vision Applications

Used to approximate convolutional weights in neural networks with low-rank matrices to reduce memory and computation costs.


References

Comments

Popular

How to Fine-Tune LLaMA 3.2-1B-Instruct for Korean Instruction Tasks with LoRA and Hugging Face

LLaMA 3.2-1B-Instruct is a lightweight instruction-tuned language model released by Meta. It is designed to handle a wide range of instruction-based tasks with relatively low computational resources. Although the model was trained with multilingual capabilities, its performance on languages not included in its training set—such as Korean—is limited. This tutorial demonstrates how to fine-tune this open-source model on a Korean dataset using Hugging Face Transformers and PEFT (specifically LoRA), enabling it to better respond to Korean instructions. 1. Prerequisites Before running the example code below, ensure you have the following libraries installed: pip install torch transformers datasets peft accelerate mlflow huggingface_hub To use the LLaMA model or KoAlpaca datasets, you'll need a Hugging Face token. Additionally, you may need to handle potential CUDA Out-Of-Memory (OOM) errors. The following code takes care of both: from huggingface_hub import login login("y...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...