AI from scratch · Reference
Cheatsheets
Every function and method called on the path: exactly the library calls you encounter in lessons and notebooks, each with a one-line example and the lesson that introduces it.
1. NumPy (import numpy as np)
| Call | What it does | Example | First used in |
|---|---|---|---|
np.array() | Creates a multi-dimensional array from lists | np.array([[1, 2], [3, 4]]) | s2-just-enough-code |
np.mean() | Arithmetic average across an axis or all elements | np.mean(errors) | s1-what-is-ml |
np.std() | Sample or population standard deviation | np.std(losses) | p2-describing-data |
np.sum() | Sums elements along an axis | np.sum(X, axis=0) | s2-just-enough-code |
np.sqrt() | Element-wise square root | np.sqrt(np.mean(err**2)) | s2-just-enough-code |
np.exp() | Natural exponential \(e^x\) | np.exp(-loss) | s2-just-enough-code |
np.log() | Natural logarithm \(\ln x\) | np.log(probs + 1e-12) | s2-just-enough-code |
np.dot() / @ | Matrix multiplication and vector inner products | A @ x or np.dot(A, B) | 01-matrices-are-moves |
np.linspace() | N evenly spaced numbers between start and stop | np.linspace(-3, 3, 100) | s2-just-enough-code |
np.arange() | Evenly spaced values within a half-open interval | np.arange(0, 10, 0.5) | s2-just-enough-code |
np.zeros() | Array of given shape filled with 0.0 | np.zeros((N, D)) | numpy-in-depth |
np.ones() | Array of given shape filled with 1.0 | np.ones_like(y) | numpy-in-depth |
np.maximum() | Element-wise max (used for ReLU) | np.maximum(0, z) | s1-what-is-ml |
np.argmin() | Index of the minimum value | np.argmin(distances, axis=1) | s2-just-enough-code |
np.argmax() | Index of the maximum value (predicted class) | np.argmax(logits, axis=-1) | s2-just-enough-code |
np.linalg.inv() | Computes the matrix inverse \(A^{-1}\) | np.linalg.inv(X.T @ X) | l1-systems-and-inverses |
np.linalg.svd() | Singular Value Decomposition \(U, \Sigma, V^T\) | U, S, Vt = np.linalg.svd(A) | l3-svd |
np.linalg.eig() | Eigenvalues and eigenvectors of square matrix | vals, vecs = np.linalg.eig(cov) | l2-eigenvectors-and-pca |
np.random.seed() | Sets PRNG state for reproducibility | np.random.seed(42) | s1-what-is-ml |
2. pandas (import pandas as pd)
| Call | What it does | Example | First used in |
|---|---|---|---|
pd.read_csv() | Loads a CSV or TSV file into a DataFrame | df = pd.read_csv('ai/data/bank.csv') | p1-probability-and-bayes |
pd.DataFrame() | Constructs a tabular DataFrame from dict or array | pd.DataFrame({'x': x, 'y': y}) | s2-just-enough-code |
df.head() | Returns the first N rows (default 5) | df.head(3) | s2-just-enough-code |
df.describe() | Computes count, mean, std, min, percentiles, max | df.describe() | s2-just-enough-code |
df.groupby() | Splits data into groups based on category columns | df.groupby('job')['deposit'].mean() | s2-just-enough-code |
df.value_counts() | Counts unique occurrences of each category | df['borough'].value_counts() | p2-describing-data |
df.dropna() | Removes rows containing missing/null values | df.dropna(subset=['target']) | features-and-leakage |
pd.get_dummies() | One-hot encodes categorical columns into binary flags | pd.get_dummies(df, drop_first=True) | pandas-and-sklearn |
pd.merge_asof() | Point-in-time join on nearest preceding timestamp | pd.merge_asof(events, features, on='time') | features-and-leakage |
df.corr() | Calculates pairwise Pearson correlation matrix | df[['age', 'balance']].corr() | p2-describing-data |
3. scikit-learn (import sklearn)
| Call | What it does | Example | First used in |
|---|---|---|---|
train_test_split() | Splits arrays/tables into train and validation sets | X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2) | p1-probability-and-bayes |
StandardScaler() | Standardizes features to zero mean and unit variance | scaler = StandardScaler().fit(X_tr) | p2-describing-data |
Pipeline() | Chains transformers with an estimator safely | pipe = Pipeline([('scale', StandardScaler()), ('clf', LogisticRegression())]) | pandas-and-sklearn |
LinearRegression() | Fits ordinary least-squares linear regression | model = LinearRegression().fit(X, y) | l1-systems-and-inverses |
LogisticRegression() | Fits regularized logistic regression for classification | clf = LogisticRegression(C=1.0).fit(X, y) | zoo-logistic |
DecisionTreeClassifier() | Recursively partitions feature space using Gini/entropy | tree = DecisionTreeClassifier(max_depth=4).fit(X, y) | 13-trees-and-boosting |
RandomForestClassifier() | Bagged ensemble of randomized decision trees | rf = RandomForestClassifier(n_estimators=100).fit(X, y) | 13-trees-and-boosting |
PCA() | Linear dimensionality reduction via covariance SVD | pca = PCA(n_components=2).fit(X) | p2-describing-data |
confusion_matrix() | Evaluates classification accuracy per class breakdown | cm = confusion_matrix(y_true, y_pred) | 12-measuring-a-model |
classification_report() | Displays precision, recall, and F1-score | print(classification_report(y_true, y_pred)) | 12-measuring-a-model |
4. PyTorch (import torch)
| Call | What it does | Example | First used in |
|---|---|---|---|
torch.tensor() | Constructs a tensor from array data | t = torch.tensor([1.0, 2.0], requires_grad=True) | s1-what-is-ml |
tensor.backward() | Computes gradients via reverse-mode autodiff | loss.backward() | training-in-pytorch |
optimizer.zero_grad() | Clears accumulated gradients before backward pass | optimizer.zero_grad() | training-in-pytorch |
optimizer.step() | Updates parameters using accumulated gradients | optimizer.step() | training-in-pytorch |
torch.no_grad() | Context manager disabling autograd engine | with torch.no_grad(): eval_model() | s1-what-is-ml |
nn.Linear() | Applies linear transformation \(y = x W^T + b\) | nn.Linear(in_features=128, out_features=10) | training-in-pytorch |
nn.ReLU() | Rectified linear unit activation \(\max(0, x)\) | nn.ReLU() | training-in-pytorch |
nn.CrossEntropyLoss() | Combines LogSoftmax and NLLLoss in one step | criterion = nn.CrossEntropyLoss() | training-in-pytorch |
optim.Adam() | Adaptive moment estimation optimizer | optim.Adam(model.parameters(), lr=1e-3) | optimizers |
tensor.to('cuda') | Transfers tensor to GPU memory | x = x.to(device) | gpus-and-scale |
Last updated