【问题标题】:How do I fit a a curve well using scipy.optimize.curvefit?如何使用 scipy.optimize.curvefit 拟合曲线?
【发布时间】:2017-07-26 19:58:36
【问题描述】:

我有一组数据,我想使用正弦函数对其进行拟合。因此,我编写了以下代码:

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

def sin_curve(rad, a, b, c, d):
    result = []
    for value in rad:
        outcome = float(a*np.sin(b*value + c) + d)
        result.append(outcome)
    return result

# X data => polangle_rad, Y data => three_ara
[a_300, b_300, c_300, d_300], var_300  = curve_fit(sin_curve, polangle_rad, three_ara, p0=[10,2,-0.5,75])

polplt_xrange = np.arange(0,2*np.pi+unit,unit)

# Plotting
plt.figure()
three_line,_ = ax.plot(polangle_rad, three_ara, 'bo', polplt_xrange, np.array(sin_curve(polplt_xrange, a_300, b_300, c_300, d_300)), 'b-')

plt.show()

我得到的情节是这样的;拟合曲线由蓝色实线给出,而数据点由蓝点给出。

从图中,我们可以看到拟合曲线略微向左旋转。有没有更好的方法来拟合曲线?

【问题讨论】:

  • 你能提供数据吗?数据似乎无法用普通的 sin 函数表示,尝试添加一些谐波。并且作为@ImportanceOfBeingErnest cmets,尽管缺少数据,但您的样本无法运行,例如unit 未定义。

标签: python matplotlib scipy


【解决方案1】:

该问题不可重现。使用生成的值时,拟合是完美的。因此,该方法运行良好。

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

def sin_curve(rad, a, b, c, d):
    result = []
    for value in rad:
        outcome = float(a*np.sin(b*value + c) + d)
        result.append(outcome)
    return result

xval = np.linspace(0,2*np.pi,16)
yval = -10*np.sin(2*xval-1.5)+75
# X data => polangle_rad, Y data => three_ara
[a_300, b_300, c_300, d_300], var_300  = curve_fit(sin_curve, xval, 
                                                    yval, p0=[10,2,-0.5,75])

print [a_300, b_300, c_300, d_300]
# [-9.9999999999999556, 1.9999999999999991, -1.4999999999999984, 75.0]

polplt_xrange = np.linspace(0,2*np.pi,100)

# Plotting
fig = plt.figure()
ax = fig.add_subplot(121, projection="polar")
ax2 = fig.add_subplot(122)

p, = ax.plot(xval, yval, 'bo')
y = np.array(sin_curve(polplt_xrange, a_300, b_300, c_300, d_300))
line, = ax.plot(polplt_xrange,y , 'b-')

ax.set_ylim(None, y.max()*1.1)

ax2.plot(xval, yval, 'bo')
ax2.plot(polplt_xrange,y , 'b-')

plt.tight_layout()
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2021-01-19
    相关资源
    最近更新 更多