保存嵌套 For 循环的产品(存储网格)

Save product of a nested For Loop (Storage Grid)

我通过嵌套循环创建了一个问题 space。 我正在尝试存储结果 (v_hat),因此我可以“调用”特定问题 P(d,u) 并获得相应的 30 个数组。

outfile = TemporaryFile()
n = 10
w = np.random.normal(60, 3, n)
for d in range(10):
    r = np.random.uniform(0.1 * d, 0.2 * d)
    v = w * r
    for u in range(10):
        c = np.random.uniform(0.1 * u, 0.2 * u)
        sigma = v * c
        for j in range(30):
            v_hat = np.random.normal(v, sigma)  
            np.save(outfile, v_hat)
np.load(outfile)

我试过 np.save 但它不起作用,即使它起作用了,我也不知道如何调用特定的 P(d,u)

如果有人能提供帮助,我将不胜感激!谢谢!

numpy 允许您为 dun, 30 数组创建单独的维度,留下一个可以索引的 (10, 10, n, 30) 数组进入 (out[d, u]) 以恢复您需要的数组。这可以保存为一个有组织的数组而不是一堆 un-indexed sub-arrays:

import numpy as np

def v_hat_gen(n, dmax, umax, i, fn = None):
    w = np.random.normal(60, 3, n)
    r = np.random.uniform(0.1 * np.arange(dmax), 0.2 * np.arange(dmax))
    v = np.einsum('i, jk -> ijk', r, w[None, :])
    c = np.random.uniform(0.1 * np.arange(umax), 0.2 * np.arange(umax), size = (umax, dmax)).T
    sigma = v*c[..., None]
    v_hat = np.random.normal(v[...,None], sigma[...,None], size = sigma.shape + (i,))
    if fn:
        with np.open(fn, 'wb') as f:
            np.save(f, v_hat)
    return v_hat

out = v_hat_gen(5, 10, 10, 30)
print(out.shape)

Out[]: (10, 10, 5, 30)

鉴于您知道每个嵌套循环中的迭代次数 (=10, 10, 30) 和 v_hat 的形状(= 无论 n 是什么),您可以使 outfile 形状为 (10, 10, 30, n) 的 NumPy 数组。然后在每次迭代期间,您可以用 v_hat.

替换 outfile 中的适当行(其中适当的行是 outfile[d][u][j]

然后在最后,你可以保存outfile。这是代码:

# You can set n to whatever you want; I tested for various n and the code always works
n = 8

# Make outfile the necessary size
outfile = np.zeros((10, 10, 30, n), dtype=float)

w = np.random.normal(60, 3, n)

for d in range(10):
    r = np.random.uniform(0.1 * d, 0.2 * d)
    v = w * r

    for u in range(10):
        c = np.random.uniform(0.1 * u, 0.2 * u)
        sigma = v * c

        for j in range(30):
            v_hat = np.random.normal(v, sigma)  

            # Index the appropriate row in outfile and replace with this iteration's v_hat
            outfile[d][u][j] = v_hat

# Save outfile to a txt file. Change the path as desired.
np.savetxt("file.txt", outfile)

# How to read in the txt. Make sure the path here and in the line above match
outfile_loaded = np.loadtxt("file.txt")

如果您有任何问题,请告诉我。