Through the Narrow Middle

Learning to CompressMedium+20 XP+20

Through the Narrow Middle

A small autoencoder works on greyscale strips: each strip is a list of nnn pixel brightnesses between 0 and 1. The encoder squeezes the strip down to a code of kkk numbers, the decoder rebuilds the strip from that code alone, and the reconstruction loss scores how good the copy is.

Encoder: one layer, ReLU. enc_w is a list of kkk rows, one per code number, and each row holds nnn weights, one per pixel. enc_b holds kkk biases. Code number jjj is

cj=max⁡(0, ∑iWji xi+bj)c_j = \max\Big(0,\ \sum_{i} W_{ji}\, x_i + b_j\Big)cj​=max(0, i∑​Wji​xi​+bj​)

where WjiW_{ji}Wji​ is enc_w[j][i] and bjb_jbj​ is enc_b[j].

Decoder: one layer, sigmoid. dec_w is a list of nnn rows, one per rebuilt pixel, and each row holds kkk weights, one per code number. dec_b holds nnn biases. Rebuilt pixel iii is

x^i=σ(∑jVij cj+di),σ(z)=11+e−z\hat{x}_i = \sigma\Big(\sum_{j} V_{ij}\, c_j + d_i\Big), \qquad \sigma(z) = \frac{1}{1 + e^{-z}}x^i​=σ(j∑​Vij​cj​+di​),σ(z)=1+e−z1​

where VijV_{ij}Vij​ is dec_w[i][j] and did_idi​ is dec_b[i].

Reconstruction loss. Subtract, square, then average over every pixel:

L=1n∑i(x^i−xi)2L = \frac{1}{n}\sum_{i} (\hat{x}_i - x_i)^2L=n1​i∑​(x^i​−xi​)2

Task: write autoencode(x, enc_w, enc_b, dec_w, dec_b) and return a tuple (code, rebuilt, loss):

  • code: the list of kkk code numbers,
  • rebuilt: the list of nnn rebuilt pixels,
  • loss: a single number.

Round every returned number to 4 decimal places. Round only at the end: compute the loss from the unrounded rebuilt pixels.

Notice what the loss compares against. There is no label anywhere: the target is the input itself.

→
→

The task is simply: reproduce your own input. It sounds pointless until you look at the narrow part in the middle.

Examples

x = [0.9, 0.8, 0.1, 0.2]
enc_w = [[1.0, 1.0, -1.0, -1.0], [-1.0, -1.0, 1.0, 1.0]]
enc_b = [0.0, 0.5]
dec_w = [[2.0, -1.0], [2.0, -1.0], [-2.0, 1.0], [-2.0, 1.0]]
dec_b = [0.5, 0.0, -0.5, 0.0]
returns ([1.4, 0.0], [0.9644, 0.9427, 0.0356, 0.0573], 0.0123)
x = [0.2, 0.7, 0.4]
enc_w = [[0.5, 1.0, -0.5]]
enc_b = [0.1]
dec_w = [[-1.0], [1.5], [0.2]]
dec_b = [-1.0, 0.3, -0.5]
returns ([0.7], [0.1545, 0.7941, 0.411], 0.0037)

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