1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
| import time import numpy as np from numpy.linalg import norm
from random import normalvariate from math import sqrt
def randomUnitVector(n): unnormalized = [normalvariate(0, 1) for _ in range(n)] theNorm = sqrt(sum(x * x for x in unnormalized)) return [x / theNorm for x in unnormalized]
def svd_1d(A, epsilon=1e-10): ''' The one-dimensional SVD '''
n, m = A.shape x = randomUnitVector(min(n,m)) lastV = None currentV = x
if n > m: B = np.dot(A.T, A) else: B = np.dot(A, A.T)
iterations = 0 while True: iterations += 1 lastV = currentV currentV = np.dot(B, lastV) currentV = currentV / norm(currentV)
if abs(np.dot(currentV, lastV)) > 1 - epsilon: print("converged in {} iterations!".format(iterations)) return currentV
def svd(A, k=None, epsilon=1e-10): ''' Compute the singular value decomposition of a matrix A using the power method. A is the input matrix, and k is the number of singular values you wish to compute. If k is None, this computes the full-rank decomposition. ''' A = np.array(A, dtype=float) n, m = A.shape svdSoFar = [] if k is None: k = min(n, m)
for i in range(k): matrixFor1D = A.copy()
for singularValue, u, v in svdSoFar[:i]:
matrixFor1D -= singularValue * np.outer(u, v)
if n > m: v = svd_1d(matrixFor1D, epsilon=epsilon) u_unnormalized = np.dot(A, v) sigma = norm(u_unnormalized) u = u_unnormalized / sigma else: u = svd_1d(matrixFor1D, epsilon=epsilon) v_unnormalized = np.dot(A.T, u) sigma = norm(v_unnormalized) v = v_unnormalized / sigma
svdSoFar.append((sigma, u, v))
singularValues, us, vs = [np.array(x) for x in zip(*svdSoFar)] return singularValues, us.T, vs
def QR_HouseHolder(mat: np.array): cols = mat.shape[1]
Q = np.eye(cols) R = np.copy(mat)
for col in range(cols - 1): a = np.linalg.norm(R[col:, col]) e = np.zeros((cols - col)) e[0] = 1.0 num = R[col:, col] - a * e den = np.linalg.norm(num)
u = num / den H = np.eye(cols) H[col:, col:] = np.eye((cols - col)) - 2 * u.reshape(-1, 1).dot(u.reshape(1, -1)) R = H.dot(R)
Q = Q.dot(H)
return Q, R
def QR_GivenRot(mat: np.array): rows, cols = mat.shape
R = np.copy(mat) Q = np.eye(cols)
for col in range(cols): for row in range(col + 1, rows): if abs(R[row, col]) < 1e-6: continue
f = R[col, col] s = R[row, col] den = np.sqrt(f * f + s * s) c = f / den s = s / den
T = np.eye(rows) T[col, col], T[row, row] = c, c T[row, col], T[col, row] = -s, s
R = T.dot(R)
Q = T.dot(Q)
return Q.T, R
def QR_Basic(mat: np.array): eig = np.copy(mat)
rows, cols = mat.shape eigV = np.eye(cols) for _ in range(50): q, r = QR_HouseHolder(eig) eig = r.dot(q) eigV = eigV.dot(q)
return np.diag(eig), eigV
def QR_Heisenberg(mat: np.array): rows, cols = mat.shape Hsbg = np.copy(mat)
eigv = np.eye(cols) for row in range(1, rows - 1): array = mat[row:, row - 1]
a = np.linalg.norm(array)
e = np.zeros((1, rows - row))[0] e[0] = 1.0 num = array - a * e u = num / np.linalg.norm(num)
H = np.eye(rows - row) - 2 * u.reshape(-1, 1).dot(u.reshape(1, -1))
T = np.eye(rows) T[row:, row:] = H
Hsbg = T.T.dot(Hsbg).dot(T) eigv = eigv.dot(T.T)
eigv = eigv.T for _ in range(50): q, r = QR_GivenRot(Hsbg) Hsbg = r.dot(q) eigv = eigv.dot(q) return np.diag(Hsbg), eigv
def Jacobi_Basic(mat: np.array): rows, cols = mat.shape
eig = np.copy(mat) eigV = np.eye(rows, cols)
for _ in range(300): maxRow, maxCol = 0, 0 maxValue = -1 for row in range(rows): for col in range(cols): if row == col: continue if abs(eig[row, col]) > maxValue: maxValue = abs(eig[row, col]) maxRow = row maxCol = col a = 0 if abs(eig[maxRow, maxRow] - eig[maxCol, maxCol]) < 1e-5: a = 0.25 * np.pi else: a = 0.5 * np.arctan((2 * eig[maxRow, maxCol]) / (eig[maxRow, maxRow] - eig[maxCol, maxCol]))
P = np.eye(rows) P[maxRow, maxRow] = np.cos(a) P[maxCol, maxCol] = np.cos(a) P[maxRow, maxCol] = -np.sin(a) P[maxCol, maxRow] = np.sin(a) eig = P.T.dot(eig).dot(P) eigV = eigV.dot(P)
return np.diag(eig), eigV
def SortEig(eig, eigV): e = np.copy(eig) v = np.copy(eigV) print(e); indices = np.argsort(e) print(indices); e = np.sort(e)
for i, j in enumerate(indices): v[:, i] = eigV[:, j]
return e, v
def SVD_Solver(mat, Func): aTa = mat.T.dot(mat) aaT = mat.T.dot(mat) print(f"Ata:{ aTa}" ) eig, eigv = Func(aTa)
eig, eigv = SortEig(eig, eigv)
rows, cols = mat.shape U = eigv S = np.zeros_like(mat) for i in range(rows): S[i, i] = eig[i]
eig, eigv = Func(aaT) eig, eigv = SortEig(eig, eigv) V = eigv
return U, np.sqrt(S), V
def SVD1(mat: np.array, Method: int): U, S, V = SVD_Solver(mat, Jacobi_Basic)
return U, S, V
mat = np.array([[3.0, 2.0, 2.0], [2.0, 5.0, 1.0], [2.0, 1.0, 4.0], ])
start_time = time.perf_counter()
end_time = time.perf_counter() usetime = end_time - start_time
start_time = time.perf_counter() u, s, v = svd(mat) end_time = time.perf_counter() usetime = end_time - start_time print(f"Method Jacobi_Basic use: {usetime}" ) print(s)
start_time = time.perf_counter() u, s, v = np.linalg.svd(mat) end_time = time.perf_counter() usetime = end_time - start_time print(f"Method Real use: {usetime}")
print(u) print(s) print(v)
|