使用 scipy curve_fit 的猜测

Using a guess with scipy curve_fit

我有一个函数,我想在知道曲线拟合误差的情况下进行曲线拟合。我正在尝试使用 scipy.optimize.curve_fit 来执行此操作,但 运行 遇到了问题。现在我的代码是:

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

pi = np.pi
sqrt = np.sqrt
mean = np.mean

A = 1
T_2 = 100
nu_0 = 10
phi_0 = 0
n = .001
nu_s = 500
T = 1000

t = np.linspace(0, T, num = (nu_s*T))

def S_n(A,t,T_2,nu_0,phi_0,n,nu_s,T):
    return (A/np.sqrt(2))*np.exp(-t/T_2)*np.cos(2*pi*nu_0*t+phi_0)

S = S_n(A,t,T_2,nu_0,phi_0,n,nu_s,T) + np.random.normal(0, n, nu_s*T)

guess = np.array([A,T_2,nu_0,phi_0,n,nu_s,T])
print guess

popt, pcov = curve_fit(S_n,t,S, guess)
print popt
perr = sqrt(np.diag(pcov))
print perr

这给了我无限的错误。我不确定我的猜测是否正确,因为在等式中,除 t 之外的所有内容都保持不变,所以我将 t 排除在我的猜测之外,因为它不再是一个数组,因为 t 是一个序列。当我将 t 排除在猜测之外时,我在这里所做的是,我收到的每个变量的值都与我最初给出的值相去甚远,并且出现无限错误。如果我在猜测中包含 t,则会出现错误。

您没有考虑 curve_fit 的参数顺序:

Definition: curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw)

Docstring: Use non-linear least squares to fit a function, f, to data.

Assumes ydata = f(xdata, *params) + eps

Parameters

f : callable The model function, f(x, ...). It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments.

如果你做一个函数:

def Sm(t, A,T_2,nu_0,phi_0,n,nu_s,T):
    return S_n(A, t, T_2,nu_0,phi_0,n,nu_s,T)

(注意前两个参数的顺序已经改变) 并将其传递给 curve_fit,它将起作用。

虽然清理你的原始函数可能更像 pythonic:

def S_n(t, A, T_2, nu_0, phi_0, n, nu_s, T):
    return (A/np.sqrt(2))*np.exp(-t/T_2)*np.cos(2*pi*nu_0*t+phi_0)

S = S_n(t, A, T_2, nu_0, phi_0, n, nu_s, T) + np.random.normal(0, n, nu_s*T)

然后你可以将S_n原样传递给curve_fit,以及Sguess

为了清楚起见,以下代码产生了所需的拟合:

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

def S_n(t, amplitude, sigma,freq0,phase):
    return (amplitude/np.sqrt(2))*np.exp(-t/sigma)*np.cos(2*np.pi*freq0*t+ phase)

amplitude = 1
sigma = 100
freq0 = 10
phase = 0
n = .001
sample_freq = 500
period = 1000

t = np.linspace(0, period, num = (sample_freq*period))
S = S_n(t, amplitude, sigma,freq0,phi_0) + np.random.normal(0, n, sample_freq*period)

guess = np.array([amplitude, sigma, freq0, phase ])
print guess
popt, pcov = curve_fit(S_n,t,S, guess)
print popt
print(np.all(np.isfinite(pcov)))
# output
[  1 100  10   0]
[  1.00000532e+00   1.00000409e+02   1.00000000e+01  -1.49076430e-05]
True