Vectorized Operations

Apply math to whole arrays at once, with no Python loop and near-C speed.

Syntaxresult = array_a * array_b

Vectorization means writing a * 2 to double every element at once, instead of looping. It is shorter and dramatically faster.

Element-wise math

Arithmetic between arrays of the same shape works element by element. Functions like np.sqrt apply to every element.

Example

Example · python
import numpy as np

prices = np.array([10.0, 20.0, 30.0])
qty    = np.array([2, 1, 3])

totals = prices * qty
print(totals)          # [20. 20. 90.]
print(prices + 5)      # [15. 25. 35.]
print(np.sqrt(totals)) # [4.47 4.47 9.49]

When to use it

  • A researcher normalises a 1-million-row dataset by subtracting the mean and dividing by the standard deviation in two vectorised numpy operations instead of a Python loop.
  • A computer-vision engineer applies a sigmoid activation function to an entire array of raw model outputs in one np.exp call.
  • A finance analyst uses vectorised numpy arithmetic to compute daily returns across 500 stock time-series simultaneously.

More examples

Vectorised arithmetic vs loop

Applies a 10% discount to every price with a single multiplication, showing how vectorised ops replace slow Python loops.

Example · python
import numpy as np

prices = np.array([100.0, 200.0, 150.0, 300.0])

# Vectorised - fast
discounted = prices * 0.9

# Equivalent Python loop - slow at scale
discounted_loop = [p * 0.9 for p in prices]
print(discounted)

Element-wise math functions

Applies exponential, logarithm, and square-root functions element-wise to a whole array in a single call.

Example · python
import numpy as np

x = np.array([0.0, 1.0, 2.0, 3.0])

print(np.exp(x))    # e^x for each element
print(np.log(x + 1))  # log(x+1) to avoid log(0)
print(np.sqrt(x))

Sigmoid activation vectorised

Implements the sigmoid activation function using np.exp so it operates on every element of a logits array simultaneously, as used in logistic regression outputs.

Example · python
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

logits = np.array([-2.0, -0.5, 0.0, 1.5, 3.0])
probs = sigmoid(logits)
print(probs)

Discussion

  • Be the first to comment on this lesson.