Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

trend_filtering.py 738 B

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  1. import numpy as np
  2. import cvxpy as cp
  3. import scipy as scipy
  4. def trend_filtering(y, vlambda, order=1):
  5. n = len(y)
  6. e = np.ones((1, n))
  7. if order == 1:
  8. D = scipy.sparse.spdiags(np.vstack((e, -2 * e, e)), range(3), n - 2, n)
  9. elif order == 2:
  10. D = scipy.sparse.spdiags(np.vstack((e, -3 * e, 3 * e, -e)), range(4), n - 3, n)
  11. elif order == 3:
  12. D = scipy.sparse.spdiags(np.vstack((e, -4 * e, 6 * e, -4 * e, e)), range(5), n - 4, n)
  13. else:
  14. raise Exception("order can only be 1-3")
  15. x = cp.Variable(shape=n)
  16. obj = cp.Minimize(0.5 * cp.sum_squares(y - x)
  17. + vlambda * cp.norm(D * x, 1))
  18. prob = cp.Problem(obj)
  19. prob.solve(solver=cp.OSQP)
  20. return x.value
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...