r/learnmachinelearning • • 19d ago

Help trying to make CNN from scratch but i cannot understand this specific part

/r/MLQuestions/comments/1xyhp29/trying_to_make_cnn_from_scratch_but_i_cannot/
1 Upvotes

2 comments sorted by

1

u/Massive_Distance_616 19d ago

d_logits is “how much the loss changes if each logit changes”. For softmax followed by cross-entropy it works out to something very simple: the predicted probabilities, with 1 subtracted at the true class. That’s what p.copy() and then -= 1 at the label does. If the model gave the right class 0.9, the gradient on that logit is -0.1, so only a small nudge. If it gave it 0.1, the gradient is -0.9, a big nudge.

Your dense layer is logits = features @ W + b. Weight W[i, k] only affects the loss through logit k, and it gets multiplied by feature i, so its gradient is feature i times d_logits[k]. Doing all the weights at once, that’s features.T @ d_logits. The transpose is only there to make the shapes line up: (16 x N) times (N x 2) gives (16 x 2), the same shape as W.

The bias is added to every example’s logit with no multiplier, so its effect on the loss is just d_logits itself, summed over the examples. That’s why it’s sum(d_logits, axis=0).

For the next step, first get the gradient on your 16 pooled features with d_logits @ dense_weights.T, then go back through the global average pool. The same idea applies: each pixel of that 122x122 map gets the gradient of its pooled value divided by 122*122. Then it passes through the ReLU (zero wherever the forward output was zero), and then into the conv weights, which works like the dense case but summed over every position the filter slid over.

Once each piece is written, check it against a numerical gradient on a tiny input before moving to the next layer. It will save you a lot of debugging later.

2

u/boldbug-dev 18d ago

thanks man, this truly helped!!