Home > Article > Backend Development > How do you perform exponential and logarithmic curve fitting in Python beyond polynomial fitting?
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.
<code class="python">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)")</code>
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().
<code class="python">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)")</code>
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.
<code class="python">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)")</code>
The above is the detailed content of How do you perform exponential and logarithmic curve fitting in Python beyond polynomial fitting?. For more information, please follow other related articles on the PHP Chinese website!