0% found this document useful (0 votes)
50 views

Numpy 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
50 views

Numpy 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 20
ol Ci: Numeric Computing with Numpy Thu Huong Nguyen! and Si Thin Nguyen? *[email protected] [email protected] Faculty of Computer Science, VKU 1 Exercises with solutions 1.1 Introduction 1.1.1 Import the numpy package under the name np import numpy as np 1.1.2 Print the numpy version and the configuration import numpy as mp print(np.__version__) print (ap. show_config()) 4.22.4 openblas64__info Libraries = [‘openblas64_', ‘openblas64_'] Library_dirs = ['/opt/arm64-builds/1ib'] language = ¢ define_macros = [(‘HAVE_CBLAS', None), (‘BLAS_SYMBOL_SUFFIX', '64_'), (/HAVE_BLAS_ILP64', None)] runtime library_dirs = ['/opt/armé4-builds/1ib'] blas_ilp64_opt_info: Libraries = [‘openblas64_', ‘openblas64_'] library_dirs = ['/opt/arm64-builds/1ib'] language = define_macros = [(‘HAVE_CBLAS', None), (‘BLAS_SYMBOL_SUFFIX', '64_'), (HAVE_BLAS_ILP64', None)] runtime library_dirs = ['/opt/arm64-builds/1ib'] openblas64__lapack_info: Libraries = [‘openblas64_', ‘openblas64_'] Library_dirs = ['/opt/arm64-builds/1ib'] language = ¢ define_macros = [(‘HAVE_CBLAS', None), (‘BLAS_SYMBOL_SUFFIX', '64_'), Ci: (HAVE_BLAS_ILP64", None), (‘HAVE_LAPACKE', None)] runtime_library_dirs = ['/opt/arm64-builds/1ib'] lapack_ilp64_opt_info: libraries = [‘openblas64_', ‘openblasé64_"] Library_dirs = ['/opt/arm64-builds/1ib'] language = ¢ define.macros = [(‘HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', ‘64. (C/HAVE_BLAS_ILP64", None), ('HAVELAPACKE', None)] runtine_library_dirs = ['/opt/arm64-builds/1ib'] Supported SIMD extensions in this NumPy install baseline = NEON, NEON_FP16,NEON_VFPV4, ASIMD found = ASIMDHP not found = ASIMDDP 1.2 Numpy array /Vector/Matrix creation 1.2.1 Write a program to create a Numpy array 1, one-dimensional 2, two-dimensional # one-dimensional array one_arr = np.array([i, 2, 3, 4, 5]) print ("One-dimensional NunPy array: ",one_arr) 1- (1, 2, 3, 4] print ("Original List:",1) List_arr = np.array(1) print ("One-dimensional NumPy array from a given numeric list: ",list_arr) # two-dimensional array two_arr-arr = np.array(([1, 2, 3], [4, 5, 611) # froma list of lists listOfLists = [[1, 2, 31, [4, 5, 61, [7,8,911 print("Griginal list of lists: ",listOfLists) List2_arr = np.array(List0fLists) print ("Two-dimensional NunPy array from list of two lists : \n",1ist2_arr) One-dimensional WunPy array: [123 4 5] Original List: [1, 2, 3, 4] One-dimensional NunPy array froma given numeric list: [123 4] Original list of lists 1: [[1, 2, 3], (4, 5, 61, [7, 8, 91] Two-dimensional NunPy array from list of two lists : [[1 23) 456) e911 cl oi 1.2.2 Write a program to convert a list and tuple into Numpy arrays Hints Use the function asarray() my_list = [1, 2, 3, 4, 5, 6, 7, 8] print("List to array: ") print (np.asarray(my_list)) my_tuple = ([8, 4, 6], 1, 2, 31) print("Tuple to array: ") print (np.asarray (my_tuple)) List to array: (12345678) Tuple to array: ((8 4 6) 231 1.2.3 Write a program to create a 2d Numpy array as below: ca a ies a. a x = mp.ones((5,5)) print ("Original array:") print (x) print("Gutput array with 1 on the border and 0 inside in the array") x[1:-1,1:-1] = 0 print Gx) Original array: Cla. 4 a. a ies a. Output ca ta. a a a n 1 1 1 1 . 1 array with 1 on the border and 0 inside in the array 5] 1 1] 1 J 1 1.2.4 Write a program to create a 3x3 matrix with values ranging from 1 to 9 x= np.arange(1, 10) reshape(3,3) print (x) C1 2 3) (45 6] (7 8 91) 1.2.5 Write a program to create a 8x8 matrix and fill it with a checkerboard pattern filled with 0 and 1. : /print (Checkerboard pattern:") x = mp.zeros((8,8) dtype-int) x[1::2,::2] = 4 p12) = 1 print (x) Checkerboard pattern: (01010103) (10101010) fo1010103) 10101010) fo1010104) [10101010] fo1010103) f10101010)) 1.2.6 Write a program to create a 8x8 matrix and fill it with a checkerboard pattern filled with 0 and 1 using the function tile () : print (Checkerboard pattern:") x = mp.tile( mp.array((f0,1],[1,0]]), (4,4)) print(x) Checkerboard pattern: (lo1010104) 10101010) fo1010104) [10101010] fo1010101) (10101010) fo1010103) [o101010)) ol cl Ci: 1.2.7 Write a program to create a null vector of size 10 and update sixth value to 11. x = np.zeros(10) print (x) print("Update sixth value to 11") x6] = 11 print (x) fo. 0. 0. 0. 0. 0. 0. 0. 0. 0.) Update sixth value to 11 CO. 0. 0. 0. 0. 0. 11. 0. 0. 0.7 1.2.8 Write a NumPy program to create an empty and a full array. # Greate an empty array x = np.empty((S,7)) print (x) # Create a full array y = mp.ful1((4,8),9) print(y) [[-3,10503618e1231 -2.10503618e+231 2.17053206e-314 4.446590810-323 5.92878775e-323 7.76593822e-299 4. 50155003e-294] (-8.914946616+303, nan -1,17273833e-308 2.19702506e-314 2.19702506e-314 2.47032823e-323 2. 16412116e-314] [ 2.16412116e-314 3.45845952e-323 2.16412120e-314 2.16412120e-314 8.60974374e-129 2.19706806e-314 2. 19706806e-314] [ 1.97626258e-323 2.16412115e-314 2.16412115e-314 1.48219694e-323 2.16612113e-314 2.16412113e-314 4.446590810-323] ([ 2.16412123e-314 2.16412123e-314 -1.88173352e+121 2.19706813e-314 2.19706813e-314 1.99395786e+197 2, 19528522e-314]] (9 9 9] (9 9 9] (9 9 9] (9 9 9)) 1.2.9 Write a NumPy program to create a 3-D array with ones on a diagonal and zeros elsewhere. import numpy as mp x = mp.eye(3) print Gx) 1.3. Subsetting/Slicing/Indexing 1.3.1 Create an arrary as follows: ‘¢ Return the array of elements in the 2nd row ‘© Return the array of elements in the third cohumn © Return a sub-array consisting of the odd rows and even columns of. (J: (import numpy Y = numpy.array(L 3,6,9,12], (15,18,21,24], [27,30,33,36], (39,42,45,48], (51,54,57,60] n YE::2, 11:2] array({L 6, 12, [30, 36], (54, 60)]) 1.3.2. Extract from the array np.array ([3,4,6,10,24,89,45,43,46,99,100]) with Boolean masking all the number © which are not divisible by 2 ‘© which are divisible by 5 which are divisible by 3 and 5 which are divisible by and set them to 42 (): (import mumpy as ap A = np.array([3,4,6,10,24,89,45,43, 46,99, 100]) div8 = ALAZ3!=( print ("Elements of A not divisible by 3:") print (diva) divs = ATA/S= print ("Elements of A divisible by 5:") print (div) print("Elenents of A, which are divisible by 3 and 5:") print (A[(A/3==0) & (AZS= print(" ATAYS=-0] = 42 print("""New values of A after setting the elements of A, which are divisible by 3, to 42:""") print (A) Elenents of A not divisible by 3. [ 4 10 89 43 46 100) Elements of A divisible by 5 [10 45 100) Ci: o Elements of A, which are divisible by 3 and 5: (45) New values of A after setting the elements of A, which are divisible by 3, to 42: [42 4 42 10 42 89 42 43 46 42 100) 1.4 Broadcasting 1.4.1 Write a NumPy program to broadcast on different shapes of arrays where p(3,3) + (3). The p variable has a shape of (3, 3), while q only has a shape of 3. import numpy as mp p ~ mp.array([[0, 0, 0), (1, 2, 31, [4 5, 611) @ np.array([10, 11, 12)) print ("Original arrays:") print ("Array-1") print(p) print ("Array-2") print (q) print("\nNew Array: new_arrayi = p+ q print (new_array!) 1.4.2 Selling pies on weekends. Sell 3 types of pies at different prices, and the following number of each pie was sold last weekend. How much money I made per pie type per day? Requirement: Don’t use loops Pie Cost Cost ($) | __ Friday Saturday Sunday Apple 20 [apple [ 2 [ 3 | 2 Blueberry 15 Blueberry 6 3 3 Pumpkin 25 Pumpkin Gy 3 5 cost = np.array([20, 15, 251) print ("Pie cost:") print (cost) sales = mp.array({[2, 3, 1], (6, 3, 3, (5, 3, 511) a: O: O: QO: QO: QO: print("\nPie sales (#):") print (sales) Pie cost: (20 15 25] Pie sales (#) Cl2 3 1] [6 3 3] [5 3 5]] we could make them the same size, and multiply corresponding elements “elementwise” Gost (6) Cost ($) Cost ($) Apple | 20-2000 Buebery 1515S Blueberry Pumpkin 25 ab 5 cost = np.repeat(cost, 3). reshape((3, 3)) cost array([[20, 20, 20], U5, 15, 15), [25, 25, 25]]) cost * sales array([{ 40, 60, 20], [L90, 45, 45], (125, 75, 12511) cost = mp.array([20, 15, 25]).reshape(3, 1) print (f" cost shape: (cost. shape}") cost shape: (3, 1) cost * sales Apple Pumpkin Friday Saturday | Sunday 2a (ie ee ia [tors See ees : array({{ 40, 60, 20], 90, 45, 45], (128, 75, 12511) 1.5 Numpy Array Attributes 1.5.1 Find the number of dimensions, shape, the number of elements and the memory size of each clement of a given array. Example: Original array: i234) [5678] [910.11 13) Number of array dimensions: 2 Array dimensions:(3, 4) Number of items: 12 Memory size of each element of the said array: 8 Hints: Use the ndim, shape, size and item size properties respectively 1.6 Operations on Numpy Array 1.6.1 Write a program to reverse a NumPy array (J: x = mp.arange(i, 10) print ("Original array: print (x) print ("Reverse array:") x= xf::-1) print (x) Original array: 4123456789) Reverse array: (9876543214) 1.6.2 Write a program to convert an Numpy array to a float type (Cl: x = mp.arange(i, 10) print ("Original array") print (x) x = mp.asfarray(x) print ("Array converted to a float type:") print (x) ol cl Original array 123456789) Array converted to a float type: (1.2.3. 4,5.6.7. 8.9.) 1.6.3 Write a program to test whether each element of a 1-D array is also present in a second array [0, 1, 2,3, 5] and Array2: [0, 2, 4] Example: Array Compare each element of Arrayl and Array2: | True False False ‘True Fi Hint: Use the function intd() array1 = nmp.array({0, 1, 2, 3, 61) print("Array1: ",array1) array2 = [0,2,4] print ("Array2: ",array2) print ("Compare each element of arrayi and array2") print(np.intd(array1, array2)) Arrayt: [0123 5) Array2: (0, 2, 4] Compare each element of array! and array? [ True False True False False] 1.6.4 Write a program to find common values between two Numpy arrays. Example: Arrayl: [ 010 20 40 60] and Array2: [10, 30, 40] Common values between two arrays:|10 40] Hint: Use the function intersee1d() array1 = mp.array({0, 10, 20, 40, 60]) print("Array1: ",array1) array2 = [10, 30, 40] print ("Array2: ",array2) print ("Conmon values between two arrays:") print (np.intersectid(arrayi, array2)) Array: [0 10 20 40 60) Array2: [10, 30, 40] Common values between two arrays [10 40] 1.6.5 Perform the following operations on two arrays: © substract * mutiple « divide © power 10 © mod © remainder U: [import numpy as np arr-np.array(((0,1,2], (3.4.51, (6,7,8]]) arri=[10, 10,10] # Substracting the two arrays arr2i = np.subtract(arr, art) print("Substracting the two arrays:") print (arr21) # Multiplying the two arrays arr22 = np.multiply(arr, arr1) print("Multiplying the tvo arrays: print (arr22) # Dividing the tuo arrays p-divide(arr, arri) print ("Dividing the two arrays:") print (arr23) #Use nunpy.pouer() to calculating exponents of an array of numbers arr = mp.array([5, 3, 6, 9, 2, 41) arr24 = np.power(arr,2) print ("calculating exponents of an array of numbers:" print (arr24) # Use nunpy.rectprocat() function arr = np.array([50, 1.34, 3, 1, 25]) arr26 = np. reciprocal (arr) print ("Use numpy.reciprocal() function") print (arr26) # Use reciprocal function arr = np.array((75], dtype = int) arr27 = np.reciprocal (arr) print ("Use numpy.reciprocal() function") print (arr27) # Use nunpy.mod() function arr = mp.array([7,16, 25]) arri = np. array({4,8,6]) arr28 = np.nod(arr,arr1) arr23 print ("Use numpy.mod() function") print (arr28) # Use munpy.remainder() function arr = mp.array([7,16, 25]) arri = np. array([4,8,6]) arr29 = np. remainder (arr,arr1) print ("Use numpy.renainder() function") print (arr29) Substracting the two arrays: [[-10 -9 -8] u cl [-7 -6 -5] [-4 -3 -21 Multiplying the two arrays: [L 0 10 20] [30 40 50] {60 70 80}] Dividing the two arrays: (lO. 0.1 0.2) [0.3 0.4 0.5) [0.6 0.7 0.8]] calculating exponents of an array of numbers, (125 27 216 729 8 64) Use numpy-reciprocal() function (0.02 0. 74626866 0.33333333 1. 0.04 1 Use nunpy.reciprocal() function (01 Use numpy.mod() function (301) Use numpy.remainder() function (301) 1.7 Linear algebra 1.7.1. Input an matrix and determine: rank, trace, determinant, inverse of this import numpy as np A= np.array(((6, 1, 1], (4, -1, 6), [4 8, 1) # Rank of a matrix print ("Rank of A:", np.linalg.matrix_rank(A)) # Trace of matriz A print("\nTrace of A:", mp.trace(A)) # Determinant of a matriz print("\nDeterminant of A:", np.linalg.det(A)) # Inverse of matréz A print("\nInverse of A:\n", np. Linalg.inv(A)) print("\nMatrix A raised to power 3:\n", np.Linalg.matrix_power(A, 3)) Rank of A: 3 Trace of A: 11 12 ol Ci: Ci: Ci: Ci: Determinant of A: -306.0 Inverse of A: TE 0.17647089 -0.00326797 -0.02287582) { 0.05882353 -0.13071895 0.08496732] [-0.11764708 0.1503268 0. 05228758)) Matrix A raised to power 3: [E336 162 228] [406 162 469] {698 702 905]] 1.7.2. Return dot product of two matrix a = mp.array(C(1.21, (3.411) b = mp.array({ (11,12, (13,14]]) print ("Dot product: ") print (np.dot(a,b)) print ("Complex-conjugating dot product: ") np. vdot (a,b) Dot product: C37 40] (85 92]] Complex-conjugating dot product: 130 1.7.3 Return inner product of two arrays #Ordinary inner product for vectors: a = mp.array([1,2,3]) b = np.array((0,1,0]) np-inner(a, b) 2 ‘one multidimensional examples: #Ecample 1 a = mp.arange(24) reshape((2,3,4)) b = mp.arange(4) c = mp.inner(a, >) c.shape @, 3) 13 Ci: Ci: Ci: Ci Ci: Ci: Ci: Ci Ci: #Some multidimensional examples: #Example 2 a = mp.arange(2) .reshape((1,1,2)) b = mp.arange(6) reshape ((3,2)) = mp.inner(a, b) ¢.shape a, 1,3) 7.4 Return outer product of two vectors ‘#canpie 1 rl = np.outer(ap.ones((5,)), mp.linspace(-2, 2, 5)) rn im ~ mp.outer(ij+mp.linspace(2, -2, 5), np.ones((5,))) grid = rl + im grid array([L-2-42.j, -142.J, 0.425, 142.j, 2.42.3), (242.5, 141.3, 0.41.3, 141.3, 26031, (2.40.5, -1.40.j, 0.40.3, 1.40.j, 2.40.3], [21.j,

You might also like