Turn a model's scores into chances with softmax, then turn the temperature down and up to watch its answers become surer or more adventurous.
AI · beginner · 8 min · 16 steps · free
What you'll learn
Use softmax to turn scores into chances that add up to 1
Explain what low and high temperature do
Choose a temperature for a task
temperature.py
import math
# The model has scored three possible next words. Bigger score, better fit.
words = ["tea", "cake", "soup"]
scores = [2.0, 1.0, 0.5]
# Softmax turns scores into chances that add up to 1. Temperature decides how sure it sounds.
for temperature in [1.0, 0.5, 2.0]:
powered = [math.exp(s / temperature) for s in scores]
chances = [round(p / sum(powered), 2) for p in powered]
print("temperature", temperature, "->", chances)
Step by step
This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
Three possible next words.
The model's scores for them. Scores can be any numbers, even negative, so they are not chances yet.
Try three temperatures. First 1.0: the scores as they are.
Softmax step 1: e to the power of each score. Everything becomes positive, and bigger scores grow much bigger.
Step 2: divide each by the total, so they add up to 1. tea 0.63, cake 0.23, soup 0.14.
Print them.
Temperature 0.5: dividing by a small number stretches the scores apart.
Now tea's power is far bigger than the others.
tea 0.84. Low temperature makes the model surer: it will almost always say "tea".
It prints temperature 0.5 -> [0.84, 0.11, 0.04].
Temperature 2.0: dividing by a big number squeezes the scores together.
powered now points to a different list: [2.71828, 1.64872, 1.28403].
tea 0.48, cake 0.29, soup 0.23. Much more even: the model will sometimes pick cake or soup.
It prints temperature 2.0 -> [0.48, 0.29, 0.23].
Same scores, three temperatures, three moods. Low temperature is focused and repeatable (good for code and facts); high is varied and surprising (good for ideas). The model's knowledge never changed.
Common mistakes
Thinking temperature changes what the model knows: it only changes how it picks
Expecting temperature 0 answers to be correct, rather than just repeatable
Best practices
Use low temperature for facts and code, higher for brainstorming
Key takeaways
Softmax turns scores into chances: e to each score, divided by the total.
Temperature divides the scores first.
Low temperature sharpens the chances; high temperature flattens them.
Temperature changes how the model picks, not what it knows.
Check yourself
You want the same answer every time for a code question. Which temperature?
Answer: Low, near 0. Low temperature makes the top choice dominate, so answers repeat.
After softmax, what do the chances always add up to?
Answer: 1. Each value is divided by the total, so together they make 1.