Search code examples
pythonnumpypytorcharray-broadcasting

What is the numpy equivalent of expand in pytorch?


Suppose I have a numpy array x of shape [1,5]. I want to expand it along axis 0 such that the resulting array y has shape [10,5] and y[i:i+1,:] is equal to x for each i.

If x were a pytorch tensor I could simply do

y = x.expand(10,-1)

But there is no expand in numpy and the ones that look like it (expand_dims and repeat) don't seem to behave like it.


Example:

>>> import torch
>>> x = torch.randn(1,5)
>>> print(x)
tensor([[ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724]])
>>> print(x.expand(10,-1))
tensor([[ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724]])

Solution

  • You can achieve that with np.broadcast_to. But you can't use negative numbers:

    >>> import numpy as np
    >>> x = np.array([[ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724]])
    >>> print(np.broadcast_to(x,(10,5)))
    [[ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
     [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
     [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
     [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
     [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
     [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
     [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
     [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
     [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
     [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]]