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

Set-up · 20 minutes

Set up your lab for AI governance for engineers

After this lesson you can
  • Create the lab folder and a virtual environment with pinned versions
  • Generate the synthetic data files that the course uses
  • Prove with a check script that the lab works
Lab files of this lesson (3)

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. Type the code yourself first: you learn more.

What you need

  • The courses "AI security fundamentals" (its lesson 8 checks a third-party provider) and "Security fundamentals" (its lesson 1 scores risks). This course turns those ideas into files and scripts. The course "How AI works" explains the model that lessons 4 and 5 train. The course "Python for security work" comes first for the code: the lessons use functions, loops, files, dictionaries and f-strings, and explain only what is new.
  • Python 3.12 or newer. The pinned libraries below need it. Check it in step 2. The checkers of lessons 1 to 3 and 6 to 13 use only the standard library, and they run on Python 3.10 or later.
  • A terminal and a text editor. About 500 MB of free disk space. No GPU, no account, no paid service, no model server.

Everything runs on your own computer, in one folder: ~/krlab/ai-governance. All data is synthetic: every company, person, product and domain in this course is invented, and no file holds a real person's data.

The lab folder when the set-up is done
Lab folder.venvlabcheck.pydata foldermakedata.py123Lab folder.venvlabcheck.pydatafoldermakedata.py123
  1. makedata.py → data folder: writes three CSV files
  2. labcheck.py → .venv: checks Python and the pinned versions
  3. labcheck.py → data folder: checks the three fingerprints

This course is not a law course and gives no legal advice. It names the main frameworks, says what each one asks an engineer to produce, and shows how to produce it with scripts and files. Whether a rule applies to your organisation is a question for your legal and compliance people, and the current official text decides it.

Set it up

1. Make the lab folder

mkdir -p (make directory, with its parents) creates the folder. cd (change directory) moves you into it.

mkdir -p ~/krlab/ai-governance
cd ~/krlab/ai-governance
pwd
/home/you/krlab/ai-governance

2. Check your Python

python3 --version prints the version of Python. If the number is below 3.12, install a newer Python first. On Debian or Ubuntu the command is sudo apt install python3.12 python3.12-venv, and then you type python3.12 in place of python3 in step 3. That command needs sudo and a network, so it is not tested here.

python3 --version
Python 3.14.4

3. Make a virtual environment

A virtual environment is a private folder of Python packages, so that the packages of this course cannot break the Python of your system. python3 -m venv .venv creates it. source .venv/bin/activate switches it on, and from then on python and pip mean the ones in .venv. pip installs packages. Run the source line at the start of every lesson.

python3 -m venv .venv
source .venv/bin/activate

4. Pin the versions and install

A pinned version is an exact one, written with ==. A model is numbers, and its numbers can change between versions of a library. If everyone installs the same versions, everyone gets the same numbers, and the answers that the lessons check are the same for you as for the author. These are the versions of the course "How AI works".

requirements.txt

scikit-learn==1.9.1
numpy==2.5.5
scipy==1.18.1
joblib==1.6.0

pip install -r requirements.txt installs everything in the file (-r means "read the list from a file"). This step needs an internet connection once.

pip install -r requirements.txt

5. Save the data generator

The generator writes three files into data/. loans.csv holds invented loan applications for lessons 4 and 5. screening.csv holds invented past hiring decisions for lesson 4 and the scenario test. records.csv holds invented network and expense records for lesson 2. random.Random(seed) makes a random generator with a fixed start, so it gives the same numbers on every machine. csv reads and writes comma-separated files. hashlib.sha256 makes a fingerprint of some bytes: if one byte changes, the fingerprint changes.

makedata.py

"""makedata.py: write the three synthetic data files of the course. Every value is invented.

A fixed seed gives the same files on every machine. Only random() is used, so the numbers
do not depend on the Python version.
"""
import csv
import hashlib
import random
from pathlib import Path

DATA = Path("data")


def pick(rnd, items):
    return items[int(rnd.random() * len(items))]


def write(name, header, rows):
    DATA.mkdir(exist_ok=True)
    with open(DATA / name, "w", newline="") as f:
        out = csv.writer(f, lineterminator="\n")
        out.writerow(header)
        out.writerows(rows)


def loans(n=1000, seed=7):
    """Loan applications. Group B has a lower income on average. The group is not used to decide `repaid`."""
    rnd = random.Random(seed)
    rows = []
    for i in range(1, n + 1):
        group = "A" if rnd.random() < 0.6 else "B"
        income = round(25 + 45 * rnd.random() + (10 if group == "A" else 0))
        debt = round(0.10 + 0.50 * rnd.random(), 2)
        years = int(10 * rnd.random())
        score = 0.06 * income - 5 * debt + 0.15 * years + 2 * (rnd.random() - 0.5)
        rows.append([f"L{i:04d}", group, income, f"{debt:.2f}", years, 1 if score > 1.8 else 0])
    write("loans.csv", ["id", "group", "income", "debt_ratio", "history_years", "repaid"], rows)


def screening(n=800, seed=11):
    """Past hiring decisions. Group B has longer career gaps, and past managers penalised a gap."""
    rnd = random.Random(seed)
    rows = []
    for i in range(1, n + 1):
        group = "A" if rnd.random() < 0.55 else "B"
        test = round(40 + 50 * rnd.random())
        years = int(12 * rnd.random())
        gap = int(rnd.random() * (6 if group == "A" else 30))
        score = 0.04 * test + 0.12 * years - 0.05 * gap + 1.5 * (rnd.random() - 0.5)
        rows.append([f"P{i:04d}", group, test, years, gap, 1 if score > 3.3 else 0])
    write("screening.csv", ["id", "group", "test_score", "years", "gap_months", "hired"], rows)


