418512: Computer Programming Languages Lecture 7 Pramook Khungurn TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: A AAAA A A
Python Mathematical Libraries NumPy SciPy matplotlib
NUMPY
Numpy Numpy manipulates homogeneous multidimensional array. – Table of same types of elements. – Indexed by tuple of positive integers. Example: – [1, 2, 1] rank 1 1 axis – [[ 1., 0., 0.], [ 0., 1., 2.]] rank 2 2 axis
ndarray ndarray = class for multidim array Properties – ndarray.ndim number of axes – ndarray.shape tuple of integers indicating sizes of array in each dim – ndarray.size total number of elements in an array
ndarray Properpies – ndarray.dtype type of elements in the array – ndarray.itemsize size in bytes of each element of the array – ndarray.data memory containing the actual elements don’t deal with this directly
ndarray >>> from numpy import * >>> a = arange(10).reshape(2,5) >>> a array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> a.shape (2, 5) >>> a.size 10 >>> a.dtype dtype('int32') >>> a.itemsize 4
Array Creation Use the “array” function. >>> from numpy import * >>> a = array( [2,3,4] ) >>> a array([2, 3, 4]) >>> type(a) >>> b = array( [(1.5,2,3), (4,5,6)] ) >>> b array([[ 1.5, 2., 3. ], [ 4., 5., 6. ]])
dtype parameter >>> c = array( [ [1,2], [3,4] ], dtype=complex ) >>> c array([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+0.j]])
Array Creation zeros >>> zeros((3,4)) array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])
Array Creation ones >>> ones((2,3,4), dtype=int16) array([[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]], dtype=int16)
Array Creation empty >>> empty((2,3)) array([[ e+161, e-096, e-057], [ e+277, e+214, e+000]])
Array Creation arange >>> arange( 10, 30, 5 ) array([10, 15, 20, 25]) >>> arange( 0, 2, 0.3 ) array([ 0., 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
Array Creation linspace – last argument = number of elements >>> linspace( 0, 2, 9 ) array([ 0., 0.25, 0.5, 0.75, 1., 1.25, 1.5, 1.75, 2. ])
Basic Operations Arithmetic operators apply elementwise. >>> a = array( [20, 30, 40, 50] ) >>> b = arange( 4 ) >>> c = a - b >>> c array([20, 29, 38, 47]) >>> b**2 array([0, 1, 4, 9]) >>> 10*sin(a) array([ , , , ]) >>> a < 35 array([ True, True, False, False], dtype=bool)
Multiplication * (multiplication) operates elementwise too. – Not matrix multiplication. >>> A = array( [[1,1], [0,1]] ) >>> B = array( [[2,0], [3,4]] ) >>> A * B array([[2, 0], [0, 4]])
Matrix Product Use the “dot” function. >>> A = array( [[1,1], [0,1]] ) >>> B = array( [[2,0], [3,4]] ) >>> dot(A,B) array([[5, 4], [3, 4]])
In-Place Operator Some operators do not create new arrays. >>> a = ones((2,3), dtype=int) >>> b = random.random((2,3)) >>> a *= 3 >>> a array([[3, 3, 3], [3, 3, 3]]) >>> b += a >>> b array([[ , , ], [ , , ]]) >>> a += b >>> a array([[6, 6, 6], [6, 6, 6]])
Unary Operators >>> a = random.random((2,3)) >>> a array([[ , , ], [ , , ]]) >>> a.sum() >>> a.min() >>> a.max()
axis parameter Supply the “axis” parameter to apply operators along a particular axis. >>> b = arange(12).reshape(3,4) >>> b array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> b.sum(axis=0) array([12, 15, 18, 21]) >>> b.min(axis=1) array([0, 4, 8]) >>> b.cumsum(axis=1) array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]])
Universal Functions >>> B = arange(3) >>> B array([0, 1, 2]) >>> exp(B) array([ 1., , ]) >>> sqrt(B) array([ 0., 1., ])
Indexing, Slicing, and Iterating >>> a = arange(10)**3 >>> a array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]) >>> a[2] 8 >>> a[2:5] array([ 8, 27, 64]) >>> a[3] = >>> a array([0, 1, 8, -1000, 64, 125, 216, 343, 512, 729])
Indexing Multidimensional Array Indices are tuple separated by commas. >>> def f(x,y):... return 10*x+y... >>> b = fromfunction(f, (5,4), dtype=int) >>> b array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]]) >>> b[2,3] 23 >>> b[:,1] array([ 1, 11, 21, 31, 41]) >>> b[1:3,:] array([[10, 11, 12, 13], [20, 21, 22, 23]])
Iterating over Multidimensional Array You get the rows. >>> for row in b:... print row... [ ] [ ] [ ] [ ] [ ]
Flat Attribute Use “flat” attribute to get each element. >>> for element in b.flat:... print element,
Ravel and Transpose >>> a = floor(10*random.random((3,4))) >>> a array([[ 4., 0., 0., 0.], [ 7., 2., 1., 3.], [ 6., 9., 1., 1.]]) >>> a.ravel() array([ 4., 0., 0., 0., 7., 2., 1., 3., 6., 9., 1., 1.]) >>> a.transpose() array([[ 4., 7., 6.], [ 0., 2., 9.], [ 0., 1., 1.], [ 0., 3., 1.]])
Reshape and Resize Reshape returns a new array. >>> a = floor(10*random.random((3,4))) >>> a.reshape(6,2) array([[ 0., 7.], [ 6., 8.], [ 3., 5.], [ 3., 9.], [ 0., 7.], [ 4., 7.]]) >>> a.resize(2,6) >>> a array([[ 0., 7., 6., 8., 3., 5.], [ 3., 9., 0., 7., 4., 7.]])
Deep Copy Do deep copy with the “copy” method. >>> a = arange(12).reshape(3,4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> d = a.copy() >>> d is a False >>> d[0,0] = 9999 >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> d array([[9999, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
Matrix Matrices are created by “matrix” function. Matrices are different from arrays that * is matrix multiplication. >>> A = matrix([[1,2,3], [4,5,6], [7,8,9]]) >>> A matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> B = matrix([[2,0,0], [0,2,0], [0,0,2]]) >>> A * B matrix([[ 2, 4, 6], [ 8, 10, 12], [14, 16, 18]])
SCIPY
Scipy Scipy is for scientific computation. To use: import scipy Useful subpackages: – clusterclustering algorithms – fftpackfast fourier transform – integrateintegration – interpolateinterpolation and smoothing splines – linalglinear algebra – optimizeoptimization and root-finding – signalsignal processing – sparsesparse matrices – statsstatistical distribution and functions
Scipy Documentation Use “scipy.info” on packages or functions. >>> import scipy >>> from scipy import linalg >>> scipy.info(linalg) >>> scipy.info(linalg.det )
integrate.quad Use it to integrate a general function. For example, if you want to compute: >>> from scipy import integrate >>> integrate.quad(lambda x: x**2, 0, 4.5) (30.375, e-13) The first return value is the value of integration. The second is the upper bound on the error.
optimize.fmin Use it to find the argument that minimizes a function. For example, if you want to minimize: >>> def rosen(x):... return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)... >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] >>> xopt = fmin(rosen, x0, xtol=1e-8) >>> print xopt [ ]
optimize.fsolve Use it to find a zero of a function. Suppose you want to solve: >>> def func(x):... return x + 2*cos(x)... >>> from scipy.optimize import fsolve >>> x0 = fsolve(func, 0.3) >>> print x0 [ ]
optimize.fsolve You want to solve a system of equation >>> def func2(x):... out = [x[0]*cos(x[1])-4]... out.append(x[1]*x[0] - x[1] - 5)... return out... >>> x02 = fsolve(func2, [1,1]) >>> print x02 [ ]
linalg.inv Find the inverse of a matrix. >>> A = matrix([[1,3,5], [2,5,1], [2,3,8]]) >>> from scipy import linalg >>> linalg.inv(A) array([[-1.48, 0.36, 0.88], [ 0.56, 0.08, -0.36], [ 0.16, -0.12, 0.04]])
linalg.solve To solve the linear system: >>> A = mat('[1 3 5; 2 5 1; 2 3 8]') >>> b = mat('[10;8;3]') >>> linalg.solve(A,b) array([[-9.28], [ 5.16], [ 0.76]])
linalg.det Find the determinant. >>> A = mat('[1 3 5; 2 5 1; 2 3 8]') >>> linalg.det(A)
linalg.svd Find the singular value decomposition. >>> A = mat('[1 3 2; 1 2 3]') >>> U, s, Vh = linalg.svd(A) >>> U array([[ , ], [ , ]]) >>> s array([ , 1. ]) >>> Vh array([[ e-01, e-01, e-01], [ e-16, e-01, e-01], [ e-01, e-01, e-01]])
linalg.eig Find eigenvalues and eigenvectors. >>> A = mat('[1 5 2; 2 4 1; 3 6 2]') >>> la, v = linalg.eig(A) >>> v array([[ , , ], [ , , ], [ , , ]]) >>> la array([ j, j, j])
MATPLOTLIB
matplotlib.pyplot A package for plotting graphs. pyplot works like MATLAB. – Commands make changes a figure. – Stateful.
pyplot.plot >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3,4]) [ ] >>> plt.ylabel('some numbers') >>> plt.show()
pyplot.plot
Here’s how you plot x-vs-y.
pyplot.plot Third argument indicates the style of the graph. – Default value ‘b-’ is blue line. – Below: ‘ro’ is red dots. >>> plt.plot([1,2,3,4], [1,4,9,16], 'ro') [ ] >>> plt.show()
pyplot.plot
pyplot.axis axis() takes [xmin, xmax, ymin, ymax] >>> plt.plot([1,2,3,4], [1,4,9,16], 'ro') >>> plt.axis([0, 6, 0, 20]) >>> plt.show()
pyplot.axis
matplotlib and Numpy You can use Numpy arrays as arrays of x and y values. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> t = np.arange(0., 5., 0.2) >>> plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') >>> plt.show()
matplotlib and Numpy
pyplot.subplot subplot(r, c, fignum) – Create a grid with r rows and c cols. – fignum ranges from 1 to r*c. – fignum selects which grid cell to draw to.
pyplot.subplot >>> import numpy as np >>> import matplotlib.pyplot as plt >>> def f(t):... return np.exp(-t) * np.cos(2*np.pi*t)... >>> t1 = np.arange(0.0, 5.0, 0.1) >>> t2 = np.arange(0.0, 5.0, 0.02) >>> plt.figure(1) >>> plt.subplot(2,1,1) >>> plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') >>> plt.subplot(2,1,2) >>> plt.plot(t2, np.cos(2*np.pi*t2), 'r--') >>> plt.show()
pyplot.subplot
Drawing Text text() – Add text at arbitrary location. xlabel(), ylabel(), title() – Add text at specified locations.
Drawing Text import numpy as np import matplotlib.pyplot as plt mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60,.025, r'$\mu=100,\ \sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True)
Drawing Text
pyplot.annotate Makes it easy to annotate the graph. – xy: the location of to be annotated – xytext: the location of the text ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = plt.plot(t, s, lw=2) plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) plt.ylim(-2,2) plt.show()
pyplot.annotate