In addition to polynomial fitting, which has the polyfit() function in Python, there exist techniques for fitting exponential and logarithmic curves.
To fit a curve to the model y = A B log x, we can transform the data by taking the logarithm of both sides, resulting in log y = log A B log x. By fitting log y against log x using polyfit(), we obtain the coefficients log A and B.
import numpy as np
x = np.array([1, 7, 20, 50, 79])
y = np.array([10, 19, 30, 35, 51])
coeffs = np.polyfit(np.log(x), y, 1)
print("Coefficients:", coeffs)
print("y ≈", coeffs[1], " ", coeffs[0], "log(x)")
To fit a curve to the model y = Ae^(Bx), we can take the logarithm of both sides, resulting in log y = log A B x. The parameters can then be determined by fitting log y against x using polyfit().
x = np.array([10, 19, 30, 35, 51])
y = np.array([1, 7, 20, 50, 79])
coeffs = np.polyfit(x, np.log(y), 1)
print("Coefficients:", coeffs)
print("y ≈", np.exp(coeffs[1]), "*", "exp(", coeffs[0], "x)")
It's worth noting that unweighted fitting (without considering the weights of the data points) can lead to bias towards small values, particularly in exponential curve fitting. To mitigate this, weights can be included in the fitting process, proportional to the y-values.
Scipy provides the curve_fit() function to perform nonlinear curve fitting. This allows us to fit any model directly, without transformations.
from scipy.optimize import curve_fit
# Logarithmic curve fitting
popt, pcov = curve_fit(lambda t, a, b: a b * np.log(t), x, y)
print("Coefficients:", popt)
print("y ≈", popt[1], " ", popt[0], "log(x)")
# Exponential curve fitting
popt, pcov = curve_fit(lambda t, a, b: a * np.exp(b * t), x, y, p0=(1, 0.1))
print("Coefficients:", popt)
print("y ≈", popt[0], "*", "exp(", popt[1], "x)")
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3