当拟合到具有大值的曲线时,scipy curve_fit失败

时间:2017-06-26 21:25:04

标签: python python-3.x scipy scientific-computing idl-programming-language

我试图将一些水平风数据拟合到余弦曲线,以便估计不同高度(风速方位角显示)的风的方向和速度,但是每当我尝试使用值> 〜1,曲线看起来太平,拟合的输出低于预期。

import numpy as np
import scipy.optimize as sc

azimuth = np.full((8), 60) #All values = 60 deg.
velocity = [5.6261001,6.6962662,3.9316666,-0.88413334,-5.4323335,-6.5153003,-3.2538002,1.0269333]
#Function that defines curve that data will be fitted to
def cos_Wave(x,a, b, c):
    return a * np.cos(x-b) + c

azimuthData = np.deg2rad(azimuth)
coeffs, matcov = sc.curve_fit(cos_Wave, azimuthData, velocity, p0 = (1,0,0)

plt.scatter(azimuthData, velocity)
plt.plot(azimuthData, cos_Wave(azimuthData, *coeffs))
plt.show()
print(coeffs)

系数输出为:[1.,0.,0.13705066]并附图:

Python CurveFit

我使用IDL的内置曲线拟合函数执行了类似的曲线拟合,并获得了更多实际值,产生[7.0348234,0.59962606,0.079354301]并提供了合适的拟合。是否有这种情况的原因?我假设它可能与初始估计(P0)有关,但是,在IDL实现中利用初始初始估计仍然提供了更合理的结果。

1 个答案:

答案 0 :(得分:2)

你需要解决一些问题:

import numpy as np
import scipy.optimize as sc
import matplotlib.pyplot as plt

azimuth = np.linspace(0, 360, 8)  # deg values from 0 to 360
velocity = [5.6261001, 6.6962662, 3.9316666, -0.88413334, -5.4323335,
            -6.5153003, -3.2538002, 1.0269333]


def cos_Wave(x, a, b, c):
    """Function that defines curve that data will be fitted to"""
    return a * np.cos(x-b) + c


azimuthData = np.deg2rad(azimuth)
coeffs, matcov = sc.curve_fit(cos_Wave, azimuthData, velocity, p0=[1, 0, 0])

plt.scatter(azimuthData, velocity)
nx = np.linspace(0, 2 * np.pi, 100)
plt.plot(nx, cos_Wave(nx, *coeffs))
plt.savefig("plot.png")
print(coeffs)

[6.63878549 1.03148322 -0.27674095]

enter image description here