Advertisement
julianzhang

Optional Lab: Python, NumPy and Vectorization

Aug 9th, 2022
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.76 KB | None | 0 0
  1. import numpy as np # it is an unofficial standard to use np for numpy
  2. import time
  3. # NumPy routines which allocate memory and fill arrays with value
  4. a = np.zeros(4); print(f"np.zeros(4) : a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
  5. a = np.zeros((4,)); print(f"np.zeros(4,) : a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
  6. a = np.random.random_sample(4); print(f"np.random.random_sample(4): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
  7. # NumPy routines which allocate memory and fill arrays with value but do not accept shape as input argument
  8. a = np.arange(4.); print(f"np.arange(4.): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
  9. a = np.random.rand(4); print(f"np.random.rand(4): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
  10. # NumPy routines which allocate memory and fill with user specified values
  11. a = np.array([5,4,3,2]); print(f"np.array([5,4,3,2]): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
  12. a = np.array([5.,4,3,2]); print(f"np.array([5.,4,3,2]): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
  13. #vector indexing operations on 1-D vectors
  14. a = np.arange(10)
  15. print(a)
  16.  
  17. #access an element
  18. print(f"a[2].shape: {a[2].shape} a[2] = {a[2]}, Accessing an element returns a scalar")
  19.  
  20. # access the last element, negative indexes count from the end
  21. print(f"a[-1] = {a[-1]}")
  22.  
  23. #indexs must be within the range of the vector or they will produce and error
  24. try:
  25. c = a[10]
  26. except Exception as e:
  27. print("The error message you'll see is:")
  28. print(e)
  29. #vector slicing operations
  30. a = np.arange(10)
  31. print(f"a = {a}")
  32.  
  33. #access 5 consecutive elements (start:stop:step)
  34. c = a[2:7:1]; print("a[2:7:1] = ", c)
  35.  
  36. # access 3 elements separated by two
  37. c = a[2:7:2]; print("a[2:7:2] = ", c)
  38.  
  39. # access all elements index 3 and above
  40. c = a[3:]; print("a[3:] = ", c)
  41.  
  42. # access all elements below index 3
  43. c = a[:3]; print("a[:3] = ", c)
  44.  
  45. # access all elements
  46. c = a[:]; print("a[:] = ", c)
  47. a = np.array([1,2,3,4])
  48. print(f"a : {a}")
  49. # negate elements of a
  50. b = -a
  51. print(f"b = -a : {b}")
  52.  
  53. # sum all elements of a, returns a scalar
  54. b = np.sum(a)
  55. print(f"b = np.sum(a) : {b}")
  56.  
  57. b = np.mean(a)
  58. print(f"b = np.mean(a): {b}")
  59.  
  60. b = a**2
  61. print(f"b = a**2 : {b}")
  62. a = np.array([ 1, 2, 3, 4])
  63. b = np.array([-1,-2, 3, 4])
  64. print(f"Binary operators work element wise: {a + b}")
  65. #try a mismatched vector operation
  66. c = np.array([1, 2])
  67. try:
  68. d = a + c
  69. except Exception as e:
  70. print("The error message you'll see is:")
  71. print(e)
  72. a = np.array([1, 2, 3, 4])
  73.  
  74. # multiply a by a scalar
  75. b = 5 * a
  76. print(f"b = 5 * a : {b}")
  77.  
  78.  
  79. def my_dot(a, b):
  80. """
  81. Compute the dot product of two vectors
  82.  
  83. Args:
  84. a (ndarray (n,)): input vector
  85. b (ndarray (n,)): input vector with same dimension as a
  86.  
  87. Returns:
  88. x (scalar):
  89. """
  90. x = 0
  91. for i in range(a.shape[0]):
  92. x = x + a[i] * b[i]
  93. return x
  94. # test 1-D
  95. a = np.array([1, 2, 3, 4])
  96. b = np.array([-1, 4, 3, 2])
  97. print(f"my_dot(a, b) = {my_dot(a, b)}")
  98. # test 1-D
  99. a = np.array([1, 2, 3, 4])
  100. b = np.array([-1, 4, 3, 2])
  101. c = np.dot(a, b)
  102. print(f"NumPy 1-D np.dot(a, b) = {c}, np.dot(a, b).shape = {c.shape} ")
  103. c = np.dot(b, a)
  104. print(f"NumPy 1-D np.dot(b, a) = {c}, np.dot(a, b).shape = {c.shape} ")
  105. np.random.seed(1)
  106. a = np.random.rand(10000000) # very large arrays
  107. b = np.random.rand(10000000)
  108.  
  109. tic = time.time() # capture start time
  110. c = np.dot(a, b)
  111. toc = time.time() # capture end time
  112.  
  113. print(f"np.dot(a, b) = {c:.4f}")
  114. print(f"Vectorized version duration: {1000*(toc-tic):.4f} ms ")
  115.  
  116. tic = time.time() # capture start time
  117. c = my_dot(a,b)
  118. toc = time.time() # capture end time
  119.  
  120. print(f"my_dot(a, b) = {c:.4f}")
  121. print(f"loop version duration: {1000*(toc-tic):.4f} ms ")
  122.  
  123. del(a);del(b) #remove these big arrays from memory
  124. # show common Course 1 example
  125. X = np.array([[1],[2],[3],[4]])
  126. w = np.array([2])
  127. c = np.dot(X[1], w)
  128.  
  129. print(f"X[1] has shape {X[1].shape}")
  130. print(f"w has shape {w.shape}")
  131. print(f"c has shape {c.shape}")
  132. a = np.zeros((1, 5))
  133. print(f"a shape = {a.shape}, a = {a}")
  134.  
  135. a = np.zeros((2, 1))
  136. print(f"a shape = {a.shape}, a = {a}")
  137.  
  138. a = np.random.random_sample((1, 1))
  139. print(f"a shape = {a.shape}, a = {a}")
  140. # NumPy routines which allocate memory and fill with user specified values
  141. a = np.array([[5], [4], [3]]); print(f" a shape = {a.shape}, np.array: a = {a}")
  142. a = np.array([[5], # One can also
  143. [4], # separate values
  144. [3]]); #into separate rows
  145. print(f" a shape = {a.shape}, np.array: a = {a}")
  146. #vector indexing operations on matrices
  147. a = np.arange(6).reshape(-1, 2) #reshape is a convenient way to create matrices
  148. print(f"a.shape: {a.shape}, \na= {a}")
  149.  
  150. #access an element
  151. print(f"\na[2,0].shape: {a[2, 0].shape}, a[2,0] = {a[2, 0]}, type(a[2,0]) = {type(a[2, 0])} Accessing an element returns a scalar\n")
  152.  
  153. #access a row
  154. print(f"a[2].shape: {a[2].shape}, a[2] = {a[2]}, type(a[2]) = {type(a[2])}")
  155. #vector 2-D slicing operations
  156. a = np.arange(20).reshape(-1, 10)
  157. print(f"a = \n{a}")
  158.  
  159. #access 5 consecutive elements (start:stop:step)
  160. print("a[0, 2:7:1] = ", a[0, 2:7:1], ", a[0, 2:7:1].shape =", a[0, 2:7:1].shape, "a 1-D array")
  161.  
  162. #access 5 consecutive elements (start:stop:step) in two rows
  163. print("a[:, 2:7:1] = \n", a[:, 2:7:1], ", a[:, 2:7:1].shape =", a[:, 2:7:1].shape, "a 2-D array")
  164.  
  165. # access all elements
  166. print("a[:,:] = \n", a[:,:], ", a[:,:].shape =", a[:,:].shape)
  167.  
  168. # access all elements in one row (very common usage)
  169. print("a[1,:] = ", a[1,:], ", a[1,:].shape =", a[1,:].shape, "a 1-D array")
  170. # same as
  171. print("a[1] = ", a[1], ", a[1].shape =", a[1].shape, "a 1-D array")
  172.  
  173.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement