让我们假设我们有一个变量(形状(1,N,a,b,c)),它存储具有形状(a,b,c)的numpy数组。我首先要用零初始化这个变量
import numpy as np
N = 5
a = 20
b = 40
c = 4
storage = np.zeros(1, N, a, b, c)
# collect new arrays
while True:
values = np.random.random((a, b, c)) # np.array with shape (a, b, c)
save_values_to_storage(values)
函数save_values_to_storage(values)的目标是填充存储中的值。在第一个循环中,存储的(1,N,...)值将用values
填充。在下一个循环(1,N,...)中,存储的值将用values
填充,之前的值将移动到(1,N-1,...)。等等。如果第一次存储values
到达第一个位置(1,1,...)并且检索并存储新的values
,则第一个values
将被抛弃,使得新的values
被存储在位置(1,N,...)并且所有其他价值因其位置而减少。
我不知道如何才能实现这样的行为。它类似于numpy数组的队列。所以我的问题是如何实现
save_values_to_storage(values)
功能?
编辑:似乎deque
是相似的。但我不知道如何将它们用于numpy数组
我想我解决了这个问题。我不确定这是否是最好的方法。我感谢任何改进。
import numpy as np
import random
N = 5
a = 20
b = 40
c = 4
inputs = np.zeros((N, a, b, c))
for i in range(0, 10):
# replace right hand side with method that gets values
values = np.random.random((a, b, c))
# expand the dimension to fit to inputs
values = np.expand_dims(values, axis=0)
# delete values in first entry of inputs
inputs = np.delete(inputs, obj=0, axis=0)
# concatenate inputs and values to a new array
inputs = np.concatenate([inputs, values], axis=0)
# for debugging
# print('shape: {}'.format(inputs.shape))
# expand the dimension with an additional first dimension to achieve (1, N, a, b, c) # shape.
inputs = np.expand_dims(inputs, axis = 0)