我试图随时间曲线拟合某些数据(x =时间,y =数据),但是在确定要使用的功能以及如何/是否需要清理数据时遇到了一些麻烦。
这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#define xdata dnd ydata
ydata = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 12]
ydata_1 = [2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4]
ydata_2 = [1, 3, 7, 7, 10, 12, 12, 13, 13, 11, 11, 11, 12, 14, 15, 15, 15, 15, 16, 16, 16, 17, 16, 18, 18, 19, 19, 19, 19, 19, 19, 20, 20, 20, 21, 22, 22, 22, 23, 23, 24, 26, 25, 25, 25, 26, 26, 26, 26, 27, 27]
xdata = []
for i, _ in enumerate(ydata):
xdata.append(i+1)
x = np.array(xdata)
y = np.array(ydata)
def func(xdata, a, b, c, d):
t = 60
return (a * xdata * np.exp(1 - (b / (t - c)**d)))
xfine = np.linspace(y.min(), y.max(), 100)
popt, pcov = curve_fit(func, x, y)
fig = plt.figure()
ax4 = fig.add_subplot(1,1,1)
ax4.plot(x, y, '.')
ax4.plot(xfine, func(xfine, popt[0], popt[1], popt[2], popt[3]),'r-')
ax4.set_xlabel('Time')
ax4.set_ylabel('Score')
ax4.grid('on')
plt.show()
您可以看到,随着时间的流逝,我的数据非常重复,并且该功能目前还无法正常工作。我真的不知道我在做什么错以及如何解决。
答案 0 :(得分:0)
您正在将线性函数拟合到ydata中。如果您想适应指数级的用户,请尝试以下操作:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#define xdata dnd ydata
ydata = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3,
3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6,
7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10,
10, 10, 10, 10, 10, 11, 12]
y = np.array(ydata)
x = np.arange(1,len(y)+1,1)
def func(xdata, a, b, c):
return (a*np.power(b, xdata)) + c
#or return (a*np.exp(-b*xdata))
xfine = np.arange(1, len(y)+1, 0.1)
popt, pcov = curve_fit(func, x, y)
fig = plt.figure()
ax4 = fig.add_subplot(1,1,1)
ax4.plot(x, y, '.')
ax4.plot(xfine, func(xfine, popt[0], popt[1], popt[2]),'r-')
ax4.set_xlabel('Time')
ax4.set_ylabel('Score')
plt.show()