I am trying to write my own backpropogation algorithm for neural networks for a class. For any specific weight of my network I could easily take the derivative, but for computational speed I want to write the derivatives out in terms of matrix expressions that could be simply coded and executed. Let us use the following notation: let $x\in\mathbb{R}^p$ be our set of $p$ inputs to our network. Let us have $m$ hidden layers of nodes each consisting of $n$ nodes. We will write the values at the $i^{th}$ hidden layer as $z_i$, which are retieved from multipling the $i^{th}$ weight matrix $W_i$ by the previous layer a chosen function $f$ (sigmoid, RELU, etc). Finally, we consider only $1$ output node (since we could loop through the output nodes and do this for all of them, although it'd be nice to generalize).
As such we can say that our network is given as $$ z_1 = f(W_1 x) $$ $$ z_2 = f(W_2 z_1) $$ $$ \vdots $$ $$ z_n = f(W_n z_{n-1}) $$ $$ \hat{y} = f(W_{n+1} z_n) $$
Using Mean Squared Error we get that our objective function for a given point is $$ MSE = (\hat{y} - y)^2 $$
The first update matrix (which is actually a vector) was fairly easy to find the update for. I found that $$ \frac{\partial(MSE)}{\partial W_{n+1}} = 2(\hat{y}-y)f'(W_{n+1}z_n) z_n = k_n z_n $$
where $k_n=2(\hat{y}-y)f'(W_{n+1}z_n)$. From here the next layer is also special I found that if we let $$ \frac{\partial(MSE)}{\partial W_n} = k_n (W_{n+1}\circ f'(W_n z_{n-1}))\otimes z_{n-1} = k_{n-1}\otimes z_{n-1} $$
where $\circ$ represents the element wise multiplication and $\otimes$ represents the outer product. The final formula I get is the one that should (in theory) work for every layer following, however I am getting a code error on the final step that the matrix dimensions I have do not properly line up, which means I must have a problem with my formula. I find that if $$ k_i = (k_{i+1}^T W_i)\circ f'(W_i z_{i-1}) $$ then we can say that $$ \frac{\partial (MSE)}{\partial W_i} = k_i \otimes z_{i-1} $$
If anyone can help me find an error that'd be much appreicated!