1. Fraud check: distances from new transactions to known fraud, without a loop
A fraud team wants to flag a new card transaction when it sits very close to a transaction that was already confirmed as fraud. Each transaction is a feature row, for example [unix timestamp in seconds, amount]. Nearest-neighbour search, k-means and retrieval all start with the same step: the distance from every row of A to every row of B. A double for loop over thousands of rows is far too slow in Python, so you use broadcasting.
Write pairwise_dist(A, B) where A has shape (n, d) and B has shape (m, d). Return an (n, m) float array where entry [i, j] is the Euclidean distance between A[i] and B[j].
Rules:
- Exact enough for raw, unscaled features. Timestamps are about 1.7e9. The popular shortcut sqrt(|a|^2 + |b|^2 - 2 a.b) subtracts two huge numbers that are almost equal and loses the answer: for two transactions 3.5 seconds and 3.5 units apart it returns 0.0 instead of about 4.95. Subtract the rows first, then square.
- The distance from a row to itself is exactly 0.0, never nan.
- A and B can be lists or NumPy arrays of ints or floats. n and m can be 1; the result is still 2-D.
def pairwise_dist(A, B)Example 1
Input: A = [[0, 0]], B = [[3, 4], [0, 1]]
Output: [[5.0, 1.0]]
Example 2
Input: list(np.asarray(pairwise_dist([[0.0, 0.0, 0.0]], [[1.0, 2.0, 2.0]])).shape)
Output: [1, 1]
Example 3
Input: A = [[1, 2]], B = [[1, 2], [4, 6]]
Output: [[0.0, 5.0]]
Constraints
Ahas shape(n, d)Bhas shape(m, d)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 7 tests to be accepted.
Hint 1
Reshape A to (n, 1, d) and B to (1, m, d).
Hint 2
Subtracting them broadcasts to (n, m, d).
Hint 3
Square, sum over the last axis, take the square root.
Understand the idea
Many algorithms need the distance from every row of A to every row of B. A double loop works but is slow in Python. Broadcasting lets NumPy pair every row of A with every row of B at once, like making a full mileage table between two lists of cities. Add a new axis so A becomes (n, 1, d) and B becomes (1, m, d); their difference is then (n, m, d). Square, sum over d, and take the square root.
A = [[1, 2]], B = [[4, 6], [1, 2]]. First pair: difference (3, 4), squares 9 + 16 = 25, root 5. Second pair: difference (0, 0), distance 0. Output [[5.0, 0.0]].
D[i, j] = sqrt(sum over k of (A[i, k] - B[j, k])^2)
Forgetting the square root gives squared distances, a common bug. k-nearest neighbours, k-means and vector search all start with this matrix.