NI-ROZ / ANI-ROZ

Pracovní list: devět metod učeníWorksheet: nine learning methods

90 minut, práce ve dvojicích. Výstupem je srovnávací tabulka a krátké zdůvodnění vlastního experimentu.90 minutes, working in pairs. Submit a comparison table and a short explanation of your own experiment.

Po cvičení rozlišíte regresi, klasifikaci a shlukování. Umíte provést srovnání na stejných datech a pojmenovat jeho omezení.After the session, you can distinguish regression, classification and clustering. You can compare methods on the same data and state the limitations.

Notebooklab.pyrequirements.txtMetodika a vzorové řešeníTeacher notes and worked solution

Spuštění a dataSetup and data

Potřebujete Python 3.11 nebo novější. Balík rozbalte celý. Při instalaci knihoven potřebujete internet, samotné experimenty pak používají data dodaná se scikit-learn.Use Python 3.11 or later. Extract the whole package. Installing libraries requires internet access. The experiments then use data included with scikit-learn.

# Windows PowerShell (Python 3.11+):
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe lab.py compare --out results/run01

# Linux / macOS (Python 3.11+):
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python lab.py compare --out results/run01

Vytvoří se JSON i CSV v results/run01. Pro nový experiment zvolte nový název složky. Program odmítá přepisovat hotový běh. Volitelně otevřete notebook v Jupyteru nebo ve VS Code s rozšířením Jupyter a zvolte Python z .venv.The command creates JSON and CSV files in results/run01. Use a new output directory for a new experiment. The program refuses to overwrite an existing run. Optionally open the notebook in Jupyter or in VS Code with the Jupyter extension and select the .venv Python.

Dataset load_digits obsahuje 1 797 obrázků, deset tříd a 64 vstupních hodnot v rozsahu 0–16. Každý řádek X zde popisuje celý obrázek.load_digits contains 1,797 images, ten classes and 64 input values in the range 0–16. Each row of X describes a whole image here.

ČástSubsetPočetCountPoužitíPurpose
Train1077Učení parametrů i scaleruFit parameters and scalers
Validation360Volba metody, příznaků a nastaveníChoose method, features and settings
Test360Závěrečné posouzení předem vybrané variantyFinal evaluation of a previously selected configuration

Používáme náhodné stratifikované dělení podle obrázků. Bez ID pisatelů nemůžeme z tohoto běhu vyvozovat úspěšnost na nových pisatelích.We use a random, stratified split by image. Without writer IDs, this run cannot establish performance on unseen writers.

1. Úlohy a metody1. Tasks and methods

0–10 minut. Přiřaďte metodám jejich použití v tomto cvičení. Pak uveďte jinou úlohu z rozpoznávání pro dva vybrané algoritmy.0–10 minutes. Assign the methods to their use in this lab. Then propose another recognition task for two selected algorithms.

Zvolená metodaChosen estimatorÚloha v tomto cvikuTask in this lab
Linear regression
Logistic regression
Decision tree
Random forest
SVM (SVC)
k-NN
k-means
Gaussian naive Bayes
Gradient boosting

Logistická regrese v našem experimentu klasifikuje číslice. Regresní varianty stromů, SVM a k-NN by řešily jinou cílovou proměnnou.Logistic regression classifies digits in our experiment. Regression variants of trees, SVM and k-NN would use a different type of target.

2. Kontrola experimentu2. Audit the experiment

10–20 minut. Projděte split_indices() a classifiers() v lab.py. Najděte, kde se učí StandardScaler.10–20 minutes. Read split_indices() and classifiers() in lab.py. Find where StandardScaler learns its parameters.

3. Sedm klasifikátorů na stejném splitu3. Seven classifiers on the same split

20–35 minut. Spusťte compare. Do vlastní tabulky opište trénovací accuracy, validační accuracy a macro-F1. Dummy slouží jako kontrolní základ.20–35 minutes. Run compare. Record training accuracy, validation accuracy and macro-F1. Dummy provides a control baseline.

# Windows PowerShell:
.\.venv\Scripts\python.exe lab.py compare --out results/run01
# Linux / macOS:
.venv/bin/python lab.py compare --out results/run01

Accuracy je podíl správných rozhodnutí. Macro-F1 průměruje F1 jednotlivých tříd stejnou vahou. Balanced accuracy průměruje recall tříd. Tato čísla odpovídají různým otázkám.Accuracy is the fraction of correct decisions. Macro-F1 averages class F1 scores with equal weight. Balanced accuracy averages class recall. These numbers answer different questions.

V JSON najdete validation_confusion_matrix a validation_error_examples pro validační volbu. Časy měření závisí na počítači. Bez opakování a intervalů nepovažujte malé rozdíly za jisté pořadí metod.The JSON includes validation_confusion_matrix and validation_error_examples for the validation choice. Timings depend on the machine. Without repeated runs and uncertainty estimates, small differences do not establish a reliable ranking.

4. Popis obrázku a jednotky příznaků4. Image descriptors and feature units

35–50 minut. Před zobrazením výsledků odhadněte úspěšnost k-NN pro 1 průměr, 4 průměry kvadrantů a 64 pixelů. K zůstává 3. Výsledky jsou v feature_study.35–50 minutes. Before viewing results, predict how k-NN will perform with one mean, four quadrant means and 64 pixels. k stays at 3. Results are in feature_study.

