Python数据拟合

2024-09-30 10:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

The fit that I am getting

当我试图用抛物线拟合这个数据时,我得到了一个可怕的拟合。 我最初是做一个直方图的数据,这是一个对象的位置,然后绘制负对数值的直方图bin计数的位置使用抛物线拟合。 我使用的代码是:

time,pos=postime()
plt.plot(time, pos)
poslen=len(pos)
plt.xlabel('Time')
plt.ylabel('Positions')
plt.show()


n,bins,patches = plt.hist(pos,bins=100)
n=n.tolist()
plt.show()
l=len(bins)   
s=len(n)
posx=[]
i=0
j=0
pbin=[]
sig=[]
while j < (l-1): 
    pbin.append((bins[j]+bins[j+1])/2)
    j=j+1

while i < s:

    if n[i]==0:
        pbin[i]=0
    else:
        sig.append(np.power(1/n[i],2))
        n[i]=n[i]/poslen

        n[i]=np.log(n[i])
        n[i]=n[i]*(-1)
    i=i+1


n[:]=[y for y in n if y != 0] 
pbin[:]=[y for y in pbin if y != 0]       

from scipy.optimize import curve_fit
def parabola(x, a , b):
    return a * (np.power(x,2)) + b

popt, pcov = curve_fit(parabola, pbin, n)
print popt

plt.plot(pbin,n)
plt.plot(pbin, parabola(pbin, *popt), 'r-')

Tags: 数据posleniftimeplotnpplt
2条回答

也可以使用矩阵求逆。你知道吗

import numpy as np
import matplotlib.pyplot as plt 
x = np.linspace(-5,5,100)
Y = (np.power(x,2) + np.random.normal(0,1,x.shape)).reshape(-1,1)

X = np.c_[np.ones(x.shape), x, np.power(x,2)]
A = np.linalg.inv(X.transpose().dot(X)).dot(X.transpose().dot(Y))
Yp = X.dot(A)

fig = plt.figure()
ax = fig.add_subplot()
plt.plot(x,Y,'o',alpha=0.5)
plt.plot(x,Yp)
plt.show()

矩阵形式是

X*A=Y
A=(Xt*X)-1*Xt*Y

如果需要的话,你可以有一个更好的主意。它并不总是有效的,您可能需要应用某种形式的regularization。你知道吗

我不知道你为什么要计算直方图。。。但这里有一个不需要直方图计算的工作示例。你知道吗

import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot


time_ = np.arange(-5, 5, 0.1)
pos = time_**2 + np.random.rand(len(time_))*5

def parabola(x, a, b):
    return a * (np.power(x, 2)) + b

popt, pcov = curve_fit(parabola, time_, pos)
yfit = parabola(time_, *popt)

pyplot.plot(time_, pos, 'o')
pyplot.plot(time_, yfit)

enter image description here

另外,如果你的time_向量不是均匀采样的,你希望它是均匀采样的拟合,你可以做:fittime_ = np.linsapce(np.min(time_), np.max(time_))然后yfit = parabola(fittime_, *popt)。你知道吗

相关问题 更多 >

    热门问题