r/learnmachinelearning • u/boldbug-dev • 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
1
u/Massive_Distance_616 19d ago
d_logitsis “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 whatp.copy()and then-= 1at 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. WeightW[i, k]only affects the loss through logitk, and it gets multiplied by featurei, so its gradient is featureitimesd_logits[k]. Doing all the weights at once, that’sfeatures.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 asW.The bias is added to every example’s logit with no multiplier, so its effect on the loss is just
d_logitsitself, summed over the examples. That’s why it’ssum(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.