简体   繁体   English

如何使用 Scipy curve_fit 获取日志 function 拟合数据

[英]How to get a log function fit using Scipy curve_fit for the data

I am trying to get a*log(b/x)^c type fit for the following data (simplified for 10 data points)我正在尝试让 a*log(b/x)^c 类型适合以下数据(简化为 10 个数据点)

I have tried methods described in some other questions like this one using both curve_fit and lmfit but the solution never converges.我已经尝试过使用curve_fit和lmfit在其他一些问题中描述的方法,但解决方案永远不会收敛。 My guess is that my initial conditions are bad.我的猜测是我的初始条件很糟糕。 I was able to get the other exponential function commented out fit but the application requires a log fit of the form given.我能够得到另一个指数 function 注释掉适合,但应用程序需要给定形式的对数适合。 The data with the fit that works is attached for reference.附上适合的数据以供参考。

import numpy as np
from scipy.optimize import curve_fit


x=[0, 0.89790454, 1.79580908, 2.69371362, 3.59161816, 4.48952269, 5.38742723, 6.28533177, 7.18323631, 8.08114085]
y=[0.39599324, 0.10255828, 0.07094521, 0.05500624, 0.04636146, 0.04585985,  0.0398909,  0.03340628, 0.03041699, 0.02498938]
x = np.array(x,dtype=float) 
y = np.array(y,dtype=float)


def func(x, a, b, c):
    #return a*np.exp(-c*(x*b))+d

    return a*(np.log(b/x)**c)

popt, pcov = curve_fit(func, x, y, p0=[.5,.5,1],maxfev=10000)

print(popt)

a,b ,c = np.asarray(popt)

指数拟合衰减函数图供参考

Replace your function with,将您的 function 替换为,

def func(x, a, b, c):
    #return a*np.exp(-c*(x*b))+d
    t1 = np.log(b/x)
    t2 = a*t1**c
    print(a,b,c,t1, t2)
    return t;

Yow will rapidly see that t1 = np.log(b / x) may be negative (this happens whenever b < x).你会很快看到t1 = np.log(b / x)可能是负数(只要 b < x 就会发生这种情况)。 A power of a negative number to a non-integer power is not a real number, and here numpy is producing nan results.负数到非整数幂的幂不是实数,这里 numpy 产生nan结果。

I have no difficukty with my fitting software (result below).我对我的拟合软件没有任何困难(结果如下)。

Often a cause of difficulty with non-linear fitting using iterative method of regression is the setting of initial values of the parameters to start the iterative process.使用回归的迭代方法进行非线性拟合的困难原因通常是设置参数的初始值以启动迭代过程。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM