替代scipy.optimize.curve_fit

And*_*rew 6 python numpy matplotlib scipy

我试图用matplotlib绘制一些可视化,并在我的一个函数中,我检查波是否是对数.这是我目前的工作版本:

import numpy as np
def is_logarithmic(waves):

    def expfunc(x, a, b, c):
        return a*np.exp(b*x) + c

    wcopy = list(waves)
    wcopy.sort()

    # If the ratio of x-max : x-min < 10, don't use a logarithmic scale
    # (at least in matplotlib)
    if (wcopy[-1] / wcopy[0]) < 10:
        return False

    # Take a guess at whether it is logarithmic by seeing how well the x-scale
    # fits an exponential curve
    diffs = []
    for ii in range(len(wcopy) - 1):
        diffs.append(wcopy[ii + 1] - wcopy[ii])

    # Fit the diffs to an exponential curve
    x = np.arange(len(wcopy)-1)
    try:
        popt, pcov = curve_fit(expfunc, x, diffs)
    except Exception as e:
        print e
        popt = [0.0, 0.0, 0.0]
        pcov = np.inf

    # If a > 0.5 and covsum < 1000.0
    # use a logarithmic scale.
    if type(pcov) == float:
        # It's probably np.inf
        covsum = pcov
    else:
        covsum = pcov.diagonal().sum()
    res = (covsum < 1000.0) & (popt[0] > 0.5)
    return res
Run Code Online (Sandbox Code Playgroud)

我正在尝试找到scipy的替代品curve_fit(),因为我不想安装这么大的库只是为了使用那个功能.还有其他我可以使用的东西,或其他功能的组合,从理想上只使用numpy和matplotlib,来获得类似的结果?

Ed *_*ith 7

Numpy 可以进行线性 ( numpy.linalg.lstsq) 和多项式拟合 ( numpy.polyfit)。一般来说,您需要 scipy 来拟合您自己定义的函数(scipy 使用 fortran minpack,而 numpy 仅使用 C 构建)。

但是,对于您的示例,您可以使用与此问题类似的方法来拟合 exp。基本上,取方程两边的对数并使用numpy.polyfit