Python 3.3中的非线性拟合

3 投票
1 回答
1123 浏览
提问于 2025-04-17 21:30

我想知道怎么在Python 3.3中进行非线性拟合。我在网上找不到简单的例子。我对这些拟合技术不是很了解。

任何帮助都非常欢迎!

提前谢谢大家。

1 个回答

6

想要了解一个简单的例子,可以去看看这个链接: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()

在这里输入图片描述

撰写回答