0

I seem to recall encountering a Numpy or PyTorch method similar to numpy.tile, except that it allowed partial tiling to reach specified dimensions. So if I had

a = np.array([[5, 6, 7, 8],
              [1, 2, 3, 4]])

(or, correspondingly, t = torch.Tensor(a) if this is a PyTorch method),

then

a.mystery_method((3,4))

would produce output

array([[5, 6, 7, 8],
       [1, 2, 3, 4],
       [5, 6, 7, 8]])

Unfortunately, I now can't find this method in the Numpy or Pytorch docs. Does it actually exist, and what is it if so?

perigon
  • 2,160
  • 11
  • 16

1 Answers1

2

You can use np.resize -

M = 3 # number of rows for output
np.resize(a,(M,a.shape[1]))

Another way with np.take or simply indexing along the first axis for performance -

np.take(a,np.arange(M)%a.shape[0],axis=0) # with np.take
a[np.arange(M)%a.shape[0]]                # with indexing

Runtime test -

In [91]: a = np.random.randint(0,9,(2000,4000))

In [92]: M = 3000

In [93]: %timeit np.resize(a,(M,a.shape[1]))
10 loops, best of 3: 24.1 ms per loop

In [94]: %timeit np.take(a,np.arange(M)%a.shape[0],axis=0)
100 loops, best of 3: 16.2 ms per loop

In [95]: %timeit a[np.arange(M)%a.shape[0]]
100 loops, best of 3: 15.2 ms per loop
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • 1
    A warning - in older versions, `np.resize` had problems with referencing and slicing the created or original array and would throw `ValueErrors` that were difficult to trace. [`ndarray.resize`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.resize.html#numpy.ndarray.resize) still has this problem as per the docs. – Daniel F Jul 25 '17 at 10:47