待拟合函数 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])
powerlaw = lambda x, alpha, beta: alpha * (x ** beta)
logx = log10(xdata)
logy = log10(ydata)
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)
手机扫一扫
移动阅读更方便
你可能感兴趣的文章