Python Forum
Trying to replace for loops with numpy
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to replace for loops with numpy
#9
Hi

If you want to test the power of vectorization, try the following basic example:

import numpy as np
import time

def square_function(x):
    return x**2


n = 10_000_000; # 10 million itérations


# case 1: using loops
y1 = np.zeros(n, dtype = np.float); # initialization

t0 = time.time();
for i in range(n):
    y1[i] = 0.1*i**2;

t1 = time.time();
duration1 = t1 - t0;
print("Duration using loops = {} seconds".format(duration1));

#case 2: using vectorization
y2 = np.zeros(n, dtype = np.float);      # initialization

t0 = time.time();
i = np.arange(n, dtype = np.float);     # vector of indexes is created
y2 = 0.1*i**2;
t1 = time.time();
duration2 = t1 - t0;
print("Duration using Vectorization = {} seconds".format(duration2));

## ratio calculation
print("Vectorization is {} times faster than loops use!!!".format(duration1 / duration2));
print("we check there's not difference: min(y2-y1) = {} and max(y2-y1) = {}".format(np.min(y2-y1),np.max(y2-y1)));
del y2; del y1;

# case 3: using a function works as well
y3 = np.zeros(n, dtype = np.float);      # initialization

t0 = time.time();
i = np.arange(n, dtype = np.float);     # vector of indexes is created
y3 = square_function(i);
t1 = time.time();
duration3 = t1 - t0;
print("Duration using Vectorization + function = {} seconds".format(duration3));
del y3;
Some basics on vectorization I'm currently writing down:
[Image: 1564738252-vectorization.png]

Concerning the 2 vectors resulting from Kronecker product, a more "visual" approach:
[Image: 1564738255-kronecker.png]

Paul
Reply


Messages In This Thread
RE: Trying to replace for loops with numpy - by paul18fr - Aug-04-2019, 07:09 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Numpy] How to store different data type in one numpy array? water 7 294 Mar-26-2024, 02:18 PM
Last Post: snippsat
  Numpy returns "TypeError: unsupported operand type(s) for *: 'numpy.ufunc' and 'int'" kalle 2 2,530 Jul-19-2022, 06:31 AM
Last Post: paul18fr
  replace sets of values in an array without using loops paul18fr 7 1,630 Jun-20-2022, 08:15 PM
Last Post: paul18fr
  "erlarge" a numpy-matrix to numpy-array PhysChem 2 2,932 Apr-09-2019, 04:54 PM
Last Post: PhysChem

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020