Presentation is loading. Please wait.

Presentation is loading. Please wait.

418512: Computer Programming Languages Lecture 7 Pramook Khungurn TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: A AAAA.

Similar presentations


Presentation on theme: "418512: Computer Programming Languages Lecture 7 Pramook Khungurn TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: A AAAA."— Presentation transcript:

1 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

2 Python Mathematical Libraries NumPy SciPy matplotlib

3 NUMPY

4 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

5 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

6 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

7 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

8 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. ]])

9 dtype parameter >>> c = array( [ [1,2], [3,4] ], dtype=complex ) >>> c array([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+0.j]])

10 Array Creation zeros >>> zeros((3,4)) array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])

11 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)

12 Array Creation empty >>> empty((2,3)) array([[ 2.59345406e+161, 8.12549991e-096, 2.24630812e-057], [ 1.12958007e+277, 2.21211602e+214, 6.00003876e+000]])

13 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])

14 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. ])

15 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([ 9.12945251, -9.88031624, 7.4511316, - 2.62374854]) >>> a < 35 array([ True, True, False, False], dtype=bool)

16 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]])

17 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]])

18 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([[ 3.61985813, 3.66556966, 3.87592214], [ 3.20532333, 3.23846057, 3.48698414]]) >>> a += b >>> a array([[6, 6, 6], [6, 6, 6]])

19 Unary Operators >>> a = random.random((2,3)) >>> a array([[ 0.5984133, 0.93697558, 0.18051175], [ 0.81601338, 0.04679024, 0.73921303]]) >>> a.sum() 3.3179172722383647 >>> a.min() 0.046790239698870417 >>> a.max() 0.93697558122865876

20 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]])

21 Universal Functions >>> B = arange(3) >>> B array([0, 1, 2]) >>> exp(B) array([ 1., 2.71828183, 7.3890561 ]) >>> sqrt(B) array([ 0., 1., 1.41421356])

22 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] = -1000 >>> a array([0, 1, 8, -1000, 64, 125, 216, 343, 512, 729])

23 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]])

24 Iterating over Multidimensional Array You get the rows. >>> for row in b:... print row... [0 1 2 3] [10 11 12 13] [20 21 22 23] [30 31 32 33] [40 41 42 43]

25 Flat Attribute Use “flat” attribute to get each element. >>> for element in b.flat:... print element,... 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43

26 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.]])

27 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.]])

28 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]])

29 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]])

30 SCIPY

31 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

32 Scipy Documentation Use “scipy.info” on packages or functions. >>> import scipy >>> from scipy import linalg >>> scipy.info(linalg) >>> scipy.info(linalg.det )

33 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, 3.372302437298913e-13) The first return value is the value of integration. The second is the upper bound on the error.

34 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 [ 1. 1. 1. 1. 1.]

35 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 [-1.02986653]

36 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 [ 6.50409711 0.90841421]

37 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]])

38 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]])

39 linalg.det Find the determinant. >>> A = mat('[1 3 5; 2 5 1; 2 3 8]') >>> linalg.det(A) -25.000000000000004

40 linalg.svd Find the singular value decomposition. >>> A = mat('[1 3 2; 1 2 3]') >>> U, s, Vh = linalg.svd(A) >>> U array([[-0.70710678, -0.70710678], [-0.70710678, 0.70710678]]) >>> s array([ 5.19615242, 1. ]) >>> Vh array([[ -2.72165527e-01, -6.80413817e-01, -6.80413817e-01], [ 2.42861287e-16, -7.07106781e-01, 7.07106781e-01], [ -9.62250449e-01, 1.92450090e-01, 1.92450090e-01]])

41 linalg.eig Find eigenvalues and eigenvectors. >>> A = mat('[1 5 2; 2 4 1; 3 6 2]') >>> la, v = linalg.eig(A) >>> v array([[-0.5297175, -0.90730751, 0.28380519], [-0.44941741, 0.28662547, -0.39012063], [-0.71932146, 0.30763439, 0.87593408]]) >>> la array([ 7.95791620+0.j, -1.25766471+0.j, 0.29974850+0.j])

42 MATPLOTLIB

43 matplotlib.pyplot A package for plotting graphs. pyplot works like MATLAB. – Commands make changes a figure. – Stateful.

44 pyplot.plot >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3,4]) [ ] >>> plt.ylabel('some numbers') >>> plt.show()

45 pyplot.plot

46 Here’s how you plot x-vs-y.

47 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()

48 pyplot.plot

49 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()

50 pyplot.axis

51 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()

52 matplotlib and Numpy

53 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.

54 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()

55 pyplot.subplot

56 Drawing Text text() – Add text at arbitrary location. xlabel(), ylabel(), title() – Add text at specified locations.

57 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)

58 Drawing Text

59 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()

60 pyplot.annotate


Download ppt "418512: Computer Programming Languages Lecture 7 Pramook Khungurn TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: A AAAA."

Similar presentations


Ads by Google