简体   繁体   中英

Unexpected result with polyfit in python

Permit me first to introduce the background of the question:

I came into a quiz, which gave me a data set and a Logistic equation: 后勤

Then it asked whether that model can be linearized, and if it is, use the linear model to evaluate the value of a and k .

I tried to linearize it like this: 线性化 And coded in python:

t = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
y = np.array([43.65, 109.86, 187.21, 312.67, 496.58, 707.65, 960.25, 1238.75, 1560, 1824.29, 2199, 2438.89, 2737.71])
yAss = np.log(3000/y - 1)
cof = np.polyfit(t, yAss, deg = 1)
a = math.e**(cof[0]); 
k = -cof[1];
yAfter = 3000 / (1 + a*math.e**(-k*t))

sizeScalar = 10
fig = plt.figure(figsize = (sizeScalar*1.1, sizeScalar))
plt.plot(t, y, 'o', markersize = sizeScalar*0.75)
plt.plot(t, yAfter, 'r-')
plt.grid(True)
plt.show()

And got that, which is obviously incorrect: 错误的结果 Then by coincident, I changed some part of the code:

t = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
y = np.array([43.65, 109.86, 187.21, 312.67, 496.58, 707.65, 960.25, 1238.75, 1560, 1824.29, 2199, 2438.89, 2737.71])
yAss = np.log(3000/y - 1)
cof = np.polyfit(t, yAss, deg = 1)
a = math.e**(-cof[1]); #<<<===============here. Before: a = math.e**(cof[0])
k = cof[0]; #<<<==========================and here, Before: k = -cof[1]
temp = 3000 / (1 + a*math.e**(-k*t))
yAfter = []
for itera in temp: #<<<=======================add this
    yAfter.append(3000 - itera)

sizeScalar = 10
fig = plt.figure(figsize = (sizeScalar*1.1, sizeScalar))
plt.plot(t, y, 'o', markersize = sizeScalar*0.75)
plt.plot(t, yAfter, 'r-')
plt.grid(True)
plt.show()

And received a sequence that seems to be right? 哇靠 But how could it be? I think cof[0] IS beta, and cof 1 IS -k , if it is, my previous code should just have some wrong concept. But change the order and sign of the coefficient, I got a result that fits well?! Is it purely coincident? And what might be the right answer of the quiz?

np.polyfit returns the highest degree first: https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html#numpy.polyfit

Use:

k = -cof[0]
a = exp(cof[1])

Also, you can use NumPy's exponential:

yAfter = 3000/(1+a*np.exp(-k*t)))

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