Back to the Same Horse

Adversarial GenerationMedium+20 XP+20

Back to the Same Horse

Unpaired translation hands you two piles of photographs — horses in one, zebras in the other — and nothing linking a picture in one pile to a picture in the other. The adversarial loss on its own would be perfectly satisfied by a translator that ignores its input and emits the same convincing zebra every time. What rules that out is the round trip: turn a horse into a zebra, turn that back, and require what comes out to be the horse you started with.

Stripped down to something you can compute: every photograph is a short vector, and each translator is a matrix. to_zebra takes a horse vector to a zebra vector, to_horse takes one back, and a matrix is applied the usual way:

(Mv)i=∑jMijvj(M v)_i = \sum_j M_{ij} v_j(Mv)i​=∑j​Mij​vj​

Task: write cycle_loss(horses, zebras, to_zebra, to_horse), returning two numbers, each rounded to 4 decimal places: the cycle loss over the horse pile, then the cycle loss over the zebra pile.

  • One photograph's cycle error is the mean absolute difference, across its coordinates, between the photograph and its own round trip.
  • A pile's cycle loss is the mean of those errors over the photographs in that pile.
  • The piles are unpaired: they may be different sizes, and the nnn-th horse has nothing to do with the nnn-th zebra. Neither pile is empty.
  • Every vector has the same length, and both matrices are square of that size.

Notice what this loss never asks: whether the output is a convincing zebra. That question belongs to the discriminator. The round trip is here for the other half of the job — making sure the thing that comes out still has anything to do with the thing that went in.

Examples

horses = [[1.0, 2.0], [-3.0, 0.5]]
zebras = [[0.0, 4.0], [2.5, -1.0], [1.0, 1.0]]
to_zebra = [[0.0, -1.0], [1.0, 0.0]]
to_horse = [[0.0, 1.0], [-1.0, 0.0]]
returns [0.0, 0.0]
horses = [[1.0, 3.0], [0.0, 1.0], [2.0, -2.0]]
zebras = [[1.0, 1.0], [0.0, 4.0]]
to_zebra = [[0.5, 0.5], [0.5, 0.5]]
to_horse = [[1.0, 0.0], [0.0, 1.0]]
returns [1.1667, 1.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run