最小二乘法进行曲线拟合 Python

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                       

本文不手动实现最小二乘,调用scipy库中实现好的相关优化函数。

考虑如下的含有4个参数的函数式:

f(x)=AD1+(x/C)B+D

构造数据

import numpy as npfrom scipy import optimizeimport matplotlib.pyplot as pltdef logistic4(x, A, B, C, D):    return (A-D)/(1+(x/C)**B)+Ddef residuals(p, y, x):     A, B, C, D = p    return y - logisctic4(x, A, B, C, D)def peval(x, p):    A, B, C, D = p    return logistic4(x, A, B, C, D) A, B, C, D = .5, 2.5, 8, 7.3x = np.linspace(0, 20, 20)y_true = logistic4(x, A, B, C, D)y_meas = y_true + 0.2 * np.random.randn(len(y_true))
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

调用工具箱函数,进行优化

p0 = [1/2]*4plesq = optimize.leastsq(residuals, p0, args=(y_meas, x))                        # leastsq函数的功能其实是根据误差(y_meas-y_true)                        # 估计模型(也即函数)的参数
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

绘图

plt.figure(figsize=(6, 4.5))plt.plot(x, peval(x, plesq[0]), x, y_meas, 'o', x, y_true)plt.legend(['Fit', 'Noisy', 'True'], loc='upper left')plt.title('least square for the noisy data (measurements)')for i, (param, true, est) in enumerate(zip('ABCD', [A, B, C, D], plesq[0])):    plt.text(11, 2-i*.5, '{} = {:.2f}, est({:.2f}) = {:.2f}'.format(param, true, param, est))plt.savefig('./logisitic.png')plt.show()
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8


这里写图片描述

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值