user18624758
user18624758

Reputation:

Fit a curve to data in Python

I have a text file (plot.32.txt) with two columns containing the x and y values; I want to fit a curve to this dataset. The equation of the curve is:

y = (1/a)*np.exp((-x+b)/a)*np.exp(-np.exp((-x+a)/b))

where a and b are numbers. This code is all I have

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def frechet(x, a, b):
    return (1/a)*np.exp((-x+b)/a)*np.exp(-np.exp((-x+b)/a))

x5, y5=[], []

for line in open('plot.32.txt', 'r'):
    values=[float(s) for s in line.split()]
    x5.append(values[0])
    y5.append(values[1])
plt.plot(x5, y5, 'y.', label="32")
plt.xlabel("-ln(\u03B5)")
plt.ylabel("P(-ln(\u03B5))")
plt.xlim(0, 15)
plt.ylim(0, 0.35)
plt.legend()
plt.show()

How can I fit the curve?

Upvotes: 0

Views: 544

Answers (1)

Nin17
Nin17

Reputation: 3492

See the documentation for curve_fit https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html. You supply the function(independent, *parameters), independent variable and dependent data. The first element of the result is a list of the fitted parameters.

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
def frechet(x, a, b):
   return (1/a)*np.exp((-x+b)/a)*np.exp(-np.exp((-x+b)/a))

x5, y5=[], []
for line in open('plot.32.txt', 'r'):
    values=[float(s) for s in line.split()]
    x5.append(values[0])
    y5.append(values[1])

popt, pcov = curve_fit(frechet, x5, y5)
plt.plot(x5, y5, 'y.', label="32")
plt.plot(x5, frechet(x5, *popt))
plt.xlabel("-ln(\u03B5)")
plt.ylabel("P(-ln(\u03B5))")
plt.xlim(0, 15)
plt.ylim(0, 0.35)
plt.legend()
plt.show()
for i, (j, k) in enumerate(zip(popt, np.sqrt(np.diag(pcov)))):
   print(f'The optimal value for parameter {i} is: {j} ± {k}')

Making up some noisy data with:

x5 = np.linspace(0,10,100)
y5 = [frechet(i, 1, 4)+np.random.random()*1e-2 for i in x5]

Gives:

The optimal value for parameter 0 is: 0.9993058766043166 ± 0.004346296789517353
The optimal value for parameter 1 is: 4.000168590113876 ± 0.005228251104174721

enter image description here

Upvotes: 1

Related Questions