-1

How can I fit this function with two input variables using lmfit in python? function f(x) =a*(x - b)**2, a and b are variables and they can be a random number.

GreenROBO
  • 4,725
  • 4
  • 23
  • 43
fsrfyama
  • 325
  • 2
  • 13

1 Answers1

1

Can you try this?

import matplotlib.pyplot as plt
import numpy as np
from lmfit.models import ExpressionModel

# synthetic data
x = np.linspace(-10, 10, 100)
a,b = 0.9,1.9
y = a*(x-b)**2

# fit y using lmfit; with "guesses": a=1, b=2
gmod = ExpressionModel("a*(x-b)**2")
result = gmod.fit(y, x=x, a=1, b=2)

print(result.fit_report())

plt.plot(x, y, 'bo')
plt.plot(x, result.init_fit, 'k--', label='initial fit')
plt.plot(x, result.best_fit, 'r-', label='best fit')
plt.legend(loc='best')
plt.show()

Output: enter image description here

JP Maulion
  • 2,454
  • 1
  • 10
  • 13
  • It looks great. I also tried with defining some parameters (model.set_param_hint and model.make_params) and then fit it which can be an another solution but yours looks more understandable. – fsrfyama Mar 12 '20 at 10:33