6  NumPy Vectorized Operations

This notebook focuses on elementwise math, broadcasting, and simple linear algebra.

import numpy as np

daily_users = np.array([120, 150, 180, 210])
conversion_rates = np.array([0.04, 0.05, 0.03, 0.06])
feature_matrix = np.array(
    [
        [1.0, 10.0, 100.0],
        [2.0, 20.0, 200.0],
        [3.0, 30.0, 300.0],
    ]
)
scale = np.array([0.1, 1.0, 0.01])

6.1 Exercise 1

Estimate conversions by multiplying daily_users and conversion_rates elementwise.

# TODO: Use elementwise multiplication.
estimated_conversions = daily_users ____ conversion_rates
estimated_conversions

6.2 Exercise 2

Square the daily_users array.

# TODO: Apply an elementwise power operation.
users_squared = daily_users __ 2
users_squared

6.3 Exercise 3

Use broadcasting to scale each column of feature_matrix by scale.

# TODO: Multiply the matrix by the scale vector.
scaled_features = feature_matrix ____ scale
scaled_features

6.4 Exercise 4

Compute the dot product between weights and inputs.

weights = np.array([0.2, 0.3, 0.5])
inputs = np.array([5.0, 10.0, 2.0])

# TODO: Use np.dot to combine the vectors.
score = np.dot(____, ____)
score

6.5 Exercise 5

Create a random integer array with shape (2, 3) using a seeded generator.

# TODO: Use the explicit generator pattern from modern NumPy.
rng = np.random.default_rng(seed=____)
random_batch = rng.integers(0, 10, size=(__, __))
random_batch