Basics of NumPy, matplotlib and SciPy

Bikash Santra

Research Scholar, Indian Statistical Institute, Kolkata

NumPy¶

In [1]:
import numpy as np
In [2]:
A1 = np.array([[1,2,3,4,8]])
A = np.array([1,2,3,4,8])
B = np.array([1,2,3,10,20])
print(A1.shape, B.shape)
print(type(A1), type(B))
((1, 5), (5,))
(<type 'numpy.ndarray'>, <type 'numpy.ndarray'>)
In [3]:
c = np.zeros((2,2))
print(c)
print(type(c))
[[ 0.  0.]
 [ 0.  0.]]
<type 'numpy.ndarray'>
In [4]:
c = np.ones((3,3))
print(c)
[[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]
In [5]:
c = np.full((3,3),10)
print(c)
[[10 10 10]
 [10 10 10]
 [10 10 10]]
In [6]:
c = np.eye((4))
print(c)
[[ 1.  0.  0.  0.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]
In [7]:
d = np.random.random((2,3))
print(d)
[[ 0.13347464  0.87774393  0.90664143]
 [ 0.04115962  0.11057935  0.82196922]]
In [8]:
r = np.random.normal()
print(r)
-0.746379890817
In [9]:
r1 = np.random.randint(1,10,100)
print(r1)
[5 4 8 6 8 5 5 8 6 4 2 2 9 9 2 3 8 3 6 6 9 4 4 5 2 5 3 2 2 1 7 7 4 6 4 1 6
 9 6 2 6 3 3 9 1 1 9 4 8 8 5 4 2 4 4 2 2 8 5 3 1 5 5 8 5 3 8 8 8 1 8 9 6 5
 9 7 5 9 7 7 6 2 7 2 5 9 3 4 8 3 5 2 6 7 7 8 5 8 4 9]
In [10]:
r2 = np.random.randint(1,10,(4,5))
print(r2)
[[7 8 9 5 5]
 [8 8 7 9 3]
 [7 7 8 9 9]
 [1 4 2 2 2]]
In [11]:
y = np.empty_like(r2)
print(y)
[[    139953336601624            44346192                   0
                    0                   0]
 [7310593858020254331 4049070531863519844 3482467996703862829
  3328776101189466677 2475346153545413171]
 [7236833184642769452 7881144752318672485 7310875413622977637
  8319683848551211564 2462380941086177826]
 [4189022128297176677 3976741372411994402 3759771654807629109
  3474301034786338098 3834310626855380013]]
In [12]:
y = np.zeros_like(r2)
print(y)
[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]
In [13]:
y = np.ones_like(r2)
print(y)
[[1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]]
In [14]:
print(r2.T) # Transpose
[[7 8 7 1]
 [8 8 7 4]
 [9 7 8 2]
 [5 9 9 2]
 [5 3 9 2]]
In [15]:
x = np.array([[1,2],[3,4]])
print(np.sum(x))  # Compute sum of all elements; prints "10"
print(np.sum(x, axis=0))  # Compute sum of each column; prints "[4 6]"
print(np.sum(x, axis=1))  # Compute sum of each row; prints "[3 7]"
10
[4 6]
[3 7]
In [16]:
print(np.sqrt(x))
[[ 1.          1.41421356]
 [ 1.73205081  2.        ]]
In [17]:
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
In [18]:
print(x+y)

print(np.add(x,y))
[[ 6  8]
 [10 12]]
[[ 6  8]
 [10 12]]
In [19]:
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])

v = np.array([9,10])
w = np.array([11, 12])
print(x)
print(y)
print(v)
print(w)
[[1 2]
 [3 4]]
[[5 6]
 [7 8]]
[ 9 10]
[11 12]
In [20]:
print(v.dot(w))
print('---------------')
print(np.dot(v, w))
219
---------------
219
In [21]:
print(x.dot(v))
print('---------------')
print(np.dot(x, v))
[29 67]
---------------
[29 67]
In [22]:
print(np.dot(v, x))
[39 58]
In [23]:
x = np.array([[1,2], [3,4]])
print(x)
[[1 2]
 [3 4]]
In [24]:
a2d = np.array([[1,2,3],[4,5,6]])
b2d = np.array([[10,4,6],[2,4,6]])
print(a2d.shape)

r, c = b2d.shape
print(r,c)
(2, 3)
(2, 3)
In [25]:
c2d = a2d.T # Transpose
print(c2d)
print(a2d)
[[1 4]
 [2 5]
 [3 6]]
[[1 2 3]
 [4 5 6]]
In [26]:
# Element wise multiplication
d2d = a2d * b2d
print(d2d)

d2d = np.multiply(a2d, b2d)
print(d2d)
[[10  8 18]
 [ 8 20 36]]
[[10  8 18]
 [ 8 20 36]]
In [27]:
# Matrix multiplication
e2d = np.dot(a2d,c2d)
print(e2d)

e2d = np.matmul(a2d,c2d)
print(e2d)
[[14 32]
 [32 77]]
[[14 32]
 [32 77]]
In [28]:
det1 = np.linalg.det(e2d)
print(det1)
54.0
In [29]:
eig, eig1 = np.linalg.eig(e2d)
print(eig)
print(eig1)
[  0.59732747  90.40267253]
[[-0.92236578 -0.3863177 ]
 [ 0.3863177  -0.92236578]]
In [30]:
inv1 = np.linalg.inv(e2d)
print(inv1)
[[ 1.42592593 -0.59259259]
 [-0.59259259  0.25925926]]
In [31]:
ind = a2d>2
print(ind)
[[False False  True]
 [ True  True  True]]
