Lesson 01 · 35 minutes
Train your first model and ask it for a prediction
- Train a model on a few hand-made examples
- Name the input, the output and the parameters of a model
- Train a second model on new data and read its parameters
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your company has bought a detector for login attacks. The vendor says that it "learns what an attack looks like from examples". Your manager does not want a slide. "Show me what a model really is," she says, "so that I can ask the vendor the right questions." You will train the smallest real model on your own laptop and read every number in it. Then you will train a second model on port-scan data, with no steps to follow.
The idea
A normal program is a set of rules that a person writes: if there are more than ten failed logins, raise an alert. A model is different. A person gives it examples and the right answers, and a training program finds the rule by itself. The rule is stored as numbers.
- Labelled examples → Training (fit): ten minutes with their right answers
- Training (fit) → Model: sets two weights and one bias
- New login minute → Model: the input [8, 5] goes in
- Model → Prediction: label 0, attack chance 0.43
| Word | Plain meaning | In this lesson |
|---|---|---|
| Input | What you give the model to look at | Two counts for one minute of logins |
| Output | What the model answers | 0 (normal) or 1 (attack) |
| Parameters | The numbers that training sets and that make up the rule | Two weights (a weight says how much one input counts) and one bias (a fixed number added to every sum) |
| Training | Finding good parameters from examples | fit |
| Prediction | Using the parameters on a new input | predict |
You will hear several names for kinds of AI. They overlap: each is a smaller circle inside a wider one, or the same thing seen from another side.
| Name | Plain meaning | Learn it by doing |
|---|---|---|
| Machine learning | Models that find their rule from examples, as here | This course, lessons 1 and 3 |
| Statistical learning | The same methods seen as statistics: fit numbers to data, measure the error | Lesson 6, measure a model, and lesson 3, the test set |
| Deep learning | Machine learning with neural networks of many layers | Lesson 8, neural networks |
| Natural language processing (NLP) | Programs that work on human language | Lessons 9 and 12, text as numbers and a phishing filter |
| Generative AI | Models that make new text, images or sound | "How LLMs and agents work", lessons 1 and 9 (text; images and sound only in one Field note of lesson 9) |
| Language models, large (LLM) and small (SLM) | Generative models that predict the next token of text | "How LLMs and agents work", lessons 1, 3 and 9 |
Training happens once. After that, a prediction is a small calculation with fixed numbers. Every attack on a model in the later courses changes either the examples (before training), the parameters (after training) or the input (at prediction time).
Worked example
1. Open your lab
Lesson 0 made the folder ~/krlab/how-ai-works and a virtual environment (a private set of Python packages) inside it. cd moves you into the folder. source .venv/bin/activate switches the environment on, and the prompt starts with (.venv). Do this at the start of every lesson.
cd ~/krlab/how-ai-works
source .venv/bin/activate
python labcheck.pyok python 3.14.4
ok venv /home/you/krlab/how-ai-works/.venv
ok sklearn 1.9.1 (the lessons use 1.9.x)
ok numpy 2.5.5 (the lessons use 2.5.x)
ok joblib 1.6.0 (the lessons use 1.6.x)
ok model trained and predicted
lab ready: 6 of 6If the last line says something else, go back to lesson 0.
2. Write the examples and train
Each example is one minute of a login log: how many logins failed, and how many different user names were tried. A person has labelled each one. Create first_model.py with an editor. These words appear in it for the first time:
- scikit-learn is the Python library of this course. Its package name in code is
sklearn. LogisticRegressionis a class (a blueprint for objects) from scikit-learn. It is one of the simplest model types: it multiplies each input by a weight, adds the results, and turns the sum into a chance between 0 and 1.fit(X, y)is the training step.Xis the list of inputs (one list of numbers for each example).yis the list of right answers.predictreturns a label for an input.predict_probareturns the chance of each label.coef_holds the weights andintercept_holds the bias, after training. A large weight means that its input pushes the answer strongly..round(3)keeps three decimals.
A line that starts with # is a comment: Python ignores it. In f"{chance:.2f}", the part :.2f prints a number with two decimals. A for line repeats the lines under it once for each item of the list. model.predict_proba([sample])[0][1] takes the first row of the answer and its second number: the chance of label 1.
first_model.py
from sklearn.linear_model import LogisticRegression
# [failed logins in the last minute, distinct usernames tried]
X = [[1, 1], [0, 1], [2, 1], [1, 1], [3, 1],
[20, 15], [35, 30], [12, 9], [50, 40], [18, 12]]
y = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] # 0 = normal, 1 = attack
model = LogisticRegression()
model.fit(X, y)
for sample in ([2, 1], [25, 20], [8, 5]):
label = model.predict([sample])[0]
chance = model.predict_proba([sample])[0][1]
print(sample, "->", label, f"(attack chance {chance:.2f})")
print("weights:", model.coef_.round(3), "bias:", model.intercept_.round(3))3. Run it and ask for predictions
python first_model.py[2, 1] -> 0 (attack chance 0.01)
[25, 20] -> 1 (attack chance 1.00)
[8, 5] -> 0 (attack chance 0.43)
weights: [[0.466 0.367]] bias: [-5.825]The model never saw any of these three inputs. The first two are clear. The third is in between, and the model shows it: the chance is 0.43, close to a coin toss, and the label is 0 only because 0.43 is below 0.5.
4. Read the parameters
The last line of the output is the whole model: one weight for each input and one bias.
For [8, 5] the sum is 3.728 + 1.835 - 5.825 = -0.262, which is below zero. A sum of 0 means a chance of 0.5, a negative sum a chance below 0.5, and a positive sum a chance above it. The bias is a fixed number that is added to every sum: it moves the point where the answer flips.
You can check this model by hand. Large models are the same idea with millions of numbers.
5. Compare with a rule that a person writes
A person would write this: more than ten failed logins is an attack. A def line defines a function: a named piece of code that you can call. rule(*s) hands the two numbers of a list s to the function as two separate values. Create rule.py.
rule.py
def rule(failed, names):
return 1 if failed > 10 else 0
print([rule(*s) for s in ([2, 1], [25, 20], [8, 5])])python rule.py[0, 1, 0]For these inputs the rule gives the same labels. The difference is where the number 10 comes from. You chose it. The model found its numbers from the data. When the data changes, you retrain; you do not rewrite the rule.
Your turn
A port scan touches many ports of a host in a short time. A firewall has logged twelve minutes of traffic from single hosts. Each row gives the distinct ports that the host contacted in the minute, the mean number of seconds between its connections, and the label that an analyst gave (1 is a scan).
| Ports contacted | Seconds between connections | Label |
|---|---|---|
| 2 | 30 | 0 |
| 3 | 25 | 0 |
| 1 | 40 | 0 |
| 4 | 20 | 0 |
| 2 | 35 | 0 |
| 5 | 18 | 0 |
| 80 | 1 | 1 |
| 150 | 1 | 1 |
| 60 | 2 | 1 |
| 300 | 1 | 1 |
| 45 | 3 | 1 |
| 120 | 1 | 1 |
There are no steps here. Train a LogisticRegression on these rows with its default settings. Ask it about four minutes that are not in the table: [40, 4], [10, 15], [25, 8] and [6, 12]. Print the label and the scan chance of each, and read the weights.
Last, write the rule "more than 20 ports is a scan" and compare it with the model on all four minutes. They disagree on [25, 8]. Which answer would you trust, and what would you do to settle it?
Check yourself
What are the input, the output and the parameters of the model you trained?
The input is a pair of numbers (failed logins, distinct user names). The output is a label, 0 or 1. The parameters are the two weights and the bias that fit set.
The model says "attack chance 0.43" and the label is 0. Is the model sure?
No. The chance is close to 0.5. The label comes from a cut-off (0.5), which hides how unsure the model is. In a real detector you read the chance, not only the label.
You add ten more labelled examples and run fit again. What changes?
The parameters change, because fit starts again and finds new numbers. The code of the model does not change. This is why the examples matter as much as the program.
A vendor sells "deep learning for NLP". What two things does that tell you?
The model is a neural network with many layers (deep learning, a kind of machine learning), and it works on human language (NLP). It does not say that the model writes new text.
Field notes
- Record the versions with
pip freeze > my-versions.txt. A model, its numbers and its behaviour can change with a library version, so a result without versions is not reproducible. - Ten examples are far too few. The point here is to see the parts. A model built on a handful of examples can look sure and be wrong; more data and a held-out test (lesson 3) are the cure.
predict_probais not always a true probability. Many models give scores that are too sure or not sure enough. Calibration checks whether "0.9" really means "right nine times in ten". It matters when an alert has a cost.- Name the training data as part of the system. If an attacker can change the examples (data poisoning), the model learns the attacker's rule. Public risk lists for AI systems, such as the OWASP Top 10 for LLM applications and MITRE ATLAS, treat this as a main risk.