What is the numpy equivalent of expand in pytorch?

Question:

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]])
Asked By: ihdv

||

Answers:

numpy has numpy.newaxis

y = x[:, np.newaxis]
Answered By: KonstantinTogoi

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]]
Answered By: flawr

You can use np.tile which repeats the elements of a given axis as:

>>> x = np.range(5)
>>> x = np.expand_dims(x, 0)
>>> x.shape
(1, 5)
>>> y = np.tile(x, (10, 1))  # repeat axis=0 10 times and axis=1 1 time
>>> y.shape
(10, 5)

Answered By: scarecrow