Scipy curve_fit 对简单数据使用边界和初始参数的混淆

Scipy curve_fit confusion using bounds and initial parameters on simple data

虽然我已经非常适合其他数据集,但出于某种原因,以下代码不适用于一组相对简单的点。我已经尝试了衰减指数和幂,以及初始参数和界限。我相信这暴露了我更深层次的误解;我很感激任何建议。

    snr = [1e10, 5, 1, .5, .1, .05]
    tau = [1, 8, 10, 14, 35, 80]

    fig1, ax1 = plt.subplots()

    def fit(x, a, b, c): #c: asymptote
        #return a * np.exp(b * x) + 1.
        return np.power(x,a)*b + c

    xlist = np.arange(0,len(snr),1)
    p0 = [-1., 1., 1.]
    params = curve_fit(fit, xlist, tau, p0)#, bounds=([-np.inf, 0., 0.], [0., np.inf, np.inf]))

    a, b, c = params[0]
    print(a,b,c)
    ax1.plot(xlist, fit(xlist, a, b, c), c='b', label='Fit')

    #ax1.plot(snr, tau, zorder=-1, c='k', alpha=.25)
    ax1.scatter(snr, tau)
    ax1.set_xscale('log')        
    #ax1.set_xlim(.02, 15)
    plt.show()

更新一:参考图,按照Eric M的代码: 会在下方post评论。


修复更新 1: xlist = np.arange(0.01,10000,1)/1000+0.01

这对我有用。有几个问题。包括我的评论。你的 xlist 中也有一个 'divide by zero' 错误,所以我通过将 0.01 添加到 xlist 并增加点的密度使曲线变圆来避免这种情况。

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

snr = [1e10, 5, 1, .5, .1, .05]
tau = [1, 8, 10, 14, 35, 80]

fig1, ax1 = plt.subplots()

def fit(x, a, b, c):
    return np.power(x, a)*b + c

xlist = np.arange(0.01,10000,1)/1000+0.01
xlist = np.append(xlist, 1e10)
p0 = [-10, 10., 1.]
params = curve_fit(fit, snr, tau, p0)

print('Fitting parameters: {}'.format(params[0]))
ax1.plot(xlist, fit(xlist, *params[0]), c='b', label='Fit')
ax1.scatter(snr, tau)
ax1.set_xscale('log')        
plt.show()

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


def fit(x, a, b, c):
    return np.power(x, a)*b + c


x = [1e10, 5, 1, .5, .1, .05]
y = [1, 8, 10, 14, 35, 80]

popt, pcov=curve_fit(fit,x,y, bounds=([-np.inf, 0., 0.], [0., np.inf, np.inf]))
x_curve = np.append(np.linspace(0.01, 10, 1000), 1e11)

# plot
fig, ax = plt.subplots()
ax.set_ylim(-25,100)
ax.set_xscale("log")
ax.scatter(x, y)
plt.plot(x_curve, np.power(x_curve, popt[0])*popt[1] + popt[2], color = 'green')
plt.show()

输出: