Advertisement
Guest User

Untitled

a guest
Jan 11th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 1.11 KB | None | 0 0
  1. # CROSS VALIDATION FOR CHOOSING SIGMA AND LAMBDA
  2. using Random
  3.  
  4. function CV(X, n)
  5.     # Random permutation for shuffle
  6.     rng = MersenneTwister(1234);
  7.     rndInd = randperm(n)
  8.     mid = floor(Int, n/2)
  9.  
  10.     # Random shuffle, using the same permutation to conserve correct labels
  11.     Xshuffle, yshuffle = X[rndInd], y[rndInd]
  12.  
  13.     # Dividing into train and validation set
  14.     Xtrain, ytrain = Xshuffle[1:mid,:], yshuffle[1:mid]
  15.     Xvali, yvali = Xshuffle[mid+1:end,:], yshuffle[mid+1:end]
  16.  
  17.     # Iterating through different combinations of sigma and lambda
  18.     bestError = Inf
  19.     bestLambda = 0
  20.     bestSigma = 0
  21.  
  22.     for lambda in 1:100
  23.         for sigma in 1:100
  24.             model = leastSquaresRBFL2(Xtrain,ytrain,lambda,sigma)
  25.             t = size(Xvali,1)
  26.             yhat = model.predict(Xvali)
  27.             testError = sum((yhat - yvali).^2)/t
  28.             if testError < bestError
  29.                 bestError = testError
  30.                 bestLambda = lambda
  31.                 bestSigma = sigma
  32.             end
  33.         end
  34.     end
  35.     return (bestError, bestSigma, bestLambda)
  36. end
  37.  
  38. show(CV(X,n))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement