我通過嵌套回圈創建了一個問題空間。我正在嘗試存盤結果(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)
如果有人可以提供幫助,我將不勝感激!謝謝!
uj5u.com熱心網友回復:
numpy允許您為和您的陣列創建單獨的維度d,從而為您留下一個可以索引到 ( ) 的陣列來恢復您需要的陣列。這可以保存為一個有組織的陣列,而不是一堆未索引的子陣列:un, 30(10, 10, n, 30)out[d, u]
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)
uj5u.com熱心網友回復:
假設您知道每個嵌套回圈中的迭代次數 (=10, 10, 30) 和v_hat(= 不管n是什么) 的形狀,您可以創建outfile一個帶有 shape 的 NumPy 陣列(10, 10, 30, n)。然后在每次迭代期間,您outfile可以outfile[d][u][j]用v_hat.
然后在最后,您可以保存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")
如果您有任何問題,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/461267.html
