Guest User

Untitled

a guest
Nov 19th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. from sklearn import linear_model
  2. import numpy as np
  3.  
  4. gamma = 0.5
  5.  
  6. clf = linear_model.Lasso(alpha=gamma, fit_intercept=False)
  7. x = np.array([[1,3,4,2],[2,2,1,3],[2,1,33,1],[3,1,2,2]], dtype=float).T
  8. y = np.array([[5,7,6,8]], dtype=float).T
  9.  
  10. clf.fit(x, y)
  11. print(clf.coef_)
  12. m = x.shape[0]
  13. n = x.shape[1]
  14. result = clf.coef_
  15.  
  16. fitError = np.square(np.linalg.norm(np.dot(x,result)-y,2))/(2.0*m) + gamma * np.linalg.norm(result, 1)
  17. print "Fit error:", fitError
  18.  
  19. [ 0.90047945 1.95962233 0.01235545 0. ]
  20. Fit error: 4.30144267082
  21.  
  22. from cvxpy import *
  23. import numpy as np
  24. from sklearn import linear_model
  25.  
  26. gamma = 0.5
  27.  
  28. x = np.array([[1,3,4,2],[2,2,1,3],[2,1,33,1],[3,1,2,2]], dtype=float).T
  29. y = np.array([[5,7,6,8]], dtype=float).T
  30. m = x.shape[0]
  31. n = x.shape[1]
  32.  
  33. # http://scikit-learn.org/stable/modules/linear_model.html#lasso
  34. w = Variable(n)
  35. cost = sum_squares(x*w - y)/(2.0*m) + gamma * norm(w, 1)
  36. prob = Problem(Minimize(cost), [])
  37. prob.solve()
  38. print "status:", prob.status
  39. print "optimal value (P*): ", prob.value
  40. print "optimal point (w*) transpose: ", w.value.T
  41.  
  42. result = w.value
  43. fitError = np.linalg.norm(np.dot(x,result)-y)**2/(2.0*m) + gamma * np.linalg.norm(result, 1)
  44.  
  45. print "Fit error %g:" % (fitError)
  46.  
  47. status: optimal
  48. optimal value (P*): 1.46804740158
  49. optimal point (w*) transpose: [[ 8.98760414e-01 1.96090538e+00 1.25244441e-02 3.69147798e-10]]
  50. Fit error 1.46805:
Add Comment
Please, Sign In to add comment