简体   繁体   English

如何使 numpy.reshape 用作特定的 for 循环

[英]How to make numpy.reshape to work as a specific for loop

I have a 4 dimension list that contains numpy arrays. The following general shape is expected for this list num_batches,50,batch_size,27 .我有一个包含 numpy arrays 的 4 维列表。此列表num_batches,50,batch_size,27预计具有以下一般形状。 The last batch (ie, num_batches = -1 ) usually has instances less than batch_size .最后一批(即num_batches = -1 )的实例通常小于batch_size So, if you loop over the first axis and print the dimension you will see something like: (50,100,27),(50,100,27),...,(50,100,27),(50,85,27) I would like to reshape it such that it has the dimensions 50,all_samples_num,27 , where all_samples_num is the sum of the second dimension of the printed dimensions.因此,如果您遍历第一个轴并打印尺寸,您将看到类似以下内容的内容: (50,100,27),(50,100,27),...,(50,100,27),(50,85,27)我会喜欢重塑它,使其具有尺寸50,all_samples_num,27 ,其中all_samples_num是打印尺寸的第二个尺寸的总和。 At first, I wrote the following for loop:起初,我写了以下 for 循环:

tt = np.empty((50,0,27))
for ttt in x:
    i = i + 1
    tmp = []
    for t in ttt:
        tmp.append(t)
    tt = np.append(tt, np.array(tmp),axis=1)

When I wanted to optimize the code, I used the following reshaping code:当我想优化代码时,我使用了以下重塑代码:

xx = np.array(x[:-1].tolist()).reshape(50,-1,27)
xx = np.concatenate((xx,np.array(x[-1].tolist()).reshape(50,-1,27)),axis=0)

However, tt and xx are not equivalent.但是, ttxx并不等价。 I tried C-order and F-order of reshape but still the resulting array is not equivalent to tt .我尝试了 C-order 和 F-order of reshape但结果数组仍然不等同于tt How can I manipulate reshape such that it does give something identical to tt ?我怎样才能操纵reshape使其确实给出与tt相同的东西?

"concatenate" is the API you are seeking. “concatenate”就是你要找的API。 "reshape" changes the interpretation of the addressing without really changing the data. “重塑”改变了寻址的解释,而没有真正改变数据。

import numpy as np

x1 = np.random.randint(100,size=(50,5,27))
x2 = np.random.randint(100,size=(50,15,27))
x3 = np.random.randint(100,size=(50,9,27))
x4 = np.random.randint(100,size=(50,3,27))

i = np.concatenate( (x1,x2,x3,x4), axis=1)
print(i.shape)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM