从返回NumPy数组的循环中收集结果 [英] Collecting results from a loop that returns NumPy Arrays
问题描述
我是一位公认的非常基本的Python程序员,试图在遇到各种研究问题的过程中学习.而且我遇到了这些问题之一-特别是如何处理循环,在该循环中我要返回一堆数据,而不是通常的单数输出"示例,您只需将循环的结果添加到之前的所有内容中
I'm an admittedly pretty basic Python programmer, trying to learn as I encounter problems implementing various research problems. And I've hit one of those problems - particularly, how to handle loops where I'm returning a bunch of data, rather than the usual "out comes a single number" examples where you just add the result of the loop to everything previous.
以下是我要运行的未循环脚本的要点: https://gist.github.com/1390355
Here's a Gist of the unlooped script I'm trying to run: https://gist.github.com/1390355
真正的重点是model_solve函数的结尾:
The really salient point is the end of the model_solve function:
def model_solve(t):
# lots of variables set
params = np.zeroes((n_steps,n_params)
params[:,0] = beta
params[:,1] = gamma
timer = np.arange(n_steps).reshape(n_steps,1)
SIR = spi.odeint(eq_system, startPop, t_interval)
output = np.hstack((timer,SIR,params))
return output
这将返回ODE积分位(spi.odeint
)的结果以及一个简单的我们在什么时间步?"计时器和本质上是两列的两个随机变量的值以4950行和7列NumPy数组的形式重复很多次.
That returns the results of the ODE integration bit (spi.odeint
) along with a simple "What time step are we on?" timer and essentially two columns of the value of two random variables repeated many, many times in the form of 4950 row and 7 column NumPy array.
但是,目标是对两个具有随机值的参数(β和γ)进行蒙特卡洛分析.本质上,我想制作一个像这样循环的函数:
The goal however is to run a Monte Carlo analysis of the two parameters (beta and gamma) which have random values. Essentially, I want to make a function that loops somewhat like so:
def loop_function(runs):
for i in range(runs):
model_solve(100)
# output of those model_solves collected here
# return collected output
所收集的输出随后将被写入文件.通常,我只需要将每个model_solve函数的结果写入文件中,但是此代码将在 PiCloud 上运行或其他平台,在结果返回到本地计算机之前,我不一定有能力写文件.相反,我试图返回由runs
* 7列和4950行组成的NumPy大型数组-然后可以将其写入本地计算机上的文件中.
That collected output would then be written to a file. Normally, I'd just have each model_solve function write its results to a file, but this code is going to be run on PiCloud or another platform where I don't necessarily have the ability to write a file until the results are returned to the local machine. Instead, I'm trying to get a return of a huge NumPy array of runs
*7 columns and 4950 rows - which can then be written to a file on my local machine.
关于如何解决这个问题的任何线索吗?
Any clues as to how to approach this?
推荐答案
使用列表保存所有结果:
use a list to save all the results:
results = []
for i in range(runs):
results.append(model_solve(100))
然后通过以下方式获取输出数组:
then get the output array by:
np.hstack(results)
这篇关于从返回NumPy数组的循环中收集结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!