Skip to content

Instantly share code, notes, and snippets.

@koorukuroo
Last active November 4, 2016 01:03
Show Gist options
  • Save koorukuroo/2e1d3dca779f0a22263e to your computer and use it in GitHub Desktop.
Save koorukuroo/2e1d3dca779f0a22263e to your computer and use it in GitHub Desktop.
Singular Value Decomposition Test
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 14 14:45:55 2014
@author: Kyunghoon
"""
import numpy as np
# Original Data Matrix
Original = np.matrix([[1,1,0,1],[7,0,0,7],[1,1,0,1],[2,5,3,6]])
print Original
U, Sigma, VT = np.linalg.svd(Original)
# Calculation with all singular value
Result = np.matrix(U)*np.matrix(np.diag(Sigma))*np.matrix(VT)
print np.round(Result).astype(np.int64)
# Calculation with 3 singular value
mU = U
mSigma = np.diag(np.append(Sigma[0:3],0))
mVT = VT
Result = mU*mSigma*mVT
print np.round(Result).astype(np.int64)
# Calculation with 2 singular value
mU = U
mSigma = np.diag(np.append(Sigma[0:2],[0,0]))
mVT = VT
Result = mU*mSigma*mVT
print np.round(Result).astype(np.int64)
# Calculation with 1 singular value
mU = U
mSigma = np.diag(np.append(Sigma[0:1],[0,0,0]))
mVT = VT
Result = mU*mSigma*mVT
print np.round(Result).astype(np.int64)
@koorukuroo
Copy link
Author

[[1 1 0 1]
 [7 0 0 7]
 [1 1 0 1]
 [2 5 3 6]]

[[1 1 0 1]
 [7 0 0 7]
 [1 1 0 1]
 [2 5 3 6]]

[[1 1 0 1]
 [7 0 0 7]
 [1 1 0 1]
 [2 5 3 6]]

[[1 1 0 1]
 [7 0 0 7]
 [1 1 0 1]
 [2 5 3 6]]

[[1 0 0 1]
 [5 3 1 7]
 [1 0 0 1]
 [4 2 1 6]]

>>> Sigma
array([  1.21809505e+01,   5.37084224e+00,   8.82325685e-01,
         1.08236251e-15])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment