python双曲线拟合

待拟合函数 y = alpha * pow(x, beta) 

输入: x数组,y数组

输出: alpha,beta,相关系数R2

from scipy.optimize import leastsq
from pylab import *
import numpy as np

xdata = np.array([4.79616, 11.63, 37.5534, 105.414])

ydata = np.array([1.33921, 0.755319, 0.34085, 0.0554339])

# Define function for calculating a power law
powerlaw = lambda x, alpha, beta: alpha * (x ** beta)
logx = log10(xdata)
logy = log10(ydata)

# define our (line) fitting function
fitfunc = lambda p, x: p[0] + p[1] * x   
errfunc = lambda p, x, y: (y - fitfunc(p, x))

pinit = [1.0, -1.0]
out, cov, infodict, mesg, ier = leastsq(errfunc, pinit,
                       args = (logx, logy), full_output=1)

beta = out[1]
alpha = 10.0 ** out[0]

ss_err = (infodict['fvec'] ** 2).sum()
ss_tot = ((ydata - ydata.mean()) ** 2).sum()
r2 = 1 - (ss_err / ss_tot)

print('Alpha: %f, Beta: %f' % (alpha, beta))
print ('R2: %f' % r2)

  

 

posted on 2017-03-12 11:37  lakeone  阅读(3587)  评论(0编辑  收藏  举报

导航