matplotlib 最小二乘拟合/幂拟合-为什么我的变量编号错误

o7jaxewo  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(133)

所以我得求出这个函数的系数。
https://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
我想我输入变量“a”的方程是正确的,答案应该在8左右。但它一直给我一个2左右的答案。我在过程中哪里出错了吗?

> import matplotlib.pyplot as mp
> import math
> 
> # (x, y) data values
> xList = [1, 2, 3, 4, 5, 6]
> yList = [8, 11, 19, 20, 18, 22]
> x = xList.copy()
> y = yList.copy()
> print (x)
> print (y)
> 
> Power Fit variables
> n = len(x)
> sumLog_x = 0
> sumLog_y = 0
> sumLog_xx = 0
> sumLog_xy = 0
> b = 0; b_Num = 0; b_Denom = 0
> a = 0; a_Num = 0; a_Denom = 0
> 
> for i in range(n) :
> sumLog_x += math.log(x[i])
> sumLog_y += math.log(y[i])
> sumLog_xx += math.log(x[i]) * math.log(x[i])
> sumLog_xy += math.log(x[i]) * math.log(y[i])
> 
> compute the exponent b
> b_Num = n * sumLog_xy - sumLog_x * sumLog_y 
> b_Denom = n * sumLog_xx - sumLog_x * sumLog_x
> b = b_Num / b_Denom
> 
> 
> a_Num = (sumLog_y) - (sumLog_x * b)
> a_Denom = n
> a = a_Num / a_Denom
> 
> print ("modeling: y = a * x^b")
> print ("exponent b = ", format(b, "0.6f"))
> print ("exponent a = ", format(a, "0.6f"))

我的输出如下

> [1, 2, 3, 4, 5, 6]
> [8, 11, 19, 20, 18, 22]
> modeling: y = a * x^b
> exponent b =  0.573009
> exponent a =  2.104825

为什么“a”是2.1?

lokaqttq

lokaqttq1#

因为你忘记了正确地计算A为np.exp(a)。下面是最终的测试代码:

#!/usr/bin/env ipython
import matplotlib.pyplot as plt
import math
import numpy as np

# (x, y) data values
xList = [1, 2, 3, 4, 5, 6]
yList = [8, 11, 19, 20, 18, 22]
x = xList.copy()
y = yList.copy()
print (x)
print (y)
 
#Power Fit variables
n = len(x)
sumLog_x = 0
sumLog_y = 0
sumLog_xx = 0
sumLog_xy = 0
b = 0; b_Num = 0; b_Denom = 0
a = 0; a_Num = 0; a_Denom = 0
nn = 0; 
for i in range(n) :
    sumLog_x += math.log(x[i])
    sumLog_y += math.log(y[i])
    sumLog_xx += math.log(x[i]) * math.log(x[i])
    sumLog_xy += math.log(x[i]) * math.log(y[i])
    nn += 1
#compute the exponent b
b_Num = n * sumLog_xy - sumLog_x * sumLog_y 
b_Denom = n * sumLog_xx - sumLog_x * sumLog_x
b = b_Num / b_Denom
 
 
a_Num = (sumLog_y) - (sumLog_x * b)
a_Denom = n
a = a_Num / a_Denom

print ("modeling: y = a * x^b")
print ("exponent b = ", format(b, "0.6f"))
print ("exponent a = ", format(a, "0.6f"))
# -----------------------------------------------------------
plt.plot(xList,yList,'k+',ms=10);
xx = np.arange(np.min(xList),np.max(xList),0.05);yy = np.exp(a)*xx**b
plt.plot(xx,yy,'r')
plt.show()

对我来说,最终的解决方案似乎是正确的,最小二乘拟合与数据匹配。

相关问题