Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from sklearn import linear_model
- import numpy as np
- gamma = 0.5
- clf = linear_model.Lasso(alpha=gamma, fit_intercept=False)
- x = np.array([[1,3,4,2],[2,2,1,3],[2,1,33,1],[3,1,2,2]], dtype=float).T
- y = np.array([[5,7,6,8]], dtype=float).T
- clf.fit(x, y)
- print(clf.coef_)
- m = x.shape[0]
- n = x.shape[1]
- result = clf.coef_
- fitError = np.square(np.linalg.norm(np.dot(x,result)-y,2))/(2.0*m) + gamma * np.linalg.norm(result, 1)
- print "Fit error:", fitError
- [ 0.90047945 1.95962233 0.01235545 0. ]
- Fit error: 4.30144267082
- from cvxpy import *
- import numpy as np
- from sklearn import linear_model
- gamma = 0.5
- x = np.array([[1,3,4,2],[2,2,1,3],[2,1,33,1],[3,1,2,2]], dtype=float).T
- y = np.array([[5,7,6,8]], dtype=float).T
- m = x.shape[0]
- n = x.shape[1]
- # http://scikit-learn.org/stable/modules/linear_model.html#lasso
- w = Variable(n)
- cost = sum_squares(x*w - y)/(2.0*m) + gamma * norm(w, 1)
- prob = Problem(Minimize(cost), [])
- prob.solve()
- print "status:", prob.status
- print "optimal value (P*): ", prob.value
- print "optimal point (w*) transpose: ", w.value.T
- result = w.value
- fitError = np.linalg.norm(np.dot(x,result)-y)**2/(2.0*m) + gamma * np.linalg.norm(result, 1)
- print "Fit error %g:" % (fitError)
- status: optimal
- optimal value (P*): 1.46804740158
- optimal point (w*) transpose: [[ 8.98760414e-01 1.96090538e+00 1.25244441e-02 3.69147798e-10]]
- Fit error 1.46805:
Add Comment
Please, Sign In to add comment