Fmin python传递参数

2024-03-28 23:00:48 发布

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

我想找到函数func\u exp的最小值。 这个函数有3个参数,我是通过拟合得到的。 然后我要求函数沿x轴的最小值(y)。使用拟合参数时。 为了这个,我试着用scipy的fin

但是,我似乎不太明白如何将参数传递给fin函数。 使用当前代码,我得到以下错误:

ValueError: setting an array element with a sequence.

对于任何帮助,我都很感激。你知道吗

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

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

class morse:
    def __init__(self):
        self.masses = {'H': 1, 'D': 2, 'C': 12, 'O': 16}

def exponential_regression (self,x_data, y_data):
    self.popt, pcov = curve_fit(func_exp, x, y, p0 = (0.5, 1.4, 3))
    print(self.popt)
    puntos = plt.plot(x, y, 'x', color='xkcd:maroon', label = "data")
    x_data= np.linspace(np.amax(x),np.amin(x),100)
    curva_regresion = plt.plot(x_data, func_exp(x_data, *self.popt), color='xkcd:teal', label = "fit: {:.3f}, {:.3f}, {:.3f}".format(*self.popt))
    plt.xlim([2, 5.5 ])
    plt.ylim([-5.5, 5 ])
    plt.legend()
    plt.show()
    return func_exp(x, *self.popt)

if __name__ == "__main__":
    x = np.array([2.5,3,3.125,3.25,3.375,3.5,3.625,3.75,4,4.5,5,5.5])
    y = np.array([17.27574826,-3.886390266,-4.892678401,-5.239229709,-5.193942987,-4.93131152,-4.557452444,-4.13446237,-3.276524893,-1.928242445,-1.17731394,-0.745240026])
    morse=morse()
    morse.exponential_regression(x, y)
    fmin(func_exp,x,args=(morse.popt[0],morse.popt[1],morse.popt[2]))

Tags: 函数importselfdata参数morsedefnp
1条回答
网友
1楼 · 发布于 2024-03-28 23:00:48

好的,我找到了解决办法。这里需要做的修改是只传递一个初始猜测值xfmin。你路过长度为12的x。你知道吗

替换

fmin(func_exp,x,args=(morse.popt[0],morse.popt[1],morse.popt[2]))

fmin(func_exp,x[0],args=(morse.popt[0],morse.popt[1],morse.popt[2]))

这里只使用x数组的第一个元素作为起点。你知道吗

也可以使用其他值作为x[1]x[-1],所有值都将收敛到最小值。函数现在将返回曲线具有最小值的x值。答案是

array([3.30895996])

相关问题 更多 >