Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 01 · 35 minutes

Train your first model and ask it for a prediction

After this lesson you can
  • 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
Lab files of this lesson (4)

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.

From examples to a prediction
Your labIn useLabelled examplesTraining (fit)ModelNew login minutePrediction1234Your labIn useLabelledexamplesTraining (fit)ModelNew login minutePrediction1234
  1. Labelled examples → Training (fit): ten minutes with their right answers
  2. Training (fit) → Model: sets two weights and one bias
  3. New login minute → Model: the input [8, 5] goes in
  4. Model → Prediction: label 0, attack chance 0.43
WordPlain meaningIn this lesson
InputWhat you give the model to look atTwo counts for one minute of logins
OutputWhat the model answers0 (normal) or 1 (attack)
ParametersThe numbers that training sets and that make up the ruleTwo weights (a weight says how much one input counts) and one bias (a fixed number added to every sum)
TrainingFinding good parameters from examplesfit
PredictionUsing the parameters on a new inputpredict

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.

NamePlain meaningLearn it by doing
Machine learningModels that find their rule from examples, as hereThis course, lessons 1 and 3
Statistical learningThe same methods seen as statistics: fit numbers to data, measure the errorLesson 6, measure a model, and lesson 3, the test set
Deep learningMachine learning with neural networks of many layersLesson 8, neural networks
Natural language processing (NLP)Programs that work on human languageLessons 9 and 12, text as numbers and a phishing filter
Generative AIModels 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.py
ok   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 6

If 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.
  • LogisticRegression is 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. X is the list of inputs (one list of numbers for each example). y is the list of right answers.
  • predict returns a label for an input. predict_proba returns the chance of each label.
  • coef_ holds the weights and intercept_ 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]
Attack chance of three new inputs
[2, 1]0.01[8, 5]0.43[25, 20]1.00[2, 1]0.01[8, 5]0.43[25, 20]1.00

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.

The rule inside the model
0.466 x failedweight times failed logins+ 0.367 x usernamesweight times user names- 5.825the biasabove 0the answer is attack0.466 x failedweight times failed logins+ 0.367 x usernamesweight times user names- 5.825the biasabove 0the answer is attack

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 contactedSeconds between connectionsLabel
2300
3250
1400
4200
2350
5180
8011
15011
6021
30011
4531
12011

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_proba is 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.