Advertisement
Guest User

Untitled

a guest
Nov 25th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 2.07 KB | None | 0 0
  1. # Code Question 1
  2. # Takes a residual matrix R and (element wise) calculates the huber loss
  3. function huberify(R,e)
  4.     HR = huberloss.(R,e)
  5. end
  6.  
  7. function huberloss(r, e)
  8.     if (abs(r) < e)
  9.         return (1/2)r^2
  10.     else
  11.         return e*(abs(r) - (1/2)*e)
  12.     end
  13. end
  14.  
  15. function robustPCA(X,k)
  16.     (n,d) = size(X)
  17.     e = 0.01
  18.  
  19.     # Subtract mean
  20.     mu = mean(X,dims=1)
  21.     X -= repeat(mu,n,1)
  22.  
  23.     # Initialize W and Z
  24.     W = randn(k,d)
  25.     Z = randn(n,k)
  26.  
  27.     R = Z*W - X
  28.     f = sum(huberify(R,e))
  29.     funObjZ(z) = pcaObjZHuber(z,X,W,e)
  30.     funObjW(w) = pcaObjWHuber(w,X,Z,e)
  31.     for iter in 1:50
  32.         fOld = f
  33.  
  34.         # Update Z
  35.         Z[:] = findMin(funObjZ,Z[:],verbose=false,maxIter=10)
  36.  
  37.         # Update W
  38.         W[:] = findMin(funObjW,W[:],verbose=false,maxIter=10)
  39.  
  40.         R = Z*W - X
  41.         f = sum(R.^2)
  42.         @printf("Iteration %d, loss = %f\n",iter,f/length(X))
  43.  
  44.         if (fOld - f)/length(X) < 1e-2
  45.             break
  46.         end
  47.     end
  48.  
  49.  
  50.     # We didn't enforce that W was orthogonal so we need to optimize to find Z
  51.     compress(Xhat) = compress_gradientDescent(Xhat,W,mu)
  52.     expand(Z) = expandFunc(Z,W,mu)
  53.  
  54.     return CompressModel(compress,expand,W)
  55. end
  56.  
  57. function pcaObjZHuber(z,X,W,e)
  58.     # Rezie vector of parameters into matrix
  59.     n = size(X,1)
  60.     k = size(W,1)
  61.     Z = reshape(z,n,k)
  62.  
  63.     # Comptue function value
  64.     R = Z*W - X
  65.     HR = huberify(R,e)
  66.     f = sum(HR)
  67.  
  68.     # Comptue derivative with respect to each residual
  69.     dR = R
  70.  
  71.     # Multiply by W' to get elements of gradient
  72.     G = HR*W'
  73.  
  74.    # Return function and gradient vector
  75.    return (f,G[:])
  76. end
  77.  
  78. function pcaObjWHuber(w,X,Z,e)
  79.    # Rezie vector of parameters into matrix
  80.    d = size(X,2)
  81.    k = size(Z,2)
  82.    W = reshape(w,k,d)
  83.  
  84.    # Comptue function value
  85.    R = Z*W - X
  86.    HR = huberify(R, e)
  87.    f = sum(HR)
  88.  
  89.    # Comptue derivative with respect to each residual
  90.    dR = R
  91.  
  92.    # Multiply by Z' to get elements of gradient
  93.     G = Z'HR
  94.  
  95.    # Return function and gradient vector
  96.    return (f,G[:])
  97. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement