Python - curve_fitting 在高 x 值时无法正常工作

问题描述 投票:0回答:1

我有四个 XY 点,我需要获取曲线,因此我使用

scipy.optimize.curve_fit
。看看这些点,我想使用指数函数。这适用于较低的 x 值,但不适用于较高的 x 值。

代码如下(可以在

low_x_values
high_x_values
之间切换):

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

low_x_values = [3.139, 2.53, 0.821, 0.27]
high_x_values = [859.8791936328762, 805.5080517453312, 639.2578427310567, 496.3622821767497]

list_x = high_x_values
list_y = [0.21, 0.49, 1.56, 23.97]
    
def func_exp(x, a, b, c):
    return a + (b * np.exp(-c * x))

list_line_info, pcov = curve_fit(func_exp, list_x, list_y, maxfev=100000)

plot_x = np.linspace(min(list_x), max(list_x), 1000)
plot_y = list_line_info[0] + ((list_line_info[1]) * np.exp((-list_line_info[2] * plot_x)))

plt.plot(plot_x, plot_y, linestyle='-', color='orangered')
plt.plot(list_x, list_y, linestyle='--', color='dodgerblue')
plt.scatter(list_x, list_y, color='black', zorder=2)
plt.grid() 

当我想找到低值的曲线时,它显示:

但是,当我想对高值做同样的事情时,我得到了这个:

我不确定我在这里错过了什么。

python scipy curve-fitting
1个回答
0
投票

两个问题:

  1. 您尝试拟合的方程没有足够的自由度来拟合曲线。你的 x 值显示拟合需要改变,但你没有给它任何方法来做到这一点。我会将拟合函数更改为
    a + b*np.exp(-c*(x-d))
  2. 您应该给
    curve_fit
    一个很好的初步猜测。我通过在 Desmos 中绘制点并手动移动值直到它们有点接近(它不必是完美的,只要足够接近)就想出了一个。
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import numpy as np

low = False
low_x_values = [3.139, 2.53, 0.821, 0.27]
high_x_values = [859.8791936328762, 805.5080517453312,
                 639.2578427310567, 496.3622821767497]

list_x = low_x_values if low else high_x_values
list_y = [0.21, 0.49, 1.56, 23.97]


def func_exp(x, a, b, c, d):
    return a + b*np.exp(-c*(x-d))

p0 = (0.3,100,5,0) if low else (0, 900, 0.008, 10)
list_line_info, pcov = curve_fit(func_exp, list_x, list_y, p0=p0)

plot_x = np.linspace(min(list_x), max(list_x), 1000)
plot_y = func_exp(plot_x, *list_line_info)

plt.plot(plot_x, plot_y, linestyle="-", color="orangered")
plt.plot(list_x, list_y, linestyle="--", color="dodgerblue")
plt.scatter(list_x, list_y, color="black", zorder=2)
plt.grid()

© www.soinside.com 2019 - 2024. All rights reserved.