What is the numpy equivalent of expand in pytorch?
Asked Answered
M

3

6

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]])
Mayoralty answered 10/12, 2020 at 12:42 Comment(2)
numpy.reshape (numpy.org/doc/stable/reference/generated/numpy.reshape.html) might be what you're looking for?Sexlimited
@Sexlimited No. reshape merely changes the shape, while expand essentially copies the data to new dimensions.Mayoralty
C
13

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]]
Consanguinity answered 10/12, 2020 at 13:0 Comment(0)
A
3

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)

Ampliate answered 10/12, 2020 at 13:0 Comment(0)
L
-1

numpy has numpy.newaxis

y = x[:, np.newaxis]
Liberati answered 10/12, 2020 at 12:58 Comment(3)
I think this is not what OP is lookingfor: This just adds a new dimension, but doesn't extend existing dimensions.Consanguinity
Expanding is usually used to multiply vector by matrix. numpy has broadcasting numpy.org/doc/stable/user/basics.broadcasting.html so extending may be redundantLiberati
Yes indeed, that works exactly the same as in pytorch. But explicitly doing so uses a slightly different method.Consanguinity

© 2022 - 2024 — McMap. All rights reserved.