One Score per Class

Classic MLHard+30 XP+30

One Score per Class

Logistic regression turns one weighted score into one probability, which is enough for a yes-or-no answer. To choose among kkk classes, give every class its own weights and its own score, and let the scores compete. This model is softmax regression, also called multinomial logistic regression.

For a row x=(x1,…,xd)x = (x_1, \dots, x_d)x=(x1​,…,xd​), each class c=0,1,…,k−1c = 0, 1, \dots, k-1c=0,1,…,k−1 gets a score and then a probability:

zc=bc+∑j=1dWc,j xjpc=ezcez0+ez1+⋯+ezk−1z_c = b_c + \sum_{j=1}^{d} W_{c,j}\, x_j \qquad\qquad p_c = \frac{e^{z_c}}{e^{z_0} + e^{z_1} + \dots + e^{z_{k-1}}}zc​=bc​+j=1∑d​Wc,j​xj​pc​=ez0​+ez1​+⋯+ezk−1​ezc​​

The pcp_cpc​ are positive and add up to 1. Training lowers the cross-entropy cost: the average over all nnn rows of −ln⁡py-\ln p_{y}−lnpy​, where yyy is the row's true class. Its gradient has a tidy form. For one row, the error of class ccc is

ec=pc−{1if c=y0otherwisee_c = p_c - \begin{cases} 1 & \text{if } c = y \\ 0 & \text{otherwise} \end{cases}ec​=pc​−{10​if c=yotherwise​

The gradient for Wc,jW_{c,j}Wc,j​ is the average of ec xje_c\, x_jec​xj​ over all rows, and the gradient for bcb_cbc​ is the average of ece_cec​.

Task: write train_softmax(X, y, k, lr, steps). Start with every weight and bias at 0, then run steps updates of batch gradient descent, each one moving every weight and bias by lr times its gradient, downhill:

Wc,j←Wc,j−lr×(gradient for Wc,j)bc←bc−lr×(gradient for bc)W_{c,j} \leftarrow W_{c,j} - \text{lr} \times \big(\text{gradient for } W_{c,j}\big) \qquad\qquad b_c \leftarrow b_c - \text{lr} \times \big(\text{gradient for } b_c\big)Wc,j​←Wc,j​−lr×(gradient for Wc,j​)bc​←bc​−lr×(gradient for bc​)
  • X is a list of nnn rows of ddd numbers. y holds each row's class, an integer from 0 to k - 1. A class may have no rows at all.
  • Every update uses all the rows, and every gradient in one update is computed from the weights as they were at the start of that update.
  • Return a tuple (W, b): W is a list of k lists of d weights and b is a list of k biases, all rounded to 4 decimal places.
  • One test has features in the hundreds, which pushes some scores into the tens of thousands. eze^{z}ez overflows long before that, so compute the probabilities in a way that never raises eee to a large positive power.

Examples

X = [[0.0], [1.0], [2.0]]
y = [0, 1, 2]
k = 3
lr = 0.5
steps = 1
returns ([[-0.1667], [0.0], [0.1667]], [0.0, 0.0, 0.0])
X = [[1.0, 2.0], [2.0, 0.5], [0.0, 1.5], [3.0, 1.0]]
y = [0, 1, 2, 1]
k = 3
lr = 0.1
steps = 2
returns ([[-0.0467, 0.0179], [0.1402, -0.0127], [-0.0935, -0.0052]], [-0.0153, 0.029, -0.0137])

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run