How AI works cheat sheet
Train a first model
| Task | Command |
|---|---|
| Make an environment | python3 -m venv .venv |
| Activate it | source .venv/bin/activate |
| Install the pinned libraries | pip install -r requirements.txt |
| Record the versions | pip freeze > my-versions.txt |
| Train on examples | model = LogisticRegression() then model.fit(X, y) |
| Predict a label | model.predict([sample])[0] |
| Predict a chance | model.predict_proba([sample])[0][1] |
| Read the parameters | model.coef_.round(3) and model.intercept_.round(3) |
Load and split data
| Task | Command |
|---|---|
| Load the digits | X, y = load_digits(return_X_y=True) |
| Check the shape | X.shape |
| Count the classes | np.bincount(y) |
| Split the data | train_test_split(X, y, test_size=0.25, random_state=42, stratify=y) |
| Train to the end | LogisticRegression(max_iter=2000).fit(X_train, y_train) |
| Score on unseen data | model.score(X_test, y_test) |
Compare the kinds of training (lessons 4 and 5)
| Task | Command |
|---|---|
| Group points with no labels | KMeans(n_clusters=3, n_init=10, random_state=0).fit(X) |
| Count the points in each group | np.bincount(km.labels_) |
| Make seeded groups of points | make_blobs(n_samples=[300, 150, 50], centers=centers, random_state=7) |
| Draw seeded random numbers | rng = random.Random(11) then rng.random() |
| Learn from a reward | Keep the average reward of each action and mostly pick the best |
| Train in steps | SGDClassifier(loss="log_loss", random_state=0) |
| Fine-tune a trained model | tuned = copy.deepcopy(base) then tuned.partial_fit(X_new, y_new) |
| Pick rows with certain labels | np.isin(y, [3, 8]) |
| Shuffle the row numbers | order = np.random.default_rng(3).permutation(n) |
| Cut rows into sites | np.split(order, [600, 1000]) or np.array_split(order, 4) |
| Average the weights of sites | np.average([m.coef_ for m in models], axis=0, weights=sizes) |
| Write a note file | cat > vendor-questions.txt <<'EOT', the lines, then EOT |
Measure a model
| Task | Command |
|---|---|
| Score the answers | accuracy_score(y_test, pred) |
| Count every mistake | confusion_matrix(y_test, pred) |
| Read each class | classification_report(y_test, pred, digits=3) |
| Find real alerts | Precision is TP / (TP + FP) |
| Find real attacks | Recall is TP / (TP + FN) |
| Score a rare class | recall_score(y_true, pred) and precision_score(y_true, pred, zero_division=0) |
Spot overfitting
| Task | Command |
|---|---|
| Limit a tree | DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train) |
| Count its leaves | tree.get_n_leaves() |
| See the sign | A high train score and a much lower test score |
| Cut a validation set | train_test_split(X_rest, noisy, test_size=0.25, random_state=42) |
| Repeat the split | cross_val_score(model, texts, labels, cv=5) |
Train a neural network
| Task | Command |
|---|---|
| Scale the pixels | X = X / 16.0 |
| Build the network | MLPClassifier(hidden_layer_sizes=(64,), max_iter=300, tol=1e-3, random_state=0) |
| Read the loss | net.loss_curve_ |
| Count the epochs | net.n_iter_ |
| Count the parameters | sum(w.size for w in net.coefs_) + sum(b.size for b in net.intercepts_) |
Search text by meaning
| Task | Command |
|---|---|
| Make word vectors | TfidfVectorizer(stop_words="english") then tfidf.fit_transform(texts) |
| Compress them | TruncatedSVD(n_components=8, random_state=0) then svd.fit_transform(A) |
| Embed a query | svd.transform(tfidf.transform([query])) |
| Compare with the texts | cosine_similarity(q, V)[0] |
| Rank the nearest | np.argsort(-sims)[:k] |
Clean a feed (lesson 10)
| Task | Command |
|---|---|
| Load a table (structured) | list(csv.DictReader(f)) |
| Load JSON lines (semi-structured) | [json.loads(line) for line in f] |
| Load free text (unstructured) | open("feed_c.dat").read() |
| Make case and spaces equal | " ".join(text.lower().split()) |
| Clean a feed | kept, dropped = clean(rows) |
| Make label-keeping variants | augment(kept) |
Record the history of data (lesson 11)
| Task | Command |
|---|---|
| Hash a file in Python | hashlib.sha256(open(path, "rb").read()).hexdigest() |
| Write a lineage record | python lineage.py write lineage.json feed.csv clean.csv |
| Find a changed file | python lineage.py check lineage.json |
| Plant a canary row | echo '9001,ok,the violet heron files its report at dawn' >> shared.csv |
| Look for the canary in a suspect file | grep -ic "violet heron" suspect.csv |
Build a text classifier (lesson 12)
| Task | Command |
|---|---|
| Chain the steps | Pipeline([("tfidf", TfidfVectorizer(lowercase=True, ngram_range=(1, 2))), ("clf", LogisticRegression(C=10, max_iter=1000))]) |
| Read the top words | model["tfidf"].get_feature_names_out() and model["clf"].coef_[0] |
| Get the chances | model.predict_proba(tests)[:, 1] |
| Save the model | joblib.dump(model, "phish.joblib") |
| Load the model | joblib.load("phish.joblib") |
| Fingerprint the file | sha256sum phish.joblib > phish.sha256 |
| Check the fingerprint | sha256sum -c phish.sha256 |
| Write a model card | python model_card.py |
Judge a detector (lesson 13)
| Task | Command |
|---|---|
| Read a CSV of numbers | np.loadtxt("logins.csv", delimiter=",", skiprows=1) |
| Use a cut-off of 0.2 | (model.predict_proba(X_test)[:, 1] >= 0.2).astype(int) |
| Make a rare class count more | LogisticRegression(max_iter=1000, class_weight="balanced") |
Safety habits
- Report the seed, the split and the library versions with every score.
- Ask of every kind of training what teaches the model, and who controls that. Check the old tests again after fine-tuning.
- Never choose a setting with the test set. Use a validation set, and split logs by time.
- Read the result for each class, and state the base rate. An average can hide a failure.
- Treat training data as part of the system. Label flipping poisons a model.
- Treat a model file as a program. Check its SHA-256 hash (
sha256sum -c) beforejoblib.load. - Apply access control when a RAG system retrieves text, and protect a vector store like the documents.
- Clean data before you train, hash it after, and keep the lineage record where the data's writers cannot change it. A hash proves that data is unchanged, not that it is right.
- Pick augmentation rules from the training rows, and never augment the test data. Give each partner a copy with its own canary row, and keep the canary secret.