我有一组数据点(代码中的 x 和 y)。我想绘制这些点,并为它们拟合一条曲线,显示使 y = 100.0 所需的 x 值(y 值是百分比)。这是我尝试过的方法,但我的曲线是 3 次多项式(我知道这是错误的)。对我来说,数据看起来是对数的,但我现在知道如何将对数曲线拟合到我的数据。
import numpy as np
import matplotlib.pyplot as plt
x = np.array([4,8,15,29,58,116,231,462,924,1848])
y = np.array([1.05,2.11,3.95,7.37,13.88,25.46,43.03,64.28,81.97,87.43])
for x1, y1 in zip(x,y):
plt.plot(x1, y1, 'ro')
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
for x1 in np.linspace(0, 1848, 110):
plt.plot(x1, f(x1), 'b+')
plt.show()
请您参考如下方法:
您实际上不需要使用 Numpy 或 Scipy 中的任何拟合函数,因为有一个“简单的”closed form formula for finding the least-squares fit to a logarithmic curve .这是 Python 中的一个实现:
def logFit(x,y):
# cache some frequently reused terms
sumy = np.sum(y)
sumlogx = np.sum(np.log(x))
b = (x.size*np.sum(y*np.log(x)) - sumy*sumlogx)/(x.size*np.sum(np.log(x)**2) - sumlogx**2)
a = (sumy - b*sumlogx)/x.size
return a,b
然后您可以将它应用到您的问题中:
x = np.array([4,8,15,29,58,116,231,462,924,1848])
y = np.array([1.05,2.11,3.95,7.37,13.88,25.46,43.03,64.28,81.97,87.43])
def logFunc(x, a, b):
return a + b*np.log(x)
plt.plot(x, y, ls="none", marker='.')
xfit = np.linspace(0,2000,num=200)
plt.plot(xfit, logFunc(xfit, *logFit(x,y)))
不过我不认为你的数据是对数的:
