如何用python拟合非线性函数? [英] How to fit a non linear function with python?

查看:155
本文介绍了如何用python拟合非线性函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用R编写了以下代码来估计三个系数(a,b和c):

I have the following code written in R to estimate three coefficients (a, b and c):

y <- c(120, 125, 158, 300, 350, 390, 2800, 5900, 7790)
t <- 1:9
fit <-  nls(y ~ a * (((b + c)^2/b) * exp(-(b + c) * t))/(1 + (c/b) *
      exp(-(b + c) * t))^2, start = list(a = 17933, b = 0.01, c = 0.31))

我得到这个结果

> summary(fit )

Formula: y ~ a * (((b + c)^2/b) * exp(-(b + c) * t))/(1 + (c/b) * exp(-(b + 
    c) * t))^2

Parameters:
   Estimate Std. Error t value Pr(>|t|)    
a 2.501e+04  2.031e+03  12.312 1.75e-05 ***
b 1.891e-05  1.383e-05   1.367    0.221    
c 1.254e+00  1.052e-01  11.924 2.11e-05 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 248.8 on 6 degrees of freedom

Number of iterations to convergence: 33 
Achieved convergence tolerance: 6.836e-06

如何用Python做同样的事情?

How to make the same thing with Python ?

推荐答案

您可以使用 curve_fit ,获得相同的结果:

You can use curve_fit, which gives you the same result:

import scipy.optimize as optimization
import numpy as np

y = np.array([120, 125, 158, 300, 350, 390, 2800, 5900, 7790])
t = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
start = np.array([17933, 0.01, 0.31])

def f(t,a,b,c):
    num = a*(np.exp(-t*(b+c))*np.power(b+c, 2)/b)
    denom = np.power(1+(c/b)*np.exp(-t*(b+c)), 2)
    return num/denom

print(optimization.curve_fit(f, t, y, start))
#(array([  2.50111448e+04,   1.89129922e-05,   1.25426156e+00]), array([[ 4.12657233e+06,   2.58151776e-02,  -2.00881091e+02],
#       [  2.58151776e-02,   1.91318685e-10,  -1.44733425e-06],
#       [ -2.00881091e+02,  -1.44733425e-06,   1.10654268e-02]]))

这篇关于如何用python拟合非线性函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