简体   繁体   中英

How to merge specific axes without ambuigity with numpy.ndarray

Basically I want to reshape tensors represented by numpy.ndarray.

For example, I want to do something like this (latex notation)

A_{i,j,k,l,m,n,p} -> A_{i,jk,lm,np}

or

A_{i,j,k,l,m,n,p} -> A_{ij,k,l,m,np}

where A is an ndarray. i,j,k,... denotes the original axes.

so the new axis 2 becomes the "flattened" version of axis 2 and 3, etc. If I simply use numpy.reshape, I don't think it knows what axes I want to merge, so it seems ambiguous and error prone.

Is there any neat way of doing this rather than creating another ndarray manually?

Using reshape is never ambiguous. It doesn't change the memory-layout of the data.

Indexing is always done using the strides determined by the shape. The right-most axis has stride 1, while the axes to the left have strides given by the product of the sizes to their right.

That means for you: as long as you collect neighboring axes, it will do the "right" thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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