Chapter 5 Numeric Computing With Numpy
Chapter 5 Numeric Computing With Numpy
Si Thin Nguyen
PhD in Computer Science at Soongsil University, Korea
Email: [email protected]
Address: Faculty of Computer Science, VKU
Chapter Content
➢ Introduction to NumPy
➢ Why should use Numpy?
➢ Numpy Array
➢ Numpy Linear Algebra
➢ Numpy Matrix Library matlib
➢ I/O with Numpy
Introduction to NumPy
➔ NumPy is short for Numerical Python
➔ Array oriented computing
➔ Efficiently implemented multi-dimensional arrays
➔ Used for scientific computing.
Why should we use Numpy?
➔ Convenient interface for working with multi-dimensional
array data structures efficiently (ndarray).
➔ Less memory to store the data.
➔ High computational efficiency
Numpy Getting Started
➔ Installing Numpy: pip install numpy
➔ Import Numpy: import numpy
➔ Alias of Numpy: import numpy as np
➔ Check Numpy version: np.__version__
Numpy Data Types
➔ supports a much greater variety of numerical types
than Python does
Boolean bool_
arr[1,2,:]
arr[2,0]
arr[2,:,:]
arr[:,1,:] arr[:,:,0]
Numpy Array Slicing
1-D Array 2-D Array
arr[:1]
[start:end]
3-D Array
arr[1:,2:4]
arr[:2,1:,:2]
Numpy Arithmetic Operations
import numpy as np [[ 0, 1, 2]
a = np.arange(9, dtype = np.float_).reshape(3,3) [ 3, 4, 5 ]
b = np.array([10,10,10]) [ 6, 7, 8 ]]
[10, 10, 10]
[[ 0, 0.1, 0.2]
np.divide [ 0.3, 0.4, 0.5]
(a,b) [ 0.6, 0.7, 0.8]]
Numpy Arithmetic Functions
import numpy as np
a = np.array([7,3,4,5,1])
b = np.array([3,4,5,6,7])
np.reshape(3,2)
np.insert([1],[3],[4],[5],axis=1)
np.transpose() np.delete(1,0)
➔ np.mean(array, [axis],...)
axis=1 axis=0
Numpy Statistical Operations
➔ np.std(array,[axis],...) # standard deviation
axis=0 axis=1
axis=0 axis=1
Numpy Linear Algebra
➔ Linalg : the package in NumPy for Linear Algebra
➔ dot(): product of two arrays
vdot(): Complex-conjugating dot product
Example : a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1], [2, 2]])
Numpy Linear Algebra
➔ inner(): product of two arrays
- numpy.inner(a, b, /)
- a, b: array_like
If a and b are non-scalar, their last dimensions must match
- Returns: out: ndarray
If a and b are both scalars or both 1-D arrays then a scalar is
returned; otherwise an array is returned. out.shape =
(*a.shape[:-1], *b.shape[:-1])
Numpy Linear Algebra
➔ outer(): compute the outer product of two vectors
numpy.outer(a, b, out=None)
Parameters:
- a : (M,) array_like
First input vector. Input is flattened if not already 1-dimensional.
- b : (N,) array_like
Second input vector. Input is flattened if not already 1-dimensional.
- out : (M, N) ndarray, optional
A location where the result is stored
Numpy Linear Algebra
➔ matmul(): Matrix product of two arrays
numpy.matmul(x1, x2, /, out=None, *, casting='same_kind',
order='K', dtype=None, subok=True[, signature, extobj, axes, axis])
= <ufunc 'matmul'>
Parameters: x1, x2: array_like
Input arrays, scalars not allowed.
Out: ndarray, optional
If provide allocation, it must have a shape that matches the
signature (n,k),(k,m)->(n,m). If not provided or None, a freshly-
allocated array is returned.
Numpy Linear Algebra
Another linear algebra functions
➔ det()
➔ inv()
➔ trace()
➔ rank()
Numpy Matrix Library matlib
➔ has functions that return matrices instead of ndarray objects.
import numpy as np
import numpy.matlib
# with the specified shape and type without initializing entries
mat_e =np.matlib.empty((3, 2), dtype = int)
# filled with 0
mat_zeros = np.matlib.zeros(5, 3)
# filled with 1
mat_ones = np.matlib.ones(4, 3)
# diagonal elements filled with 1, others with 0
mat_ones = np.matlib.eye(3,5)
# create square matrix with 0, diagonal filled with 1, others with 0
mat_zeros = np.matlib.identity(5)
# filled with random data
mat_e =np.matlib.empty(3, 2))
I/O with Numpy
Ex:
import numpy as np
a = np.array([1,2,3,4,5])
np.savetxt('out.txt',a)
b = np.loadtxt('out.txt')
print b
The output produced appears as: [ 1. 2. 3. 4. 5.]