24/26
Part 4 of 4 · Multiply, reshape, and put it togetherLearn and do

Put it together: a masked softmax

A shop shows each user three products. It gives each product a match score for each user. Then it turns each user's scores into chances that add up to 1, so better matches get shown more often. That last step is a softmax.

One rule: a product the user already bought must get chance 0.

# user 0's score for products 0, 1, 2
match = np.array([[2., 1., 0.],
                  # user 1
                  [0., 3., 1.],
                  # user 2
                  [1., 1., 1.]])
# user 0 bought product 1
bought = np.array([[False, True, False],
                   # user 1 bought nothing
                   [False, False, False],
                   # user 2 bought product 0
                   [True, False, False]])
masked = np.where(bought, -np.inf, match)
print(masked)
[[  2. -inf   0.]
 [  0.   3.   1.]
 [-inf   1.   1.]]

np.where(bought, -np.inf, match) takes minus infinity where bought is True and the match score everywhere else. Minus infinity is the trick: in a softmax it becomes exactly 0.

Now the softmax. It turns each row into chances that add up to 1:

def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
    """Turns each row of x into chances that add up to 1."""
    # each row minus its max
    z = x - x.max(axis=axis, keepdims=True)
    # every number is positive
    e = np.exp(z)
    return e / e.sum(axis=axis, keepdims=True)

chance = softmax(masked, axis=-1)
print(chance.round(3))
print(chance.sum(axis=-1))
[[0.881 0.    0.119]
 [0.042 0.844 0.114]
 [0.    0.5   0.5  ]]
[1. 1. 1.]

The last line divides each row by its own total, so every row adds up to 1. Every product a user bought has chance 0, because exp(-inf) is 0. User 2 gave products 1 and 2 the same score, so they get the same chance, 0.5 each.

Subtracting each row's max first doesn't change the result. It keeps exp from overflowing when scores are large.

Look at what the function used: a max along an axis, keepdims, and broadcasting, twice. That's this lesson.

In the editor, write masked_softmax(match, bought) from the two pieces above: the np.where mask, then the softmax along the last axis. The checks use a stack of tables and very large scores.