Python曲线拟合

来源:互联网 发布:ubuntu 16.04 ppa失败 编辑:程序博客网 时间:2024/06/05 10:04

1、多项式拟合范例

这里写图片描述

# _*_coding:utf-8_*___author__ = 'Alex_XT'# Python importsimport matplotlib.pyplot as pltimport numpy as npx = np.arange(1, 17, 1)y = np.array([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60])z1 = np.polyfit(x, y, 5)  # 用3次多项式拟合p1 = np.poly1d(z1)print(p1)  # 在屏幕上打印拟合多项式yvals = p1(x)  # 也可以使用yvals=np.polyval(z1,x)plot1 = plt.plot(x, y, 'k.', markersize=16, label='$original values$')plot2 = plt.plot(x, yvals, 'r', lw=3, label='$polyfit values$')plt.xlabel('$X$')plt.ylabel('$Y$')plt.legend(loc=4)  # 指定legend的位置,读者可以自己help它的用法plt.title('polyfitting')plt.show()

这里写图片描述

# _*_coding:utf-8_*___author__ = 'Alex_XT'# Python importsimport matplotlib.pyplot as pltimport numpy as npx = [0.0,0.1,0.21,0.30,0.41,0.59,0.62,0.797,0.85,1.0]y = np.array([1.49,0.9,1.46,0.0,-0.47,0.46,-0.2,-0.22,-1.4,-0.97])z1 = np.polyfit(x, y, 10)  # 用3次多项式拟合p1 = np.poly1d(z1)print(p1)  # 在屏幕上打印拟合多项式yvals = p1(x)  # 也可以使用yvals=np.polyval(z1,x)plot1 = plt.plot(x, y, 'k.', markersize=16, label='original values')plot2 = plt.plot(x, yvals, 'r', lw=3, label='overfit')plot3=plt.plot([0.0,1.0],[1.5,-1.5],'b',label='best fit')plt.xlabel('$X$')plt.ylabel('$Y$')plt.legend(loc=3)  # 指定legend的位置,读者可以自己help它的用法plt.title('polyfitting')plt.show()

2、指定函数拟合

这里写图片描述

# _*_coding:utf-8_*___author__ = 'Alex_XT'# Python imports#使用非线性最小二乘法拟合from scipy.optimize import curve_fitimport matplotlib.pyplot as pltimport numpy as np#用指数形式来拟合x = np.arange(1, 17, 1)y = np.array([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60])def func(x,a,b):    return a*np.exp(b/x)popt, pcov = curve_fit(func, x, y)a=popt[0]#popt里面是拟合系数,读者可以自己help其用法b=popt[1]yvals=func(x,a,b)plot1=plt.plot(x, y, '*',label='original values')plot2=plt.plot(x, yvals, 'r',label='curve_fit values')plt.xlabel('x axis')plt.ylabel('y axis')plt.legend(loc=4)#指定legend的位置,读者可以自己help它的用法plt.title('curve_fit')plt.show()

参考

【1】python曲线拟合panhaidongphd新浪博客
http://blog.sina.com.cn/s/blog_aed5bd1d0102vid7.html

原创粉丝点击