首页 > 解决方案 > Python - 更复杂函数的曲线拟合

问题描述

我希望找到下图的最佳拟合曲线方程:在此处输入图像描述

其中方程的形式为:

在此处输入图像描述

我试图在numpy 此处此处找到曲线拟合的示例,但它们都只显示如何仅绘制指数或仅正弦曲线,但我想绘制一个结合这两个函数的图形。

我该怎么做?

标签: pythonplotgraphequationexponential

解决方案


这是您可能会发现有用的一种方法。这使用lmfithttp://lmfit.github.io/lmfit-py/),它提供了一种高级的曲线拟合方法:

import numpy as np
import matplotlib.pyplot as plt

from lmfit import Model

def decay_cosine(t, amp, beta, omega, phi):
    """model data as decaying cosine wave"""
    return amp * np.exp(-beta*t)* np.cos(omega*t + phi)

# create fake data to be fitted
t = np.linspace(0, 5, 101)
y = decay_cosine(t, 1.4, 0.9, 7.2, 0.23) + np.random.normal(size=len(t), scale=0.05)

# build model from decay_cosine
mod = Model(decay_cosine)

# create parameters, giving initial values
params = mod.make_params(amp=2.0, beta=0.5, omega=5, phi=0)

# you can place bounds on parameters:
params['phi'].max = np.pi/2
params['phi'].min = -np.pi/2
params['amp'].min = 0

# fit data to model

result = mod.fit(y, params, t=t)

# print out fit results
print(result.fit_report())

# plot data with best fit
plt.plot(t, y, 'bo', label='data')
plt.plot(t, result.best_fit, 'r')
plt.show()

这将打印出这样的报告:

[[Model]]
    Model(decay_cosine)
[[Fit Statistics]]
    # fitting method   = leastsq
    # function evals   = 46
    # data points      = 101
    # variables        = 4
    chi-square         = 0.25540159
    reduced chi-square = 0.00263301
    Akaike info crit   = -595.983903
    Bayesian info crit = -585.523421
[[Variables]]
    amp:    1.38812335 +/- 0.03034640 (2.19%) (init = 2)
    beta:   0.90760648 +/- 0.02820705 (3.11%) (init = 0.5)
    omega:  7.16579292 +/- 0.02891827 (0.40%) (init = 5)
    phi:    0.26249321 +/- 0.02225816 (8.48%) (init = 0)
[[Correlations]] (unreported correlations are < 0.100)
    C(omega, phi)  = -0.713
    C(amp, beta)   =  0.695
    C(amp, phi)    =  0.253
    C(amp, omega)  = -0.183
    C(beta, phi)   =  0.178
    C(beta, omega) = -0.128

并产生这样的情节:

在此处输入图像描述


推荐阅读