Turn each row of counts into a probability distribution

Count matrices, like how often each token follows another, become probability tables once every row sums to 1.

Write row_normalize(X) for a 2D array of non-negative numbers. Return a float array of the same shape where each row is divided by its own sum. A row that sums to 0 stays all zeros.

Signaturedef row_normalize(X)

Example

row_normalize([[1, 3], [0, 0]]) is [[0.25, 0.75], [0, 0]].

Understand the idea

A count matrix, such as how often each token follows another, becomes a table of probabilities when each row is divided by its own total. Then every row sums to 1 and reads as 'given this row, how likely is each column'. Rows that are all zero have no data, so they stay zeros rather than becoming NaN. Worked example: X = [[2, 6, 2], [0, 0, 0]]. Row 0 sums to 10, so it becomes [0.2, 0.6, 0.2]. Row 1 sums to 0, so it stays [0, 0, 0]. Rule: compute the sum along each row, keeping a column shape (n, 1) so it broadcasts across the row; divide only where the sum is positive and put 0 elsewhere; return a float array of the same shape. Dividing by column sums is the common slip: the shapes still line up for square inputs, but rows no longer sum to 1. This is how bigram language model tables and transition matrices for Markov chains are built from counts.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplerow_normalize([[1, 3], [0, 0]])
  • Sample 2: three rowsrow_normalize([[2, 2, 4], [5, 0, 0], [1, 1, 1]])
  • Test 3: single rowrow_normalize([[7, 1]])