如何用调和函数拟合这些数据?

问题描述 投票:0回答:2

我想做一个曲线拟合,将曲线拟合为正弦和余弦之和。但即使只是余弦的拟合也是完全错误的。

这是我的代码: 使用 nc 文件中的这些数据(使用 xarray 打开):

ds_s_tagesgang['小时'] = array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23])

ds_s_tagesgang['T2m'] = 数组([-0.60313714, -0.6527668 , -0.669063 , -0.6045208 , -0.46157956, -0.36819172、-0.17480397、0.00283241、0.15954256、0.33030534、 0.43397593、0.54781055、0.61995673、0.59603477、0.610795、 0.5800109、0.4601419、0.29350758、0.20055556、0.03135109、 -0.15563202, -0.27981472, -0.4027779, -0.4945315], dtype=float32)

# fit a straight line to the economic data
from numpy import arange
from pandas import read_csv
from scipy.optimize import curve_fit
from matplotlib import pyplot
 
# define the true objective function
def objective(x, a, b, c):
    return a * np.sin(b * x) + c
 
# load the dataset

# choose the input and output variables
x, y = ds_s_tagesgang['hour'], ds_s_tagesgang['T2m']
# curve fit
popt, _ = curve_fit(objective, x, y)
# summarize the parameter values
a, b, c = popt
print('y = %.5f + np.sin(%.5f * x) + %.5f' % (a, b, c))
# plot input vs output
pyplot.scatter(x, y)
# define a sequence of inputs between the smallest and largest known inputs
x_line = arange(min(x), max(x), 1)
# calculate the output for the range
y_line = objective(x_line, a, b, c)
# create a line plot for the mapping function
pyplot.plot(x_line, y_line, '--', color='red')
pyplot.show()

这是我的代码,但拟合完全错误,如图所示:蓝点是我的数据。红线是“拟合”曲线

python scipy curve-fitting
2个回答
1
投票

困难可能来自于以下形式的模型方程

y = A * sin(B * x) + C

不包括相移。建议型号是:

y = A * sin(B * x + F) + C

涉及四个参数(A、B、C、F)而不是三个。

另一个困难原因是软件中使用的非线性回归方法。这是一种迭代演算,需要参数的初始猜测值。如果这些值与正确值相差太远,数值计算可能会失败。

为了克服这一困难,可以使用如下所示的非迭代方法。

请注意,模型函数以不同的形式编写,但等效:

y = a + b * sin(w * x) + c * cos(w * x) = A * sin(B * x + F) + C

A^2 = a^2+b^2

tan(F) = b/c

C = a

根据您的数据,数值计算为:

注意:上述方法涉及的拟合标准与常见的最小均方不同。如果严格要求 LMS 拟合,则必须回到非线性回归方法(迭代)。但不再需要猜测初始值,因为上面找到的值非常适合用作初始值。

参考:

https://fr.scribd.com/doc/14674814/Regressions-et-equations-integrales

此外:非线性回归结果


0
投票

@JJacquelin:你应该在你的答案中添加B=w,对于F,如果b小于0,则必须添加pi。

@Admins/Mods:我无法对 JJacquelin 的答案添加评论,这就是为什么我决定做一个额外的答案。

最好的,Romaxx

© www.soinside.com 2019 - 2024. All rights reserved.