【问题标题】:How for find x for a fitted exponential function?如何找到拟合指数函数的 x?
【发布时间】:2018-01-27 09:30:11
【问题描述】:
fp.append(np.polyfit(train_x, train_y, 2))
f.append(np.poly1d(fp))
print(np.poly1d(fp))
threshold = fsolve(f, 50)

上面的代码成功地找到了 y=50 的 x 值。但是当我尝试对拟合指数函数做同样的事情时,我不明白该怎么做。

def f_exp(x, a, b, c):
    y = a * np.exp(-b * x) + c
    return y
popt, pcov = curve_fit(f_exp, train_x, train_y)
print(popt)
threshold = fsolve(f_exp, 50) fails with  :TypeError: f_exp() missing 3 required positional arguments: 'a', 'b', and 'c'

如果我添加 *popt 那么我得到

threshold = fsolve(f_exp(*popt), 50) fails with: TypeError: f_exp() missing 1 required positional argument: 'c'

我假设我需要添加 x 值,但这是我试图找到的值...无论如何,添加一些值而不是 x 会导致另一个错误:

threshold = fsolve(f_exp(1, *popt), 50) fails with: TypeError: 'numpy.float64' object is not callable

【问题讨论】:

    标签: python numpy machine-learning scipy mathematical-optimization


    【解决方案1】:

    我猜您需要将带有优化参数的f_exp 函数传递给fsolve(即,将a、b 和c 参数设置为从curve_fit 获得的值)。为此,您可以使用functools.partial 函数:

    popt, pcov = curve_fit(f_exp, train_x, train_y)
    print(popt)
    import functools
    # preparing arguments
    kwargs = dict(zip(['a', 'b', 'c'], popt))
    optimized_f_exp = functools.partial(f_exp, **kwargs)
    threshold = fsolve(optimized_f_exp, 50)
    

    我们在这里所做的基本上是通过将原始函数的 abc args 部分修复为 popt 来创建一个新函数 optimized_f_exp(这正是它为什么称为 partial )。

    【讨论】:

    • 谢谢它有效。到目前为止,我还没有理解所有代码行。将阅读手册。
    猜你喜欢
    • 2013-01-31
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多