22/26
Part 4 of 4 · Multiply, reshape, and put it togetherLearn and do

Use swapaxes, not .T, on a stack

To compare every student with every other student in the same class, multiply each table by its own flip. The flip turns rows into columns, so that each student's row meets every other student's row.

On a single table, .T is that flip. On a stack, .T flips every axis, including the class axis, and that's not what you want:

print(classes.T.shape)
print(np.swapaxes(classes, -1, -2).shape)
(3, 2, 2)
(2, 3, 2)

classes.T turned (2, 2, 3) into (3, 2, 2). It reversed all three axes. np.swapaxes(classes, -1, -2) swaps only the last two, students and tests, and leaves the class axis alone. Each class's (2, 3) table times its own (3, 2) flip gives a 2 by 2 table of student against student.

In the editor, write gram(x): entry [i, j] is row i dotted with row j, for one table or a stack of them. The editor prints the shape for classes, which should be (2, 2, 2).