当前位置: 移动技术网 > IT编程>脚本编程>Python > Python曲线拟合代码实例

Python曲线拟合代码实例

2017年12月22日  | 移动技术网IT编程  | 我要评论

如月二月,十二楼的流星雨,佩视剧场

1、多项式拟合范例

这里写图片描述

# _*_coding:utf-8_*_
__author__ = 'Alex_XT'
# Python imports
import matplotlib.pyplot as plt
import 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])
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 imports
import matplotlib.pyplot as plt
import numpy as np

x = [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_fit
import matplotlib.pyplot as plt
import 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()

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网