使用 scipy.optimize.curve_fit 我无法正确拟合 V*cos(ω*t) 函数
Using scipy.optimize.curve_fit I can't fit V*cos(ω*t) function correctly
我已经从 python 中的一个函数创建了数据,所以我认为拟合需要是完美的,但事实并非如此 我不知道为什么
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
def fun(offset, V, f, phi):
return V * np.cos(2*np.pi*f * x + phi) + offset
xData = np.arange(0, 1, 0.005) #time
f = 2 #frequency
yData = 5 * np.cos(2*np.pi*f * x)
popt, pcov = curve_fit(fun, xData, yData, p0=[1, 1, 1])
print(popt)
plt.scatter(xData, yData, label="data")
plt.plot(xData, fun(x, *popt), label="fit")
plt.legend(loc = "upper right")
plt.show()
plotted data and fit points
存在多个问题,包括您的函数定义和初始猜测。这有效:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
def fun(xData, offset, V, f, phi):
return V * np.cos(2*np.pi*f * xData + phi) + offset
xData = np.arange(0, 1, 0.005) #time
f = 2 #frequency
yData = 5 * np.cos(2*np.pi*f * xData)
popt, pcov = curve_fit(fun, xData, yData, p0=[0, 6, 2, 1])
print(popt)
plt.scatter(xData, yData, label="data", c='k')
plt.plot(xData, fun(xData, *popt), label="fit", c='r')
plt.legend(loc = "upper right")
plt.show()
我已经从 python 中的一个函数创建了数据,所以我认为拟合需要是完美的,但事实并非如此 我不知道为什么
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
def fun(offset, V, f, phi):
return V * np.cos(2*np.pi*f * x + phi) + offset
xData = np.arange(0, 1, 0.005) #time
f = 2 #frequency
yData = 5 * np.cos(2*np.pi*f * x)
popt, pcov = curve_fit(fun, xData, yData, p0=[1, 1, 1])
print(popt)
plt.scatter(xData, yData, label="data")
plt.plot(xData, fun(x, *popt), label="fit")
plt.legend(loc = "upper right")
plt.show()
plotted data and fit points
存在多个问题,包括您的函数定义和初始猜测。这有效:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
def fun(xData, offset, V, f, phi):
return V * np.cos(2*np.pi*f * xData + phi) + offset
xData = np.arange(0, 1, 0.005) #time
f = 2 #frequency
yData = 5 * np.cos(2*np.pi*f * xData)
popt, pcov = curve_fit(fun, xData, yData, p0=[0, 6, 2, 1])
print(popt)
plt.scatter(xData, yData, label="data", c='k')
plt.plot(xData, fun(xData, *popt), label="fit", c='r')
plt.legend(loc = "upper right")
plt.show()