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)

CallWhat it doesExampleFirst used in
np.array()Creates a multi-dimensional array from listsnp.array([[1, 2], [3, 4]])s2-just-enough-code
np.mean()Arithmetic average across an axis or all elementsnp.mean(errors)s1-what-is-ml
np.std()Sample or population standard deviationnp.std(losses)p2-describing-data
np.sum()Sums elements along an axisnp.sum(X, axis=0)s2-just-enough-code
np.sqrt()Element-wise square rootnp.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 productsA @ x or np.dot(A, B)01-matrices-are-moves
np.linspace()N evenly spaced numbers between start and stopnp.linspace(-3, 3, 100)s2-just-enough-code
np.arange()Evenly spaced values within a half-open intervalnp.arange(0, 10, 0.5)s2-just-enough-code
np.zeros()Array of given shape filled with 0.0np.zeros((N, D))numpy-in-depth
np.ones()Array of given shape filled with 1.0np.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 valuenp.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 matrixvals, vecs = np.linalg.eig(cov)l2-eigenvectors-and-pca
np.random.seed()Sets PRNG state for reproducibilitynp.random.seed(42)s1-what-is-ml

2. pandas (import pandas as pd)

CallWhat it doesExampleFirst used in
pd.read_csv()Loads a CSV or TSV file into a DataFramedf = pd.read_csv('ai/data/bank.csv')p1-probability-and-bayes
pd.DataFrame()Constructs a tabular DataFrame from dict or arraypd.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, maxdf.describe()s2-just-enough-code
df.groupby()Splits data into groups based on category columnsdf.groupby('job')['deposit'].mean()s2-just-enough-code
df.value_counts()Counts unique occurrences of each categorydf['borough'].value_counts()p2-describing-data
df.dropna()Removes rows containing missing/null valuesdf.dropna(subset=['target'])features-and-leakage
pd.get_dummies()One-hot encodes categorical columns into binary flagspd.get_dummies(df, drop_first=True)pandas-and-sklearn
pd.merge_asof()Point-in-time join on nearest preceding timestamppd.merge_asof(events, features, on='time')features-and-leakage
df.corr()Calculates pairwise Pearson correlation matrixdf[['age', 'balance']].corr()p2-describing-data

3. scikit-learn (import sklearn)

CallWhat it doesExampleFirst used in
train_test_split()Splits arrays/tables into train and validation setsX_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 variancescaler = StandardScaler().fit(X_tr)p2-describing-data
Pipeline()Chains transformers with an estimator safelypipe = Pipeline([('scale', StandardScaler()), ('clf', LogisticRegression())])pandas-and-sklearn
LinearRegression()Fits ordinary least-squares linear regressionmodel = LinearRegression().fit(X, y)l1-systems-and-inverses
LogisticRegression()Fits regularized logistic regression for classificationclf = LogisticRegression(C=1.0).fit(X, y)zoo-logistic
DecisionTreeClassifier()Recursively partitions feature space using Gini/entropytree = DecisionTreeClassifier(max_depth=4).fit(X, y)13-trees-and-boosting
RandomForestClassifier()Bagged ensemble of randomized decision treesrf = RandomForestClassifier(n_estimators=100).fit(X, y)13-trees-and-boosting
PCA()Linear dimensionality reduction via covariance SVDpca = PCA(n_components=2).fit(X)p2-describing-data
confusion_matrix()Evaluates classification accuracy per class breakdowncm = confusion_matrix(y_true, y_pred)12-measuring-a-model
classification_report()Displays precision, recall, and F1-scoreprint(classification_report(y_true, y_pred))12-measuring-a-model

4. PyTorch (import torch)

CallWhat it doesExampleFirst used in
torch.tensor()Constructs a tensor from array datat = torch.tensor([1.0, 2.0], requires_grad=True)s1-what-is-ml
tensor.backward()Computes gradients via reverse-mode autodiffloss.backward()training-in-pytorch
optimizer.zero_grad()Clears accumulated gradients before backward passoptimizer.zero_grad()training-in-pytorch
optimizer.step()Updates parameters using accumulated gradientsoptimizer.step()training-in-pytorch
torch.no_grad()Context manager disabling autograd enginewith 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 stepcriterion = nn.CrossEntropyLoss()training-in-pytorch
optim.Adam()Adaptive moment estimation optimizeroptim.Adam(model.parameters(), lr=1e-3)optimizers
tensor.to('cuda')Transfers tensor to GPU memoryx = x.to(device)gpus-and-scale

Last updated