Why For loop is not preferred in Neural Network Problems?
Last Updated :
17 May, 2020
For loop take much time for completing iterations and in ML practise we have to optimize the time so we can use for loops. But then you must be wondering what to use then? Don’t worry we will discuss this in the below section.
How to get rid from loop in Machine Learning or Neural Network?
The solution is Vectorization. Now the question arises what is vectorization? Vectorization is the process to convert algorithms from operating on a single value at a time to operate on a set of values (vector) at one time. Modern CPUs provide direct support for vector operations where a single instruction is applied to multiple data (SIMD).
Why to use Vectorization over for loop ?
Vectorization is used to speed up the Python code . Using np.function can help in minimizing the running time of code efficiently. Let’s see the below example for better understanding.
Example:
import numpy as np
import time
a = np.array([ 1 , 2 , 3 , 4 ])
a = np.random.rand( 100000 )
b = np.random.rand( 100000 )
time1 = time.time()
c = np.dot(a, b)
time2 = time.time()
print ( "vectorized form time taken" + "\t" + str ( 1000 * (time2 - time1)) + "ms" )
time3 = time.time()
c = 0
for i in range ( 100000 ):
c + = a[i] * b[i]
time4 = time.time()
print ( "for loop time taken " + "\t\t" + str ( 1000 * (time4 - time3)) + "ms" )
|
Output:
vectorized form time taken 0.43511390686035156ms
for loop time taken 216.04394912719727ms
Share your thoughts in the comments
Please Login to comment...