Skip to content

Instantly share code, notes, and snippets.

@tam17aki
Last active December 18, 2024 12:37
Show Gist options
  • Save tam17aki/b45462b3367b6170a602d595d7ca55d1 to your computer and use it in GitHub Desktop.
Save tam17aki/b45462b3367b6170a602d595d7ca55d1 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""A demonstration script for robust PCA.
Copyright (C) 2024 by Akira TAMAMORI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import sys
import cvxpy as cp
import matplotlib.pyplot as plt
import numpy as np
import numpy.typing as npt
import scipy.linalg
def decomposition(
dense: npt.NDArray[np.float64], lambda_: float
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
"""Decompose dense matrix into low-rank matrix and sparse matrix.
Args:
dense (ndarray): dense matrix.
lambda_ (float): regularization parameter.
Returns:
low_rank (ndarray): low-rank matrix.
sparse (ndarray): sparse matrix.
"""
m, n = dense.shape
low_rank = cp.Variable((m, n))
sparse = cp.Variable((m, n))
objective = cp.Minimize(cp.norm(low_rank, "nuc") + lambda_ * cp.norm(sparse, 1))
problem = cp.Problem(objective, [low_rank + sparse == dense])
problem.solve()
if low_rank.value is None or sparse.value is None:
print("L and S must not be None.")
sys.exit()
else:
return low_rank.value, sparse.value
def main():
"""Perform robust PCA."""
# サンプルデータ作成 (外れ値を含む)
x = np.random.rand(100, 2)
data = np.concatenate((x, np.array([[5, 10], [11, 10], [10, 11]]))) # 外れ値を追加
# 低ランク成分とスパース成分に分解
lambda_ = 0.2 # 正則化パラメータ
low_rank, sparse = decomposition(data, lambda_)
# 低ランク成分による次元削減(PCAと同様の処理)
u, sigma, v = scipy.linalg.svd(low_rank) # 特異値分解
sigma = np.diag(sigma) # 特異値を対角行列にする
reduced_dimension = 1 # 削減後の次元数
reduced_sigma = sigma[:reduced_dimension, :reduced_dimension]
reduced_data = u[:, :reduced_dimension] @ reduced_sigma @ v[:reduced_dimension, :]
# 可視化
plt.figure(figsize=(6, 8))
plt.subplot(3, 2, 1)
plt.scatter(x[:, 0], x[:, 1])
plt.title("Original data")
plt.subplot(3, 2, 2)
plt.scatter(data[:, 0], data[:, 1])
plt.title("Original data w/ Outliers (D)")
plt.subplot(3, 2, 3)
plt.scatter(low_rank[:, 0], low_rank[:, 1])
plt.title("Low-rank component (L)")
plt.subplot(3, 2, 4)
plt.scatter(sparse[:, 0], sparse[:, 1])
plt.title("Sparse component (S)")
plt.subplot(3, 2, 5)
plt.scatter(low_rank[:, 0] + sparse[:, 0], low_rank[:, 1] + sparse[:, 1])
plt.title("Reconstructed Data (L + S)")
plt.subplot(3, 2, 6)
plt.scatter(reduced_data[:, 0], np.zeros_like(reduced_data[:, 0]))
plt.title("Reduced data after RPCA")
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment