最小化给出奇怪的结果(多参数拟合)

发布于 2025-01-17 12:50:42 字数 834 浏览 5 评论 0原文

我正在努力拟合实验数据。为了适应它,我使用残留功能的最小化。一切都很微不足道,但是这次我找不到出了什么问题,为什么配合的结果如此奇怪。与原始问题相比,简化了示例。但是无论如何,即使我将使用的参数值设置为初始猜测,它也会给出错误的参数。

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

x=np.arange(0,10,0.5)
a=0.5
b=3
ini_pars=[a, b]

def func(x, a, b):
    return a*x+b

plt.plot(x, func(x,a,b))
plt.show()

def fit(pars):
    A,B = pars
    res = (func(x,a, b)-func(x, *pars))**2
    s=sum(res)
    return s

bnds=[(0.1,0.5),(1,5)]
x0=[0.1,4]
opt = minimize(fit, x0, bounds=bnds)
new_pars=[opt.x[0], opt.x[0]]
example = fit(ini_pars)
print(example)
example = fit(new_pars)
print(example)
print(new_pars)


plt.plot(x, func(x, *ini_pars))
plt.plot(x, func(x, *new_pars))
plt.show()
```[enter image description here][1]


  [1]: https://i.sstatic.net/qc1Nu.png

I'm working on fitting of the experimental data. In order to fit it I use the minimization of the function of residual. Everything is quite trivial, but but this time I can't find what's wrong and why the result of fitting is so weird. The example is simplified in comparison with original problem. But anyway it gives wrong parameters even when I set used values of parameters as initial guess.

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

x=np.arange(0,10,0.5)
a=0.5
b=3
ini_pars=[a, b]

def func(x, a, b):
    return a*x+b

plt.plot(x, func(x,a,b))
plt.show()

def fit(pars):
    A,B = pars
    res = (func(x,a, b)-func(x, *pars))**2
    s=sum(res)
    return s

bnds=[(0.1,0.5),(1,5)]
x0=[0.1,4]
opt = minimize(fit, x0, bounds=bnds)
new_pars=[opt.x[0], opt.x[0]]
example = fit(ini_pars)
print(example)
example = fit(new_pars)
print(example)
print(new_pars)


plt.plot(x, func(x, *ini_pars))
plt.plot(x, func(x, *new_pars))
plt.show()
```[enter image description here][1]


  [1]: https://i.sstatic.net/qc1Nu.png

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨落画卷 2025-01-24 12:50:42

它应该是new_pars = [opt.x [0],opt.x [1]]而不是new_pars = [opt.x [0],opt.x [0]] < /代码>。还要注意,您可以通过new_pars = opt.x直接提取值。

It should be new_pars=[opt.x[0], opt.x[1]] instead of new_pars=[opt.x[0], opt.x[0]]. Note also that you can directly extract the values by new_pars = opt.x.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文