Skip to content

Instantly share code, notes, and snippets.

@Atlas7
Last active September 13, 2017 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Atlas7/1d18e46299665eb995c95720d6c862be to your computer and use it in GitHub Desktop.
Save Atlas7/1d18e46299665eb995c95720d6c862be to your computer and use it in GitHub Desktop.
Initialize Numpy Arrays with Tuple Unpacking Technique, via np.random.rand and np.zeros examples

Introduction

Consider this numpy array A1, that has a shape 3 by 4 (axis 0 dimensions by axis 1 dimensions):

import numpy as np
A1 = np.arange(12).reshape(3,4)

#array([[ 0,  1,  2,  3],
#       [ 4,  5,  6,  7],
#       [ 8,  9, 10, 11]])

This post shows multiple (equivalent) methods to initialize a new numpy array that takes the same shape as A1 - with either random numbers or zeros. We will appreciate with the use of tuple unpacking, the code may be made shorter and more concise.

np.random.rand

The following 3 blocks will give the same result (and same shape as A1):

np.random.seed(1)
D1a = np.random.rand(A1.shape[0], A1.shape[1])

np.random.seed(1)
D1b = np.random.rand(*tuple(A1.shape))

np.random.seed(1)
D1c = np.random.rand(*(A1.shape))

#array([[  4.17022005e-01,   7.20324493e-01,   1.14374817e-04,
#          3.02332573e-01],
#       [  1.46755891e-01,   9.23385948e-02,   1.86260211e-01,
#          3.45560727e-01],
#       [  3.96767474e-01,   5.38816734e-01,   4.19194514e-01,
#          6.85219500e-01]])

First option is longest. Third option is shortest. (same concept goes to np.random.randn)

Note the * syntax. It's called tuple unpacking. It turns a tuple (3, 4), into a list of values 3, 4. In Numpy, the np.random.rand takes in a list of values (instead of a tuple). So we unpack the tuple into a list of values.

np.zeros

The following 3 lines will give the same result (and same shape as A1):

D1za = np.zeros((A1.shape[0], A1.shape[1]))
D1zb = np.zeros(tuple(A1.shape))
D1zc = np.zeros((A1.shape))    # this also works: D1zc = np.zeros(A1.shape)

#array([[ 0.,  0.,  0.,  0.],
#       [ 0.,  0.,  0.,  0.],
#       [ 0.,  0.,  0.,  0.]])

First option is longest. Third option is shortest.

Note that np.zeros takes in a tuple. So here we just feed in a tuple straight. No unpacking is required.

Conclusion

In this article we have presented 3 (from longest to shortest) methods to feed dimensions to the np.random.rand, np.random.randn, and np.zeros utilities. We observe with tuple and tuple unpacking tricks, the code may be made shorter and more concise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment