如何使用scipy.optimize.curvefit?

2024-05-16 05:45:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

我得到的曲线图是这样的:拟合曲线由蓝色实线给出,而数据点由蓝色圆点给出。 enter image description here

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


Tags: 数据importasnppltsinresult曲线
1条回答
网友
1楼 · 发布于 2024-05-16 05:45:43

这个问题是不可复制的。使用生成的值时,拟合是完美的。因此,该方法工作良好。你知道吗

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()

enter image description here

相关问题 更多 >