我想在許多數據點上做一個高斯擬合。例如。我有一個256 x 262144數據陣列。 256點需要擬合成高斯分佈,我需要262144個點。如何快速執行多個數據集的最小二乘擬合?
有時高斯分佈的峯值超出了數據範圍,因此要得到準確的平均結果曲線擬合是最好的方法。即使峯值在該範圍內,曲線擬合也會提供更好的西格馬,因爲其他數據不在該範圍內。
我有這個工作的一個數據點,使用代碼從http://www.scipy.org/Cookbook/FittingData。
我試圖重複這個算法,但它看起來像要花費43分鐘的時間來解決這個問題。是否有一個已經寫好的並行或更高效的快速方法?
from scipy import optimize
from numpy import *
import numpy
# Fitting code taken from: http://www.scipy.org/Cookbook/FittingData
class Parameter:
def __init__(self, value):
self.value = value
def set(self, value):
self.value = value
def __call__(self):
return self.value
def fit(function, parameters, y, x = None):
def f(params):
i = 0
for p in parameters:
p.set(params[i])
i += 1
return y - function(x)
if x is None: x = arange(y.shape[0])
p = [param() for param in parameters]
optimize.leastsq(f, p)
def nd_fit(function, parameters, y, x = None, axis=0):
"""
Tries to an n-dimensional array to the data as though each point is a new dataset valid across the appropriate axis.
"""
y = y.swapaxes(0, axis)
shape = y.shape
axis_of_interest_len = shape[0]
prod = numpy.array(shape[1:]).prod()
y = y.reshape(axis_of_interest_len, prod)
params = numpy.zeros([len(parameters), prod])
for i in range(prod):
print "at %d of %d"%(i, prod)
fit(function, parameters, y[:,i], x)
for p in range(len(parameters)):
params[p, i] = parameters[p]()
shape[0] = len(parameters)
params = params.reshape(shape)
return params
請注意,數據不一定是256x262144,我已經做了一些在nd_fit furtging使這項工作。
我用得到這個工作的代碼是
from curve_fitting import *
import numpy
frames = numpy.load("data.npy")
y = frames[:,0,0,20,40]
x = range(0, 512, 2)
mu = Parameter(x[argmax(y)])
height = Parameter(max(y))
sigma = Parameter(50)
def f(x): return height() * exp (-((x - mu())/sigma()) ** 2)
ls_data = nd_fit(f, [mu, sigma, height], frames, x, 0)
注:由@JoeKington貼在下面的解決方案是偉大的,解決了真快。但是,除非高斯的顯着區域位於適當區域內,否則似乎不起作用。我將不得不測試平均值是否仍然準確,因爲這是我使用它的主要內容。
你能發表你使用的代碼嗎? – 2012-01-08 20:37:30