5

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]])
flawr
  • 10,814
  • 3
  • 41
  • 71
ihdv
  • 1,927
  • 2
  • 13
  • 29
  • numpy.reshape (https://numpy.org/doc/stable/reference/generated/numpy.reshape.html) might be what you're looking for? – DaveIdito Dec 10 '20 at 12:45
  • @DaveIdito No. reshape merely changes the shape, while `expand` essentially copies the data to new dimensions. – ihdv Dec 10 '20 at 12:49

3 Answers3

10

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]]
flawr
  • 10,814
  • 3
  • 41
  • 71
2

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)

scarecrow
  • 6,624
  • 5
  • 20
  • 39
-1

numpy has numpy.newaxis

y = x[:, np.newaxis]
Konstantin
  • 548
  • 3
  • 10
  • I think this is not what OP is lookingfor: This just adds a new dimension, but doesn't extend existing dimensions. – flawr Dec 10 '20 at 13:01
  • Expanding is usually used to multiply vector by matrix. numpy has broadcasting https://numpy.org/doc/stable/user/basics.broadcasting.html so extending may be redundant – Konstantin Dec 10 '20 at 14:08
  • Yes indeed, that works exactly the same as in pytorch. But explicitly doing so uses a slightly different method. – flawr Dec 10 '20 at 22:43