曲线拟合并不总是那么简单。这curve_fit
算法基于最小二乘曲线拟合,通常需要对输入参数进行初始猜测。根据您想要拟合的函数类型,您最初的猜测必须是正确的。
尽管您尝试了初步猜测,但我想说您还有一个与采样频率和波频率有关的额外问题。欲了解更多信息,您可以查看奈奎斯特-香农采样定理在维基百科。简而言之,你的波的频率是 1.759 / (2 * pi) = 0.28,结果非常接近你的波的采样频率x
数组(~0.33)。可能出现的另一个问题是有太多的振荡来适应您的功能。
为了使您的代码正常工作,我建议您增加波的频率(a > 4 * 0.33),或者增加采样频率并减少空间向量的长度x
.
我运行了以下代码并获得了如图所示的结果here:
# -*- coding: utf-8 -*-
import numpy as np
import pylab as pl
from scipy.optimize import curve_fit
def mysine(x, a):
return 1. * np.sin(a * x)
a = 1.759 # Wave frequency
x = np.linspace(0, 10, 100) # <== This is what I changed
y = np.sin(a * x) + 0. * np.random.normal(size=len(x))
# Runs curve fitting with initial guess.
popt, pcov = curve_fit(mysine, x, y, p0=[1.5])
# Calculates the fitted curve
yf = mysine(x, *popt)
# Plots results for comparison.
pl.ion()
pl.close('all')
fig = pl.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, '-', c=[0.5, 0.5, 0.5])
ax.plot(x, yf, 'k-', linewidth=2.0)
ax.text(0.97, 0.97, ur'a=%.4f, ã=%.4f' % (a, popt[0]), ha='right', va='top',
fontsize=14, transform=ax.transAxes)
fig.savefig('stow_curve_fit.png')