Python - NumPy

TensorFlow uses NumPy. So I wanted to work into NumPy. Below you can find my first NumPy test script.

NumPy provides a powerful N-dimensional array object, linear algebra functions and random number generators to Python. The Quickstart tutorial is a really good starting point, to work into NumPy.

In order to use NumPy, first one has to install the NumPy module for Python:

sudo pip3 install numpy

Python example script

# Small python script to be started with
#   python3 numpy_intro.py
#
# Meant as a fast introduction to NumPy
#
# By Prof. Dr. Juergen Brauer, www.juergenbrauer.org

import numpy as np

# create a 1D array
x = np.array([10, 20, 30])
print("\nx",x)

# create a 2D array
M1 = np.array([(1,2,3), (4,5,6), (7,8,9)])
print("\nM1",M1)

# do some matrix addition
M2 = M1+M1
print("\nM2",M2)

# output some matrix meta data
print("\nmatrix x has", x.ndim, "dimension(s) and shape", x.shape)
print("matrix M1 has", M1.ndim, "dimension(s) and shape", M1.shape)

# create a 1D array with entries using the arange() function
step = 3
M3 = np.arange(1,20,step)
print("\nM3",M3)

# create a 1D array with entries using the linspace() function
how_many_numbers = 9
M4 = np.linspace(0,1,how_many_numbers)
print("\nM4",M4)

# now transform the 9 values of M4 to a 2D matrix of shape 3x3
M5 = M4.reshape(3,3)
print("\nM5",M5)

# elementwise multiplication
M6 = 2*M5
print("\nM6",M6)

# defining a function foo() and applying the function on each element of an array
def foo(x):
	return x+1

M7 = np.zeros((3,4))
print("\nM7",M7)

M7 = foo(M7)
print("\nM7",M7)

M7 = foo(M7)
print("\nM7",M7)

M7 = foo(M7)
print("\nM7",M7)
		

Output generated by the script

x [10 20 30]

M1 [[1 2 3]
 [4 5 6]
 [7 8 9]]

M2 [[ 2  4  6]
 [ 8 10 12]
 [14 16 18]]

matrix x has 1 dimension(s) and shape (3,)
matrix M1 has 2 dimension(s) and shape (3, 3)

M3 [ 1  4  7 10 13 16 19]

M4 [ 0.     0.125  0.25   0.375  0.5    0.625  0.75   0.875  1.   ]

M5 [[ 0.     0.125  0.25 ]
 [ 0.375  0.5    0.625]
 [ 0.75   0.875  1.   ]]

M6 [[ 0.    0.25  0.5 ]
 [ 0.75  1.    1.25]
 [ 1.5   1.75  2.  ]]

M7 [[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]

M7 [[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]

M7 [[ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]]

M7 [[ 3.  3.  3.  3.]
 [ 3.  3.  3.  3.]
 [ 3.  3.  3.  3.]]