如何批量拆分numpy数组?

pbu*_*pbu 6 python numpy

这听起来很容易,但我不知道该怎么做。

我有 numpy 二维数组

X = (1783,30)
Run Code Online (Sandbox Code Playgroud)

我想将它们分成 64 个批次。我这样编写代码。

batches = abs(len(X) / BATCH_SIZE ) + 1  // It gives 28
Run Code Online (Sandbox Code Playgroud)

我正在尝试批量预测结果。所以我用零填充批次,并用预测结果覆盖它们。

predicted = []

for b in xrange(batches): 

 data4D = np.zeros([BATCH_SIZE,1,96,96]) #create 4D array, first value is batch_size, last number of inputs
 data4DL = np.zeros([BATCH_SIZE,1,1,1]) # need to create 4D array as output, first value is  batch_size, last number of outputs
 data4D[0:BATCH_SIZE,:] = X[b*BATCH_SIZE:b*BATCH_SIZE+BATCH_SIZE,:] # fill value of input xtrain

 #predict
 #print [(k, v[0].data.shape) for k, v in net.params.items()]
 net.set_input_arrays(data4D.astype(np.float32),data4DL.astype(np.float32))
 pred = net.forward()
 print 'batch ', b
 predicted.append(pred['ip1'])

print 'Total in Batches ', data4D.shape, batches
print 'Final Output: ', predicted
Run Code Online (Sandbox Code Playgroud)

但是在最后一个批次号 28 中,只有 55 个元素而不是 64 个(总元素 1783),它给出了

ValueError: could not broadcast input array from shape (55,1,96,96) into shape (64,1,96,96)

有什么办法解决这个问题?

PS:网络预测需要精确的批量大小为 64 才能预测。

pol*_*i_g 11

我也不太明白你的问题,尤其是 X 的样子。如果要创建数组大小相同的子组,请尝试以下操作:

def group_list(l, group_size):
    """
    :param l:           list
    :param group_size:  size of each group
    :return:            Yields successive group-sized lists from l.
    """
    for i in xrange(0, len(l), group_size):
        yield l[i:i+group_size]
Run Code Online (Sandbox Code Playgroud)


pbu*_*pbu 1

我找到了一种解决批量问题的简单方法,即生成虚拟数据,然后填充必要的数据。

data = np.zeros(batches*BATCH_SIZE,1,96,96)
// gives dummy  28*64,1,96,96
Run Code Online (Sandbox Code Playgroud)

此代码将准确加载 64 个批量大小的数据。最后一批最后会有虚拟零,但没关系:)

pred = []
for b in batches:
 data4D[0:BATCH_SIZE,:] = data[b*BATCH_SIZE:b*BATCH_SIZE+BATCH_SIZE,:]
 pred = net.predict(data4D)
 pred.append(pred)

output =  pred[:1783] // first 1783 slice
Run Code Online (Sandbox Code Playgroud)

最后我从 28*64 的总数中切出了 1783 个元素。这对我有用,但我确信有很多方法。