简体   繁体   中英

Least Squares Fitting/Power Fit - Why is my variable the wrong number

so I have to find the coefficients of this function.

https://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html

I think I input the equation for the variable "a" right, the answer should be around 8. But it keeps giving me an answer of around 2. Did I go wrong somewhere in my process?

> 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"))

My output is this

> [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

Why is "a" coming out as 2.1?

Because you forgot to calculate correct A as np.exp(a). Here is the final test code:

#!/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()

To me it seemed that the final solution is correct ie the least square fit matches with the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM