Kumita← Open visual lesson

Prediction

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 labels, scores and reference

    Four labels in a fixed order and one hand-set logit per label (demonstration scores, not a trained recognizer). The reference label is supplied with the picture; it is not computed from the scores.

    import json
    import math
    
    labels = ["watermelon", "fried egg", "mug", "no target object"]
    reference = "watermelon"  # supplied with the picture
    score_sets = {
        "A": [2.1, 0.4, -0.6, 0.8],
        "B": [1.0, -0.4, 0.0, 0.9],
        "D": [1.1, -0.2, 0.3, 1.1],  # an exact tie
        "E": [0.3, 2.5, -0.4, 0.6],  # chosen to show a mistake
    }
  2. 2. Softmax, argmax and the label

    A stable softmax gives the shares. Argmax compares full values with a strict >, so in a tie the first tied position wins (the declared tie rule). The position is then looked up in the label list, and only then compared with the reference. Shares are rounded to six decimals for the report only.

    def softmax(z):
        m = max(z)
        e = [math.exp(v - m) for v in z]
        return [v / sum(e) for v in e]
    
    def argmax(values):
        best = 0
        for k in range(1, len(values)):
            if values[k] > values[best]:
                best = k
        return best
    
    result = {}
    for name, z in score_sets.items():
        p = softmax(z)
        k = argmax(p)
        result[name] = {
            "index": k,
            "label": labels[k],
            "share": round(p[k], 6),
            "same_as_logit_argmax": argmax(z) == k,
            "correct": labels[k] == reference,
        }
  3. 3. Inspect the result

    Print the result as JSON so both languages use the same output format. B wins below one half, D is settled by the tie rule, and E is confidently wrong.

    print(json.dumps(result))

Expected result

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

{
  "A": {
    "index": 0,
    "label": "watermelon",
    "share": 0.656849,
    "same_as_logit_argmax": true,
    "correct": true
  },
  "B": {
    "index": 0,
    "label": "watermelon",
    "share": 0.396933,
    "same_as_logit_argmax": true,
    "correct": true
  },
  "D": {
    "index": 0,
    "label": "watermelon",
    "share": 0.367396,
    "same_as_logit_argmax": true,
    "correct": true
  },
  "E": {
    "index": 1,
    "label": "fried egg",
    "share": 0.760228,
    "same_as_logit_argmax": true,
    "correct": false
  }
}