AI_NET = ["chat.novachat.example", "api.lumina-ai.example", "ask.pilotwrite.example", "models.deepgrove.example"]
OTHER_NET = ["mail.corpmail.example", "files.cloudbox.example", "cal.planner.example", "wiki.docnest.example",
             "video.meetroom.example", "shop.mylumina-ai.example"]
AI_EXPENSE = ["SummarizeIt Pro, 1 seat, annual", "CodePal Team, monthly", "VoiceNote AI, 3 seats"]
OTHER_EXPENSE = ["Train ticket, Hamburg", "Team lunch", "Office chairs, 4", "Domain renewal", "Conference ticket"]
TEAMS = ["sales", "support", "finance", "engineering", "legal"]


def records(n=300, seed=3):
    """Network and expense records. `shop.mylumina-ai.example` is a decoy: it is not an AI domain."""
    rnd = random.Random(seed)
    rows = []
    for i in range(1, n + 1):
        team = pick(rnd, TEAMS)
        if rnd.random() < 0.6:
            ai = rnd.random() < 0.3
            rows.append([f"R{i:03d}", "network", team, pick(rnd, AI_NET if ai else OTHER_NET)])
        else:
            ai = rnd.random() < 0.2
            rows.append([f"R{i:03d}", "expense", team, pick(rnd, AI_EXPENSE if ai else OTHER_EXPENSE)])
    write("records.csv", ["id", "source", "team", "item"], rows)


if __name__ == "__main__":
    loans()
    screening()
    records()
    for name in ("loans.csv", "screening.csv", "records.csv"):
        data = (DATA / name).read_bytes()
        print(name.ljust(14), str(data.count(b"\n") - 1).rjust(5), "rows", hashlib.sha256(data).hexdigest()[:8])
python makedata.py
loans.csv       1000 rows b498e6c4
screening.csv    800 rows 39c79021
records.csv      300 rows 80b42b54

The last column is the fingerprint: the first 8 characters of the SHA-256 hash of the file. If yours differ, the check script below tells you which file is wrong.

Check your lab

The script labcheck.py proves that the lab works. It checks the Python version, that you are inside the virtual environment, that scikit-learn, NumPy and joblib have the pinned major and minor number, that the three data files have the right fingerprint, and that a tiny model trains. sys.prefix is the folder of the Python that runs, and it differs from sys.base_prefix only inside a virtual environment. __import__(name) loads a library whose name is in a variable. sys.exit(1) ends the program with exit code 1, which means "failed".

labcheck.py

"""labcheck.py: prove that the lab of "AI governance for engineers" works."""
import hashlib
import sys
from pathlib import Path

PINNED = {"sklearn": "1.9", "numpy": "2.5", "joblib": "1.6"}
DATA = {"loans.csv": "b498e6c4", "screening.csv": "39c79021", "records.csv": "80b42b54"}
results = []


def check(name, ok, detail):
    results.append(ok)
    print(("ok   " if ok else "FAIL ") + name.ljust(10) + detail)


v = sys.version_info
check("python", v >= (3, 12), f"{v.major}.{v.minor}.{v.micro}")
check("venv", sys.prefix != sys.base_prefix, sys.prefix)

for module, want in PINNED.items():
    try:
        lib = __import__(module)
        have = ".".join(lib.__version__.split(".")[:2])
        check(module, have == want, f"{lib.__version__} (the lessons use {want}.x)")
    except ImportError:
        check(module, False, "not installed")

for name, fingerprint in DATA.items():
    path = Path("data") / name
    got = hashlib.sha256(path.read_bytes()).hexdigest()[:8] if path.exists() else "missing"
    check(name.split(".")[0], got == fingerprint, f"{path} fingerprint {got}")

try:
    from sklearn.linear_model import LogisticRegression

    model = LogisticRegression().fit([[0], [1], [2], [3]], [0, 0, 1, 1])
    check("model", list(model.predict([[0], [3]])) == [0, 1], "trained and predicted")
except Exception as error:
    check("model", False, str(error))

print(f"lab ready: {sum(results)} of {len(results)}")
sys.exit(0 if all(results) else 1)
python labcheck.py
ok   python    3.14.4
ok   venv      /home/you/krlab/ai-governance/.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   loans     data/loans.csv fingerprint b498e6c4
ok   screening data/screening.csv fingerprint 39c79021
ok   records   data/records.csv fingerprint 80b42b54
ok   model     trained and predicted
lab ready: 9 of 9

Your Python version and your folder can differ. Every other line must be the same. Type the last line of your own output and the fingerprint of loans.csv.

If it fails

Read the first line that starts with FAIL. Fix that one, then run python labcheck.py again.

The script saysWhat it meansWhat to do
FAIL pythonPython is older than 3.12.Install Python 3.12 or newer, then repeat steps 3 and 4 with that python3.
FAIL venvThe environment is not switched on.Run source .venv/bin/activate in the lab folder.
FAIL sklearn not installedThe install did not run in this environment.Switch the environment on, then run pip install -r requirements.txt again.
FAIL sklearn 1.8.0 ...A different version is installed.Run pip install -r requirements.txt again. It replaces it with the pinned one.
FAIL loans ... missingThe data folder is empty.Run python makedata.py in the lab folder.
FAIL loans ... fingerprint 1a2b3c4dThe file differs from the author's file.You edited makedata.py or the file. Save the generator again exactly as printed and run it again.

If pip cannot find a pinned version for your system, change the four lines to the newest versions that pip offers and run the install again. The FAIL lines for the versions are then acceptable, the check on this page will not accept your last line, and a number in a later lesson can differ in its last digit. When a number differs only in the last digit, your lab is fine. When it differs in the first two digits, check your code.