Sunday, February 25, 2018

NumPy Basics for Machine Learning

Numpy Basics:

Start the Python interactive shell as shown below:

step 1 : open cmd as administrator
step 2: at command prompt (ex: C:\Windows\System32> ) Type as python
          it looks like : C:\Windows\System32> python






Here i am using Python 3.6.3.
Now you are at python interactive terminal.
These two steps are common for any interactive program practice. So remember these two steps to invoke the python interactive session.

Now we need numpy

>>> import numpy
>>> numpy.version.full_version
'1.13.3'

these above steps will give the numpy version 1.13.3

How to create an array using Numpy?


>>> import numpy as np
>>> a = np.array ( [0,1,2,3,4,5] )
>>> a
array ( [0, 1, 2, 3, 4, 5] )

>>> a.ndim  
1

>>> a.shape
(6, )

in the above step a.ndim gives the dimensions  (i.e, 1 dimension , or 2 dimension, etc.)  and  a.shape gives the number of elements in the array.


How to transform an array into 2D matrix?

>>> b = a.reshape ((3, 2))
>>> b
array ([[0, 1],
            [2, 3],
            [4, 5] ] )

>>> b.ndim
2

>>> b.shape
(3, 2)

    a.reshape((3,2)) means rows = 3 and columns = 2.
the array a is transformed into 2D matrix in 3 rows and 2 columns and the result is stored in b array.


How to update an element in array b ?


>>> b[1][0] = 77
>>> b
array([[ 0, 1],
           [77, 3],
           [ 4, 5]])

>>> a
array([ 0, 1, 77, 3, 4, 5])

Here we updated an element in 2nd row , first column with 77 using b[1][0]=77. The the value in array a is also updated with the new value 77 ( as shown in the last line).


How to get true copy ?

>>> c = a.reshape((3,2)).copy()
>>> c
array([[ 0, 1],
           [77, 3],
            [ 4, 5]])

>>> c[0][0] = -99
>>> a
array([ 0, 1, 77, 3, 4, 5])

>>> c
array([[-99, 1],
             [77, 3],
              [ 4, 5]])


Here, c and a are totally independent copies.

Another big advantage of NumPy arrays is that the operations are propagated
to the individual elements.

>>> a*2
array([ 2, 4, 6, 8, 10])

>>> a**2
array([ 1, 4, 9, 16, 25])

Contrast that to ordinary Python lists:

>>> [1,2,3,4,5]*2
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

>>> [1,2,3,4,5]**2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'list' and
'int'

Of course, by using NumPy arrays we sacrifice the agility Python lists offer. Simple
operations like adding or removing are a bit complex for NumPy arrays. Luckily,
we have both at our disposal, and we will use the right one for the task at hand.