gpt4 book ai didi

python - 曲线拟合和数据预处理

转载 作者:太空宇宙 更新时间:2023-11-03 20:51:54 25 4
gpt4 key购买 nike

我试图随着时间的推移对一些数据进行曲线拟合(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()

正如您所看到的,随着时间的推移,我的数据非常重复,并且该功能目前还无法真正发挥作用。我真的不知道我做错了什么以及如何解决它。

最佳答案

您正在将线性函数拟合到 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()

关于python - 曲线拟合和数据预处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56264062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com