非线性最小二乘拟合不最小化

2024-05-29 07:55:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用三个指数的和来拟合衰减,并使用下面的代码。从表面上看一切都很好,但优化并没有收敛(或为此做了任何事情)。当我调用lsq_res.x时,我可以看到参数与初始猜测相同。我怀疑最小化函数本身存在问题(def-fun(x,t,y):…),不确定是否正确传递了变量。非常感谢您的帮助,因为这也将允许我将此应用于其他型号

import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.optimize import least_squares

def Intensity(x_data, A21, T21, A22, T22, A23, T23, y0):
    I_model=A21*np.exp(-x_data/T21)+A22*np.exp(-x_data/T22)+A23*np.exp(-x_data/T23)+y0
    return I_model


#generate example data set (should be replaced by load of csv data file)
def gen_data(t, b1, c1, b2, c2, b3, c3, y0, noise=0, n_outliers=0, random_state=0):
    y = b1 * np.exp(-t / c1) + b2 * np.exp(-t / c2) + b3 * np.exp(-t / c3)+y0

    rnd = np.random.RandomState(random_state)
    error = noise * rnd.randn(t.size)
    outliers = rnd.randint(0, t.size, n_outliers)
    error[outliers] *= 10

    return y + error
# these are the parameters used to calculate the function, correspond to my first guess
y0 = 0.5
b1 = 0.25
c1 = .01
b2 = 0.4
c2 = .3
b3 = 0.35
c3 = 10

t_min = -3
t_max = 2
n_points = 1000

x_data = np.logspace(t_min, t_max, n_points)
y_data = gen_data(x_data, b1, c1, b2, c2, b3, c3, y0, noise=0.1, n_outliers=3) 

# the following is the minimization function where the appropriate model needs to be entered in the return line. 

def fun(x, t, y):
    return Intensity(x_data, A21, T21, A22, T22, A23, T23, y0) - y_data 
x0 = np.array([A21, T21, A22, T22, A23, T23, y0]) # give starting values for the fit parameters in the model


res_lsq = least_squares(fun, x0, args=(x_data, y_data)) #this performs the actual minimization of

y_lsq = gen_data(x_data, *res_lsq.x)

Tags: theimportdatamodeldefnplsqa21
1条回答
网友
1楼 · 发布于 2024-05-29 07:55:40

正如我看到的问题,您试图找到强度函数的最佳参数

我建议您使用scipy的曲线拟合功能

import numpy as np
from scipy.optimize import curve_fit

def Intensity(x_data, A21, T21, A22, T22, A23, T23, y0 ):
    I_model=A21*np.exp(-x_data/T21)+A22*np.exp(-x_data/T22)+A23*np.exp(-x_data/T23)+y0
    return I_model


#generate example data set (should be replaced by load of csv data file)
def gen_data(t, b1, c1, b2, c2, b3, c3, y0, noise=0, n_outliers=0, random_state=0):
    y = b1 * np.exp(-t / c1) + b2 * np.exp(-t / c2) + b3 * np.exp(-t / c3)+y0

    rnd = np.random.RandomState(random_state)
    error = noise * rnd.randn(t.size)
    outliers = rnd.randint(0, t.size, n_outliers)
    error[outliers] *= 10

    return y + error

#%%
# these are the parameters used to calculate the function, correspond to my first guess
y0 = 0.5
b1 = 0.25
c1 = .01
b2 = 0.4
c2 = .3
b3 = 0.35
c3 = 10

t_min = -3
t_max = 2
n_points = 1000

x_data = np.logspace(t_min, t_max, n_points)
y_data = gen_data(x_data, b1, c1, b2, c2, b3, c3, y0, noise=0.1, n_outliers=3)

res = curve_fit(Intensity, x_data, y_data) 

文档可以在here中找到。我希望我没有误解你的问题

如果要最小化函数,应提供静态参数值和变量的初始猜测。 在您的问题中,没有给出参数值

相关问题 更多 >

    热门问题