数据拟合

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

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 poly_fit():
    z = np.polyfit(x, y, 3)#用3次多项式拟合
    p = np.poly1d(z)
    print(p) #在屏幕上打印拟合多项式
    x2=np.arange(1,20)
    y_fit=p(x2)#也可以使用yvals=np.polyval(z,x)
    plt.plot(x, y, '*',label='original values')
    plt.plot(x2, y_fit, 'r',label='polyfit values')
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    plt.legend(loc=4)#指定legend的位置,loc=4,表示图标位于第四象限
    plt.title('poly_fit')
    plt.show()
    # plt.savefig('poly.png')

#使用非线性最小二乘法拟合,a*e(b/x)
def aebx_fit():
    def func(x, a, b):
        return a * np.exp(b / x)

    popt, pcov = curve_fit(func, x, y)
    a, b = popt  # popt里面是拟合系数,读者可以自己help其用法
    x2=np.arange(1,20)
    yvals = func(x2, a, b)
    plt.plot(x, y, '*', label='original values')
    plt.plot(x2, yvals, 'r', label='curve_fit values')
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    plt.legend(loc=4)  # 指定legend的位置,loc=4,表示图标位于第四象限
    plt.title('a*e(b/x)')
    plt.show()
    # plt.savefig('aebx.png')

#a*e(b/x)+c拟合
def aebxc_fit():
    def func(x, a, b,c):
        return a * np.exp(b / x)+c

    popt, pcov = curve_fit(func, x, y)
    a,b,c=popt# popt里面是拟合系数
    x2=np.arange(1,30)
    yvals = func(x2, a, b,c)
    plt.plot(x, y, '*', label='original values')
    plt.plot(x2, yvals, 'r', label='curve_fit values')
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    plt.legend(loc=4)  # 指定legend的位置,loc=4,表示图标位于第四象限
    plt.title('a*e(b/x)+c')
    plt.show()
    # plt.savefig('aebxc.png')


#aX的b次方拟合
def axb_fit():
    def func(x, a, b):
        return a * pow(x, b)

    popt, pcov = curve_fit(func, x, y)
    a,b = popt  # popt里面是拟合系数,读者可以自己help其用法
    x2 = np.arange(1, 20)
    yvals = func(x2, a, b)
    plt.plot(x, y, '*', label='original values')
    plt.plot(x2, yvals, 'r', label='curve_fit values')
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    plt.legend(loc=4)  # 指定legend的位置,loc=4,表示图标位于第四象限
    plt.title('axb')
    plt.show()
    #plt.savefig('axb.png')

if __name__ == '__main__':
    poly_fit()
    aebx_fit()
    aebxc_fit()
    axb_fit()

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值