重复一个函数 1000 次并将每次迭代结果保存在列表中

Repeating a function 1000 times and saving each iteration result in a list

我试图模拟一些实验的事件发生和预测因子。我有两个预测变量(圆圈和正方形)。刺激 ('events') 需要 1 秒,ISI(刺激间隔)为 8 秒。我也对与基线的对比感兴趣(圆圈与基线;正方形与基线)。最后,我试图 运行 我定义的函数(simulate_data_fixed,n=420 是一个固定的参数)1000,在每次迭代中我想计算一个效率分数最后并将效率分数存储在列表中。

def simulate_data_fixed_ISI(N=420):

    dg_hrf = glover_hrf(tr=1, oversampling=1)
    
    # Create indices in regularly spaced intervals (9 seconds, i.e. 1 sec stim + 8 ISI)
    stim_onsets = np.arange(10, N - 15, 9)
    stimcodes = np.repeat([1, 2], stim_onsets.size / 2)  # create codes for two conditions
    np.random.shuffle(stimcodes)  # random shuffle
    stim = np.zeros((N, 1))

    c = np.array([[0, 1, 0], [0, 0, 1]])

    # Fill stim array with codes at onsets
    for i, stim_onset in enumerate(stim_onsets):
        stim[stim_onset] = 1 if stimcodes[i] == 1 else 2
    
    stims_A = (stim == 1).astype(int)
    stims_B = (stim == 2).astype(int)

    reg_A = np.convolve(stims_A.squeeze(), dg_hrf)[:N]
    reg_B = np.convolve(stims_B.squeeze(), dg_hrf)[:N]
    X = np.hstack((np.ones((reg_B.size, 1)), reg_A[:, np.newaxis], reg_B[:, np.newaxis]))
    dvars = [(c[i, :].dot(np.linalg.inv(X.T.dot(X))).dot(c[i, :].T))
             for i in range(c.shape[0])]
    eff = c.shape[0] / np.sum(dvars)
    return eff

但是,我想 运行 整个块 1000 次并将 'eff' 存储在数组等中,以便稍后我想将它们显示为直方图。我该怎么做?

如果我理解正确的话你应该可以 运行

EFF = [simulate_data_fixed_ISI() for i in range(1000)] #1000 repeats

正如@theonlygusti 澄清的那样,这一行 EFF,运行 将你的函数 simulate_data_fixed_ISI() 执行 1000 次,并将每个 return 放入数组 EFF

测试

import numpy as np
def simulate_data_fixed_ISI(n=1):
    """
    Returns 'n' random numbers
    """
    return np.random.rand(n)

EFF = [simulate_data_fixed_ISI() for i in range(5)]

EFF
#[array([0.19585137]),
# array([0.91692933]),
# array([0.49294667]),
# array([0.79751017]),
# array([0.58294512])]

您的问题似乎可以归结为:

I am trying to run the function that I have defined for 1000, at each iteration I would like to calculate an efficiency score in the end and store the efficiency scores in a list

我猜“我定义的函数”是你问题中的simulate_data_fixed_ISI

然后您可以简单地 运行 使用基本的 for 循环 1000 次,并将结果添加到列表中:

def simulate_data_fixed_ISI(N=420):

    dg_hrf = glover_hrf(tr=1, oversampling=1)
    
    # Create indices in regularly spaced intervals (9 seconds, i.e. 1 sec stim + 8 ISI)
    stim_onsets = np.arange(10, N - 15, 9)
    stimcodes = np.repeat([1, 2], stim_onsets.size / 2)  # create codes for two conditions
    np.random.shuffle(stimcodes)  # random shuffle
    stim = np.zeros((N, 1))

    c = np.array([[0, 1, 0], [0, 0, 1]])

    # Fill stim array with codes at onsets
    for i, stim_onset in enumerate(stim_onsets):
        stim[stim_onset] = 1 if stimcodes[i] == 1 else 2
    
    stims_A = (stim == 1).astype(int)
    stims_B = (stim == 2).astype(int)

    reg_A = np.convolve(stims_A.squeeze(), dg_hrf)[:N]
    reg_B = np.convolve(stims_B.squeeze(), dg_hrf)[:N]
    X = np.hstack((np.ones((reg_B.size, 1)), reg_A[:, np.newaxis], reg_B[:, np.newaxis]))
    dvars = [(c[i, :].dot(np.linalg.inv(X.T.dot(X))).dot(c[i, :].T))
             for i in range(c.shape[0])]
    eff = c.shape[0] / np.sum(dvars)
    return eff


eff_results = []
for _ in range(1000):
    efficiency_score = simulate_data_fixed_ISI()
    eff_results.append(efficiency_score)
    

现在 eff_results 包含 1000 个条目,每个条目都是对函数的调用 simulate_data_fixed_ISI