gpt4 book ai didi

python - Python 3.3 中的非线性拟合

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

我想知道如何在 Python 3.3 中进行非线性拟合。我没有在网上找到任何简单的例子。我不太了解这些拟合技术。

欢迎任何帮助!

提前致谢。

最佳答案

要了解一个简单的示例,请访问 http://www.walkingrandomly.com/?p=5215

这是带有解释的代码!

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

xdata = np.array([-2,-1.64,-1.33,-0.7,0,0.45,1.2,1.64,2.32,2.9])
ydata = np.array([0.69,0.70,0.69,1.0,1.9,2.4,1.9,0.9,-0.7,-1.4])

def func(x, p1,p2):
return p1*np.cos(p2*x) + p2*np.sin(p1*x)

# Here you give the initial parameters for p0 which Python then iterates over
# to find the best fit
popt, pcov = curve_fit(func,xdata,ydata,p0=(1.0,0.3))

print(popt) # This contains your two best fit parameters

# Performing sum of squares
p1 = popt[0]
p2 = popt[1]
residuals = ydata - func(xdata,p1,p2)
fres = sum(residuals**2)

print(fres)

xaxis = np.linspace(-2,3,100) # we can plot with xdata, but fit will not look good
curve_y = func(xaxis,p1,p2)
plt.plot(xdata,ydata,'*')
plt.plot(xaxis,curve_y,'-')
plt.show()

enter image description here

关于python - Python 3.3 中的非线性拟合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22280256/

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