Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. def l2_rls_train(tr_data, tr_labels, regLambda, multiclass=False):
  2. """
  3. Add column of ones to tr_data, and calculate the optimal
  4. weight vector by setting th egradient to zero and using
  5. the matrix notation form to calculate the regularised least square model
  6.  
  7. data: type and description of "data"
  8. labels: type and description of "labels"
  9.  
  10. Returns: type and description of the returned variable(s).
  11. """
  12.  
  13. # This is just to be consistent with the lecture notes.
  14. X, y = tr_data, tr_labels
  15.  
  16. nrOfRows = X.shape[0]
  17.  
  18. # Expand X with a column of ones.
  19. X_tilde = np.column_stack((np.ones(nrOfRows), X))
  20.  
  21. # if multiclass change tr_labels into a matrix
  22. if multiclass:
  23. newY = np.zeros((tr_labels.shape[0], tr_labels.shape[0]))
  24. for i, el in enumerate(tr_labels):
  25. newY[i][el - 1] = 1
  26. y = newY
  27.  
  28. nrOfColumns = X_tilde.shape[1]
  29. # Compute the coefficient vector.
  30. if regLambda == 0:
  31. w = np.linalg.pinv(X_tilde) @ y
  32. else:
  33. inverse = np.linalg.inv(np.dot( np.transpose(X_tilde), X_tilde) + np.identity(nrOfColumns) * regLambda)
  34. w = np.dot( inverse, np.transpose(X_tilde) ) @ y
  35. # Return model parameters.
  36. return w
  37.  
  38. def l2_rls_predict(w, data):
  39. """
  40. A summary of your function goes here.
  41.  
  42. data: type and description of "data"
  43.  
  44. Returns: type and description of the returned variable(s).
  45. """
  46.  
  47. # This is just to be consistent with the lecture notes.
  48. X = data
  49.  
  50. # add column of ones (biases) to given data
  51. y = np.column_stack((np.ones(X.shape[0]), data))
  52. # Your code goes here
  53.  
  54. return np.dot(y, w)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement