Kumita← Open visual lesson

Logits

The code behind the picture

Follow the lesson’s implementation, one code cell at a time.

Choose a language and read the cells in order. These are small teaching examples; the visual lesson runs separately.

Follow the calculation

Same inputs · Same operation · Same result

3 teaching cells · Python standard library · Read-only

  1. 1. Prepare the inputs and one unit per class

    The inputs are the marked watermelon pixel's bytes divided by 255, in red, green, blue order, as in Linear Layer. W has one row per class and one column per input (4 × 3); b has one bias per class. The weights and biases are hand-set for this demonstration, not learned.

    import json
    
    pixel = [27, 166, 85]  # the marked watermelon pixel: red, green, blue bytes
    x = [value / 255 for value in pixel]
    classes = ["flesh", "rind", "seed", "background"]
    W = [[2, -2, 0], [-1, 3, -1], [-1, -1, -1], [1, 1, 2]]  # row k = class k
    b = [-0.5, -0.3, 1, -2.5]
  2. 2. Compute one logit per class

    Each class row is multiplied by the same inputs, added, and its bias added once. The results are raw scores: they may be negative or above one, and their sum is not one. Round the report to six decimal places.

    z = [sum(w * xi for w, xi in zip(row, x)) + bias for row, bias in zip(W, b)]
    result = {
        "logits": {name: round(score, 6) for name, score in zip(classes, z)},
        "sum": round(sum(z), 6),
    }
  3. 3. Inspect the result

    Print the result as JSON so both languages use the same output format.

    print(json.dumps(result))

Expected result

Running the three cells in order produces this result in either language.

{
  "logits": {
    "flesh": -1.590196,
    "rind": 1.213725,
    "seed": -0.090196,
    "background": -1.076471
  },
  "sum": -1.543137
}