|
| 1 | +import numpy as np |
| 2 | +from scipy.optimize import differential_evolution |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +import pwlf |
| 5 | + |
| 6 | +x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 7 | +y = [1, 2, 3, 4, 4.25, 3.75, 4, 5, 6, 7] |
| 8 | + |
| 9 | +my_pwlf = pwlf.PiecewiseLinFit(x, y, degree=1) |
| 10 | + |
| 11 | +# perform initial fit |
| 12 | +breaks = my_pwlf.fit(2) |
| 13 | + |
| 14 | + |
| 15 | +def my_fun(beta): |
| 16 | + # assing variables to the pwlf object |
| 17 | + my_pwlf.beta[0] = beta[0] # first line offset |
| 18 | + my_pwlf.beta[1] = beta[1] # first line slope |
| 19 | + my_pwlf.beta[2] = -1*beta[1] |
| 20 | + my_pwlf.fit_breaks[1] = beta[2] # breakpoint |
| 21 | + # generate predictions |
| 22 | + y_temp = my_pwlf.predict(my_pwlf.x_data) |
| 23 | + # compute ssr |
| 24 | + e = y_temp - my_pwlf.y_data |
| 25 | + return np.dot(e, e) |
| 26 | + |
| 27 | + |
| 28 | +bounds = np.zeros((3, 2)) |
| 29 | +# first line offset |
| 30 | +bounds[0, 0] = -10.0 # lower bound |
| 31 | +bounds[0, 1] = 10.0 # upper bound |
| 32 | +# first line slope |
| 33 | +bounds[1, 0] = -10.0 # lower bound |
| 34 | +bounds[1, 1] = 10.0 # upper bound |
| 35 | +# breakpont |
| 36 | +bounds[2, 0] = 2. # lower bound |
| 37 | +bounds[2, 1] = 6. # upper bound |
| 38 | + |
| 39 | +res = differential_evolution(my_fun, bounds, maxiter=1000, popsize=30, |
| 40 | + disp=True) |
| 41 | + |
| 42 | +# assign optimum to my_pwlf object |
| 43 | +my_fun(res.x) |
| 44 | + |
| 45 | +# generate predictions |
| 46 | +x_hat = np.linspace(min(x), max(x), 1000) |
| 47 | +y_hat = my_pwlf.predict(x_hat) |
| 48 | + |
| 49 | +plt.figure() |
| 50 | +plt.plot(x, y, 'o') |
| 51 | +plt.plot(x_hat, y_hat) |
| 52 | +plt.show() |
0 commit comments