Error: Transposed is only defined for rank 2 tensors

Please note that the code you have supplied is not complete, and can not reproduce your error message. For further questions, I would recommend you to follow the examples posted at: Read before posting: How do I get my question answered? - #4 by nate
and make sure your code reproduces your error message.

For this particular problem, the culprit is most likely

as I think you meant to use p_i and not pi