0
我試圖將多個高斯給定的數據,並在第500個型號達到時,這部分程序是用約3 GB的內存,我需要適應總共〜2000款。下面是我的程序與隨機生成的數據,這不會產生非常適合一個到簡體版本,但它說明了時間的問題:我無法想出一個辦法來優化這個部分,使其Python的配件:優化循環
import sys
sys.setrecursionlimit(5000)
import matplotlib.pyplot as plt
import numpy as np
import random
from random import uniform
x=[random.uniform(2200.,3100.) for p in range(0, 1000)]
y=[random.uniform(1.,1000.) for p in range(0, 1000)]
import sherpa.ui as ui
import numpy as np
ui.load_arrays(1,x,y) # 1 is the first data
d1=ui.get_data()
d1.staterror=0.002*d1.y # define error on y just for plotting purpose, not required for fit
ui.plot_data()
ui.set_stat("leastsq") # leasr square method for fit
ui.set_model(ui.powlaw1d.pow1) # fit powerlaw.. pow1 is the shortcut name
# ui.show_all() will show you all the parameters for the model
pow1.ref=2500
ui.fit()
# fitting templates
x2=[random.uniform(2200.,3100.) for p in range(0, 1000)]
y2=[random.uniform(1.,1000.) for p in range(0, 1000)]
model1="pow1" # initiliaze the model for fitting all the gaussians
sign="+"
sigma=45.
g_pos=x2
g_ampl=[] # we will store the fit value here
ui.freeze(model1) # freeze the powerlaw
for n in range(1,1000): # this excludes the upper limit
ui.create_model_component("gauss1d","g{}".format(n))
ui.set_par("g{}.pos".format(n),x2[n],frozen=True)
ui.set_par("g{}.ampl".format(n),y2[n])
ui.set_par("g{}.fwhm".format(n),sigma,frozen=True)
model1=model1+sign+"g{}".format(n)
if y2[n] == 0.:
g_ampl.append(0.) # list zero amplitude for this model
else:
g=ui.create_model_component("gauss1d","g{}".format(n)) # do this to store g_ampl of this model only
ui.set_source(model1) # overwriting with actual model
ui.fit()
ui.fit()
ui.fit()
g_ampl.append(g.ampl.val)
ui.freeze(model1) # freeze the model and go to the next gaussian
高效且耗時更少。任何想法,以幫助我讓它跑得更快,將不勝感激。
您的代碼無法運行。您可以編輯您的問題,以確保它包含[最小完整覈實的示例](http://stackoverflow.com/help/mcve)?很難理解你想要做什麼,甚至不知道你正在使用什麼軟件包。 –
希望這[鏈接](https://wiki.python.org/moin/PythonSpeed/PerformanceTips)可以提供幫助。所有我想改變「範圍」到「x範圍」 –
@CurtF。的 首先,我編輯的代碼,它可以對隨機生成的數據運行(如在程序)。我收錄了評論。請讓我知道它是否有幫助。 – Phyast10