from sklearn.datasets import load_digits
from lab import compute_features
images = load_digits().images  # n_images x 8 x 8
one = compute_features(images, "mean")       # n_images x 1
four = compute_features(images, "quadrants") # n_images x 4
full = compute_features(images, "pixels")    # n_images x 64

Pak prohlédněte scaling_study. Jeden pixel s největším rozptylem na tréninku jsme vynásobili 1 000. Nezměnili jsme třídy ani informaci, jen jednotky jedné souřadnice.Then inspect scaling_study. We multiply the pixel with the largest training variance by 1,000. Classes and information stay the same. Only one coordinate changes units.

5. Strom, random forest a boosting5. A tree, a random forest and boosting

50–60 minut. V capacity_study porovnejte hloubky 1, 3, 8 a neomezenou hloubku. Potom porovnejte strom s forest a boosting v hlavní tabulce.50–60 minutes. In capacity_study, compare depths 1, 3, 8 and unlimited depth. Then compare the tree with forest and boosting in the main table.

Random forest kombinuje stromy s randomizací vzorků a příznaků. Gradient boosting přidává malé stromy postupně podle záporného gradientu ztráty. Parametr learning_rate omezuje příspěvek dalšího kroku.A random forest combines trees using randomized samples and features. Gradient boosting adds small trees sequentially using the negative loss gradient. learning_rate limits the contribution of each new step.

Fm(x) = Fm−1(x) + η hm(x)

F je souborové skóre, h nový slabý model a η rychlost učení. Pro kvadratickou regresní ztrátu odpovídá směr obyčejným reziduím. U klasifikační log-loss se učíme jiné pseudoreziduum, nikoli rozdíl kódů tříd.F is the ensemble score, h the new weak model and η the learning rate. With squared regression loss, the direction corresponds to ordinary residuals. Classification log-loss gives a different pseudo-residual, not a difference between class IDs.

6. K-means bez názvů číslic6. K-means without digit names

60–70 minut. K-means se učí na trénovacích obrázcích bez y. K = 10 ovšem dodáváme jako známý počet shluků. Na validaci následně pro vyhodnocení využijeme její skutečné třídy.60–70 minutes. K-means learns from training images without y. We supply K = 10 as a known cluster count. We later use validation labels to evaluate the resulting partition.

cluster_ids = kmeans.predict(X_validation_scaled)
ari = adjusted_rand_score(y_validation, cluster_ids)

V clustering najdete ARI i výsledek po přejmenování shluků. Najdete také záměrně nevhodnou raw accuracy porovnávající ID shluku přímo s kódem číslice.clustering includes ARI and its value after renaming clusters. It also includes an intentionally unsuitable raw accuracy that directly compares cluster IDs with digit codes.

Pro pozdější klasifikaci by mapování shluků na třídy muselo vzniknout na trénovacích nebo validačních datech. Mapování odvozené až z testových štítků mění význam experimentu.For a later classification system, the cluster-to-class mapping would have to come from training or validation data. A mapping derived from test labels changes the meaning of the experiment.

7. Regrese a nové příznaky7. Regression and new features

70–80 minut. Sekce regression používá samostatná syntetická data: y = 0,8x² − 0,7x + šum. Porovnejte lineární regresi s příznakem x a se dvěma příznaky x, x². Oba modely zůstávají lineární v koeficientech.70–80 minutes. regression uses separate synthetic data: y = 0.8x² − 0.7x + noise. Compare linear regression using x with the same estimator using x and x². Both models stay linear in their coefficients.

MAE průměruje absolutní chybu. RMSE je odmocnina průměrné kvadratické chyby, proto silněji reaguje na velké odchylky. Menší hodnota je zde lepší.MAE averages absolute errors. RMSE is the square root of mean squared error and therefore reacts more strongly to large errors. Smaller values are better here.

8. Závěrečná volba a odevzdání8. Final choice and submission

80–90 minut. Podle validace vyberte jednu variantu. Uveďte metodu, příznaky, nastavení a důvod volby. Teprve potom spusťte final. Bez --model program použije validační volbu z comparison.json.80–90 minutes. Choose one configuration using validation. State the method, features, settings and selection reason. Only then run final. Without --model, the program uses the validation choice recorded in comparison.json.

# Windows PowerShell:
.\.venv\Scripts\python.exe lab.py final --out results/run01
# Linux / macOS:
.venv/bin/python lab.py final --out results/run01
# Optional arguments after the command:
# --model svm --reason "validation macro-F1"

Program znovu naučí vybranou variantu na tréninku a validaci a jednou vypočte testový výsledek. Před testem zapíše final-choice.json. Hotové final.json odmítá přepisovat. Tyto pojistky brání omylu, nikoli úmyslnému přístupu k veřejným datům.The program refits the selected configuration on training plus validation and evaluates the reserved test split. It records final-choice.json before evaluation and refuses to overwrite final.json. These safeguards prevent accidents, not intentional access to public data.

Odpovědi z textových polí se ukládají jen v tomto prohlížeči. Před odevzdáním je exportujte. Stránka nic neposílá na server.Text-field answers stay in this browser only. Export them before submission. This page sends nothing to a server.

Rozšíření a přenos k SegmenteruExtensions and transfer to Segmenter