问题
I am having trouble in understanding the optimize.curve_fit
function. My fitting function is a power law. But I don't know exactly what should be the second value in the plot command? First we have to call function ff(L,v)
it will return us fitting line but we are not calling this function. How this command is working I want to know that.
x=Ls
y=Tc
#fitting function
def ff(L,v):
return L**(-1/v)
pfit,perr=optimize.curve_fit(ff,x,y)
plt.plot(x,...)
回答1:
The plot
command plots x vs y values, so you have to calculate the corresponding y-values according to your defined function ff
. Since pfit
is returned as an array, you have to unpack the values when you call your fit function ff
. If you know, that you have two coefficients, you could of course simply extract them like v, k = pfit
and calculate the y-values with ff(x, v, k)
. But what if you change the fit function later on to L**(-1/v) * k + a
? Then you would have to rewrite your code. An easier way is to leave it to Python to unpack your coefficients with *pfit
:
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
import numpy as np
#define some sample data
x = np.arange(1, 6)
y = np.asarray([100, 37, 18, 3, 1])
#fitting function with more than one parameter to fit
def ff(L, v, k):
return L**(-1/v) * k
pfit, perr = curve_fit(ff,x,y)
print(pfit)
#plot original data
plt.plot(x, y, "ro", label = "data")
#calculate y-values
y_fit = ff(x, *pfit)
#plot fitted curve
plt.plot(x, y_fit, "b", label = "fit")
plt.legend()
plt.show()
This is of course less than impressive, the fitted curve doesn't look smooth at all:
To overcome this, we might want to create an x-value range with a better resolution and plot this one instead of the original x-value data:
x_fit = np.linspace(np.min(x), np.max(x), 1000)
plt.plot(x_fit, ff(x_fit, *pfit), "b", label = "fit")
Much better now:
来源:https://stackoverflow.com/questions/51230301/plotting-graph-using-scipy-optimize-curve-fit