Hướng dẫn python vectorization for loop
We know that most of the application has to deal with a large number of datasets. Hence, a non-computationally-optimal function can become a huge bottleneck in your algorithm and can take result in a model that takes ages to run. To make sure that the code is computationally efficient, we will use vectorization. Time complexity in the execution of any algorithm is very crucial deciding whether an application is reliable or not. To run a large algorithm in as much as optimal time possible is very important when it comes to real-time application of output. To do so, Python has some standard mathematical functions for fast operations on entire arrays of data without having to write loops. One of such library which contains such function is numpy. Let’s see how can we use this standard function in case of vectorization. What is Vectorization ? We will see how the classic methods are more time consuming than using some standard function by calculating their processing time.
Dot Product: Pictorial representation of dot product – Below is the Python code:
Output: dot_product = 833323333350000.0 Computation time = 35.59449199999999ms n_dot_product = 833323333350000 Computation time = 0.1559900000000225ms Pictorial representation of outer product – Below is the Python code:
Output: outer_product = [[ 0. 0. 0. ..., 0. 0. 0.] [ 200. 201. 202. ..., 397. 398. 399.] [ 400. 402. 404. ..., 794. 796. 798.] ..., [ 39400. 39597. 39794. ..., 78209. 78406. 78603.] [ 39600. 39798. 39996. ..., 78606. 78804. 79002.] [ 39800. 39999. 40198. ..., 79003. 79202. 79401.]] Computation time = 39.821617ms outer_product = [[ 0 0 0 ..., 0 0 0] [ 200 201 202 ..., 397 398 399] [ 400 402 404 ..., 794 796 798] ..., [39400 39597 39794 ..., 78209 78406 78603] [39600 39798 39996 ..., 78606 78804 79002] [39800 39999 40198 ..., 79003 79202 79401]] Computation time = 0.2809480000000031ms Pictorial
representation of Element wise product – Below is the Python code:
Output: Element wise Product = [ 0.00000000e+00 5.00010000e+04 1.00004000e+05 ..., 4.99955001e+09 4.99970000e+09 4.99985000e+09] Computation time = 23.516678000000013ms Element wise Product = [ 0 50001 100004 ..., 704582713 704732708 704882705] Computation time = 0.2250640000000248ms |