In [32]:
print(a2d[ind])
[3 4 5 6]
In [33]:
print(np.sum(A))
print(np.mean(A))
print(np.median(A))
print(np.var(A))
print(np.std(A))
18
3.6
3.0
5.84
2.41660919472
In [34]:
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
In [35]:
b = a[:2,1:3] #Last exclusive
print(b)
[[2 3]
 [6 7]]
In [36]:
b[0, 0] = 77 
print(b)
print(a)
[[77  3]
 [ 6  7]]
[[ 1 77  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
In [37]:
c = np.copy(a)
print(c)
[[ 1 77  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
In [38]:
c[0,0] = 105
print(c)
print(a)
[[105  77   3   4]
 [  5   6   7   8]
 [  9  10  11  12]]
[[ 1 77  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
In [39]:
a = np.array([[1,2], [3, 4], [5, 6]])
print(a)

print(a[[0, 1, 2], [0, 1, 0]]) ## localtion (0,0), (1,1), (2,0)

print(np.array([a[0, 0], a[1, 1], a[2, 0]]))
[[1 2]
 [3 4]
 [5 6]]
[1 4 5]
[1 4 5]
In [40]:
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print(a)

b = np.array([0, 2, 0, 1])
print(b)
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
[0 2 0 1]
In [41]:
print(a[np.arange(4), b])
[ 1  6  7 11]
In [42]:
a[np.arange(4), b] += 10
print(a)
[[11  2  3]
 [ 4  5 16]
 [17  8  9]
 [10 21 12]]
In [43]:
x = np.array([1, 2])
print(x.dtype)
int64
In [44]:
x = np.array([1.0, 2.0])
print(x.dtype)
float64
In [45]:
x = np.array([1, 2], dtype=np.int64)
print(x.dtype)
int64
In [46]:
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

print(x+y)
[[  6.   8.]
 [ 10.  12.]]
In [47]:
v = np.array([1,2,3])
In [48]:
print(v)    # Prints "[1 2 3]"
print(v.T)  # Prints "[1 2 3]"
[1 2 3]
[1 2 3]
In [49]:
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
In [50]:
y = np.zeros_like(x)
print(y)
[[0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]
In [51]:
for i in range(4):
    y[i, :] = x[i, :] + v
In [52]:
print(y)
print(x)
[[ 2  2  4]
 [ 5  5  7]
 [ 8  8 10]
 [11 11 13]]
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
In [53]:
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print(x)
v = np.array([1, 0, 1])
print(v)
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
[1 0 1]
In [54]:
vv = np.tile(v, (4, 1))   # Stack 4 copies of v on top of each other
print(vv)                 # Prints "[[1 0 1]
                          #          [1 0 1]
                          #          [1 0 1]
                          #          [1 0 1]]"
y = x + vv  # Add x and vv elementwise
print(y)  # Prints "[[ 2  2  4
          #          [ 5  5  7]
          #          [ 8  8 10]
          #          [11 11 13]]"
[[1 0 1]
 [1 0 1]
 [1 0 1]
 [1 0 1]]
[[ 2  2  4]
 [ 5  5  7]
 [ 8  8 10]
 [11 11 13]]
In [55]:
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v  # Add v to each row of x using broadcasting
print(y)  # Prints "[[ 2  2  4]
          #          [ 5  5  7]
          #          [ 8  8 10]
          #          [11 11 13]]"
[[ 2  2  4]
 [ 5  5  7]
 [ 8  8 10]
 [11 11 13]]
In [56]:
v = np.array([[1,2,3],[4,5,6]])
w = np.array([4,5])
print(np.reshape(v, (3, 2)))
[[1 2]
 [3 4]
 [5 6]]
In [57]:
v = np.array([1,2,3])  # v has shape (3,)
w = np.array([4,5])    # w has shape (2,)
print(np.reshape(v, (3, 1)) * w)
[[ 4  5]
 [ 8 10]
 [12 15]]
In [58]:
help(np.random)

matplotlib¶

In [59]:
import matplotlib.pyplot as plt
In [60]:
x = np.arange(-100,100,0.5) # Return evenly spaced values within a given interval
y = x**2
In [61]:
plt.plot(x,y)
plt.xlabel('X-axis')
plt.ylabel('Y-label')
plt.show()
In [62]:
x = np.arange(1,101)
print(x)
print(x.shape)
[  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
  91  92  93  94  95  96  97  98  99 100]
(100,)
In [63]:
marks = np.random.randint(1,100,100)
marks1 = np.random.randint(1,100,100)
In [64]:
width = 0.5
plt.bar(x,marks)
plt.show()
In [65]:
plt.plot(x,marks,'*') # displaying points
plt.plot(x,marks1,'+')
plt.show()

SciPy¶

In [66]:
from scipy.misc import imread, imsave, imresize, imshow
In [67]:
img = imread('cat.jpg')
In [68]:
print(img.dtype, img.shape)
(dtype('uint8'), (400, 248, 3))
In [69]:
img_tinted = img * [1, 0.95, 0.9]
#plt.figure()
plt.imshow(img)
#plt.imshow(img_tinted)
plt.show()
plt.imshow(img_tinted)
plt.show()
In [70]:
imsave('cat_tinted.jpg', img_tinted)
In [71]:
# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Plot the points using matplotlib
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
plt.show()
In [72]:
import numpy as np
import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)

# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')

# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')

# Show the figure.
plt.show()

References¶

a) https://github.com/kuleshov/cs228-material/blob/master/tutorials/python/cs228-python-tutorial.ipynb
b) https://docs.scipy.org/doc/numpy-dev/user/quickstart.html
c) https://matplotlib.org/users/pyplot_tutorial.html
d) https://docs.scipy.org/doc/scipy/reference/tutorial/index.html

Click here to download the source code of this tutorial.