Advertisement
Guest User

Untitled

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