A few Numpy Functions

Today I was taking the deep learning course from Udacity, they use numpy very often in that class and here are some notes about a few handy numpy functions that I learned.

np.arange

arange is not a typo, it is simply a function very much like built-in range function but return a ndarray instead of list, that is probably why it is called a(rray)range. Here is the source code for arange in case you are interested.

In [33]: np.arange(-1, 1, 0.5)
Out[33]: array([-1. , -0.5,  0. ,  0.5])
In [51]: np.arange(12).reshape((3,4))

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

np.vstack

v(ertically)stack all the passed ndarray/list into a new array.

In [37]: np.vstack([[1,2], [3,4], [5,6], [7,8]])

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

At the same time, you have other sibling utility functions like hstack, concatenate ..etc. that have a very similar usage.

In [38]: np.hstack([[1,2], [3,4], [5,6]])
Out[38]: array([1, 2, 3, 4, 5, 6])

np.sum

the sum is pretty straight-forward, summing up all the numbers, however, there is one pitfall that I fell over is did not pay attention to the argument ‘axis‘. 0 means column wise and 1 means row wise.

In [53]: x

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

In [54]: x.sum(0)

Out[54]: array([12, 15, 18, 21])

In [55]: x.sum(1)

Out[55]: array([ 6, 22, 38])

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s