### Run K-Means Example Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/.test.ipynb Demonstrates initializing, fitting, and predicting with the KMeans class on synthetic data. ```python x1 = np.random.randn(5,2) + 5 x2 = np.random.randn(5,2) - 5 X = np.concatenate([x1,x2], axis=0) kmeans = KMeans(k=2) kmeans.fit(X) clusters = kmeans.predict(X) print(clusters) print(kmeans.centroids) ``` -------------------------------- ### Training and Testing Example Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/feedforward.ipynb Example usage of the TwoLayerNet class to train on a simple XOR-like dataset. ```python # Generate a toy dataset X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) y = np.array([0, 1, 1, 0]) # Initialize a neural network net = TwoLayerNet(input_size=2, hidden_size=10, output_size=2) # Train the neural network net.train(X, y, num_epochs=1000) # Test the neural network probs = net.forward(X) predictions = np.argmax(probs, axis=1) print("Predictions: ", predictions) ``` -------------------------------- ### Perceptron Usage Example Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/perceptron.ipynb Demonstrates how to instantiate the Perceptron class, train it on sample data, and perform predictions. ```python X = np.array([[2.0, 1.0], [3.0, 4.0], [4.0, 2.0], [3.0, 1.0]]) y = np.array([-1, 1, 1, -1]) perceptron = Perceptron() perceptron.fit(X, y) new_X = np.array([[5.0, 2.0], [1.0, 3.0]]) perceptron.predict(new_X) ``` -------------------------------- ### Training output Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/linear_regression_md.ipynb Example output showing the cost reduction over iterations. ```text 34.3004759224227 4.265835757989014 4.052505749060854 3.8807845759072968 3.7422281683979812 3.6303399157863434 3.5398708528835554 3.4665749938168915 3.4070257924246747 3.3584711183863862 ``` -------------------------------- ### Vectorized K-means output Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_means_2.ipynb Example output from the vectorized K-means execution. ```text Output: 1517.502248752696 1218.9100430186547 1217.3621376590977 0.09020209312438965 seconds ``` -------------------------------- ### Train and Evaluate SVM with Blobs Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/svm.ipynb Example usage of the SVM class on a synthetic blobs dataset. ```python # Example usage from sklearn import datasets from sklearn.model_selection import train_test_split X, y = datasets.make_blobs(n_samples=100, centers=2, random_state=42) y = np.where(y == 0, -1, 1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) svm = SVM() svm.fit(X_train, y_train) y_pred = svm.predict(X_test) # Evaluate model accuracy = accuracy_score(y_test, y_pred) print("Accuracy:", accuracy) ``` -------------------------------- ### Iterative K-means output Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_means_2.ipynb Example output from the iterative K-means execution. ```text Output: 1517.502248752696 1218.91004301866 1217.362137659097 0.8816308975219727 seconds ``` -------------------------------- ### Train and Evaluate SVM with Classification Data Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/svm.ipynb Example usage of the SVM class on a synthetic classification dataset. ```python # Generate data X, y = make_classification(n_features=5, n_samples=100, n_informative=5, n_redundant=0, n_classes=2, random_state=1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) # Initialize SVM model svm = SVM() # Train model svm.fit(X_train, y_train) # Make predictions y_pred = svm.predict(X_test) # Evaluate model accuracy = accuracy_score(y_test, y_pred) print("Accuracy:", accuracy) ``` -------------------------------- ### Pad Sentences for Windowing Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Defines a function to add padding tokens to the start and end of a sentence to support window-based classification. ```python def pad_sentence_for_window(sentence, window_size, pad_token=""): return [pad_token]*window_size + sentence + [pad_token]*window_size ``` -------------------------------- ### Initializing parameters and data Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/linear_regression_md.ipynb Setting up dimensions and random matrices for features, weights, and targets. ```python n, k, p=100, 8, 3 X=np.random.random([n,k]) W=np.random.random([k,p]) Y=np.random.random([n,p]) max_itr=1000 alpha=0.0001 Lambda=0.01 ``` -------------------------------- ### Import required libraries Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_nearest_neighbors.ipynb Initializes the environment with NumPy, time, and Counter for data manipulation and performance tracking. ```python import numpy as np import time from collections import Counter ``` -------------------------------- ### Importing dependencies Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_means_2.ipynb Initializes the environment with NumPy and time modules. ```python import numpy as np import time ``` -------------------------------- ### Configure Model and Optimizer Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Sets hyperparameters and initializes the model and SGD optimizer. ```python config = {"batch_size": 4, "half_window": 2, "embed_dim": 25, "hidden_dim": 25, "num_classes": 2, "freeze_embeddings": False, } learning_rate = .0002 num_epochs = 10000 model = SoftmaxWordWindowClassifier(config, len(word_2_id)) optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) ``` -------------------------------- ### Run ML algorithm reference tests Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/ml-coding.md Execute the test suite for ML algorithm implementations from the repository root using uv. ```bash uv run --with numpy python src/MLC/solutions/test_ml_algorithms.py ``` -------------------------------- ### Initialize dummy input tensor Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Sets up a dummy batch of sentences with padding for testing window construction. ```python dummy_input = torch.zeros(2, 8).long() dummy_input[:,2:-2] = torch.arange(1,9).view(2,4) pp.pprint(dummy_input) ``` -------------------------------- ### Initialize PyTorch Environment Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Imports necessary libraries for data manipulation and neural network construction. ```python import pprint import torch import torch.nn as nn pp = pprint.PrettyPrinter() ``` -------------------------------- ### Create Arrays Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/numpy_practice.ipynb Demonstrates creating arrays from lists and converting data types. ```python a = [1, 2, 3] x = np.array(a) x = np.asarray(a) x ``` ```python x.tolist() ``` ```python x.astype(np.float32) ``` -------------------------------- ### Initialize Data and Weights Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/logistic_regression_md.ipynb Generates random input features, weight matrices, and one-hot encoded target labels. ```python X=np.random.random([n,k]) W=np.random.random([k,p]) y=np.random.randint(p, size=(1,n)) Y=np.zeros((n,p)) Y[np.arange(n), y]=1 max_itr=5000 alpha=0.01 Lambda=0.01 ``` -------------------------------- ### Standard PyTorch Training Loop Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/pytorch-ml-coding.md Demonstrates the essential steps for a training loop including device transfer, gradient clearing, forward pass, loss computation, and parameter updates. ```python model.train() for x, y in loader: x, y = x.to(device), y.to(device) optimizer.zero_grad(set_to_none=True) logits = model(x) loss = loss_fn(logits, y) loss.backward() optimizer.step() ``` -------------------------------- ### Broadcasting and Slicing Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/numpy_practice.ipynb Demonstrates how array slices are views and how to perform broadcasting assignments. ```python a = np.zeros(10) a[5:8] = 5 # note we can't do this with list a ``` ```python suba = a[:3] suba[:] = 2 suba ``` ```python a # note that suba is not a copy, just points to a slice of a ``` ```python suba = np.copy(a[:3]) suba ``` ```python m = np.zeros((4,4)) m[1] = 2 m ``` ```python # fancy indexing m[[1,3]] ``` -------------------------------- ### Access Instance Data Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Retrieves and prints a sample sentence from the training set. ```python instance = train_sents[0] print(instance) ``` -------------------------------- ### Review and Debug Evaluation Logic Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/pytorch-ml-coding.md Demonstrates common pitfalls in evaluation loops and provides a corrected, production-ready implementation. ```python def evaluate(model, loader): model.train() losses = [] for x, y in loader: prediction = model(x) loss = torch.nn.CrossEntropyLoss()(prediction, y) losses.append(loss) return torch.tensor(losses).mean().item() ``` ```python @torch.inference_mode() def evaluate(model, loader, device): loss_fn = torch.nn.CrossEntropyLoss() previous_mode = model.training model.eval() total_loss = 0.0 total_examples = 0 try: for x, y in loader: x, y = x.to(device), y.to(device) loss = loss_fn(model(x), y) batch_size = y.shape[0] total_loss += loss.item() * batch_size total_examples += batch_size finally: model.train(previous_mode) if total_examples == 0: raise ValueError("Cannot evaluate an empty loader") return total_loss / total_examples ``` -------------------------------- ### Execute Training Loop Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Runs the training process for a specified number of epochs and tracks loss. ```python losses = [] for epoch in range(num_epochs): epoch_loss = train_epoch(loss_function, optimizer, model, train_loader) if epoch % 100 == 0: losses.append(epoch_loss) print(losses) ``` -------------------------------- ### Importing dependencies Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/linear_regression_md.ipynb Initial imports required for numerical operations and random data generation. ```python import numpy as np import random ``` -------------------------------- ### Train and Evaluate MultiLayerNet Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/feedforward.ipynb Demonstrates data preparation, model instantiation, training, and evaluation using the MultiLayerNet class. ```python import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split # Generate a toy classification dataset X, y = make_classification(n_samples=1000, n_features=10, n_classes=2, random_state=42) # Split the dataset into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Normalize the input data mean = X_train.mean(axis=0) std = X_train.std(axis=0) X_train = (X_train - mean) / std X_test = (X_test - mean) / std # Define the mean squared error loss function def mse_loss(output, y): return np.mean((output - y) ** 2) # Create a multi-layer neural network with 2 hidden layers net = MultiLayerNet(input_size=10, hidden_sizes=[20, 10], output_size=1, activation_function=Sigmoid(), loss_function=mse_loss, reg_lambda=0.01) # Train the network for 1000 epochs net.train(X_train, y_train, num_epochs=1000, learning_rate=0.01) # Evaluate the trained network on the test set output = net.forward(X_test) predicted_classes = np.round(output) accuracy = np.mean(predicted_classes == y_test) print(f"Test accuracy: {accuracy}") ``` -------------------------------- ### Initialize DataLoader with partial function Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Configures a DataLoader using a partially applied collate function. ```python # Shuffle True is good practice for train loaders. # Use functools.partial to construct a partially populated collate function example_loader = DataLoader(list(zip(train_sents, train_labels)), batch_size=2, shuffle=True, collate_fn=partial(my_collate, window_size=2, word_2_id=word_2_id)) ``` -------------------------------- ### Initialize Data Loaders Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Creates PyTorch DataLoaders for training and testing datasets using a custom collate function. ```python train_loader = torch.utils.data.DataLoader(list(zip(train_sents, train_labels)), batch_size=2, shuffle=True, collate_fn=partial(my_collate, window_size=2, word_2_id=word_2_id)) ``` ```python test_loader = torch.utils.data.DataLoader(list(zip(test_sents, test_labels)), batch_size=1, shuffle=False, collate_fn=partial(my_collate, window_size=2, word_2_id=word_2_id)) ``` -------------------------------- ### Check Model Device Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/pytorch-ml-coding.md Inspects the device of the first parameter in the model to verify GPU placement. ```python next(model.parameters()).device ``` -------------------------------- ### Verify Padding with Vocabulary Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Iterates through training sentences, applies padding, converts to indices, and prints the resulting vocabulary words. ```python for sent in train_sents: tok_idxs = convert_tokens_to_inds(pad_sentence_for_window(sent, window_size), word_2_id) print([id_2_word[idx] for idx in tok_idxs]) ``` -------------------------------- ### Initialize Special Arrays Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/numpy_practice.ipynb Creates arrays filled with zeros, ones, identity matrices, or linearly spaced values. ```python np.zeros(3) np.zeros((3,3)) ``` ```python np.ones(3) np.ones((3,3)) ``` ```python np.eye(3) ``` ```python np.linspace(0,10,3) # 3 points, from 0 to 10, inclusive np.linspace(0,7,3) ``` -------------------------------- ### Define Training Data Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Sets up training sentences and corresponding location labels, ensuring lengths match. ```python train_sents = [s.lower().split() for s in ["we 'll always have Paris", "I live in Germany", "He comes from Denmark", "The capital of Denmark is Copenhagen"]] train_labels = [[0, 0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1, 0, 1]] assert all([len(train_sents[i]) == len(train_labels[i]) for i in range(len(train_sents))]) ``` -------------------------------- ### Training and Predicting with Logistic Regression Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/logistic_regression.ipynb Demonstrates how to initialize, train, and perform inference using the LogisticRegression class on a sample dataset. ```python # create sample dataset X = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]) y = np.array([0, 0, 1, 1, 1]) # initialize logistic regression model lr = LogisticRegression(learning_rate=0.01, n_iters=1000, regularization='l2', reg_strength=0.1, batch_size=2) # train model on sample dataset lr.fit(X, y) # make predictions on new data X_new = np.array([[6, 7], [7, 8]]) y_pred = lr.predict(X_new) print(y_pred) # [1, 1] ``` -------------------------------- ### Implement Training and Evaluation Loops in PyTorch Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/pytorch-ml-coding.md Provides a robust implementation for training one epoch and performing an evaluation pass with proper device placement and gradient management. ```python import torch def train_one_epoch(model, dataloader, optimizer, loss_fn, device): model.train() total_loss = 0.0 total_examples = 0 for inputs, targets in dataloader: inputs = inputs.to(device) targets = targets.to(device) optimizer.zero_grad(set_to_none=True) outputs = model(inputs) loss = loss_fn(outputs, targets) loss.backward() optimizer.step() batch_size = targets.shape[0] total_loss += loss.detach().item() * batch_size total_examples += batch_size if total_examples == 0: raise ValueError("Cannot train on an empty dataloader") return {"loss": total_loss / total_examples} @torch.inference_mode() def evaluate(model, dataloader, loss_fn, device): previous_mode = model.training model.eval() total_loss = 0.0 total_examples = 0 predictions = [] targets_out = [] try: for inputs, targets in dataloader: inputs = inputs.to(device) targets = targets.to(device) outputs = model(inputs) loss = loss_fn(outputs, targets) batch_size = targets.shape[0] total_loss += loss.item() * batch_size total_examples += batch_size predictions.append(outputs.detach().cpu()) targets_out.append(targets.detach().cpu()) finally: model.train(previous_mode) if total_examples == 0: raise ValueError("Cannot evaluate an empty dataloader") return { "loss": total_loss / total_examples, "predictions": torch.cat(predictions), "targets": torch.cat(targets_out), } ``` -------------------------------- ### Xavier Weight Initialization Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/feedforward.ipynb Initializes weights using a Gaussian distribution scaled by the square root of the input or hidden size to stabilize gradients. ```python # Xavier initialization self.params['W1'] = np.random.randn(input_size, hidden_size) / np.sqrt(input_size) self.params['W2'] = np.random.randn(hidden_size, output_size) / np.sqrt(hidden_size) ``` -------------------------------- ### Save and load a trained model Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/pytorch-ml-coding.md Saves model state, optimizer state, and epoch information to a checkpoint file. Reconstruct the architecture before loading and call eval() for inference. ```python torch.save( { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "epoch": epoch, }, "checkpoint.pt", ) checkpoint = torch.load("checkpoint.pt", map_location=device, weights_only=True) model.load_state_dict(checkpoint["model"]) optimizer.load_state_dict(checkpoint["optimizer"]) ``` -------------------------------- ### Array Initialization and Manipulation Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/numpy_practice.ipynb Initialize random arrays and perform list comprehension operations on NumPy array elements. ```python mu = np.random.rand(5,2) x = np.random.rand(2) ``` ```python [-mu[i[0]] for i in enumerate(mu)] ``` -------------------------------- ### Iterate through batched data Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Demonstrates iterating over the DataLoader to retrieve batched inputs, labels, and lengths. ```python for batched_input, batched_labels, batch_lengths in example_loader: pp.pprint(("inputs", batched_input, batched_input.size())) pp.pprint(("labels", batched_labels, batched_labels.size())) pp.pprint(batch_lengths) break ``` -------------------------------- ### Import NumPy Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/numpy_practice.ipynb Standard import for the NumPy library. ```python import numpy as np ``` -------------------------------- ### Defining parameters Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_means_2.ipynb Sets the number of samples, dimensions, clusters, and maximum iterations. ```python n, d, k=1000, 20, 4 max_itr=100 ``` -------------------------------- ### Initialize LongTensor for labels Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Creates a LongTensor from a raw label instance. ```python l = torch.LongTensor(train_labels[0]) pp.pprint(("raw train label instance", l)) print(l.size()) ``` -------------------------------- ### Logistic Regression Model Training and Prediction Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/logistic_regression.ipynb Demonstrates initializing, training, and predicting with the LogisticRegression class using sample data. ```python # create sample dataset X = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]) y = np.array([0, 0, 1, 1, 1]) # initialize logistic regression model lr = LogisticRegression() # train model on sample dataset lr.fit(X, y) # make predictions on new data X_new = np.array([[6, 7], [7, 8]]) y_pred = lr.predict(X_new) print(y_pred) # [1, 1] ``` -------------------------------- ### Create Vocabulary Mapping Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Defines the vocabulary list and creates a dictionary mapping words to unique integer indices. ```python id_2_word = ["", "", "we", "always", "have", "paris", "i", "live", "in", "germany", "he", "comes", "from", "denmark", "the", "of", "is", "copenhagen"] word_2_id = {w:i for i,w in enumerate(id_2_word)} ``` -------------------------------- ### Implement K-Nearest Neighbors Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/.test.ipynb A class-based implementation of the KNN algorithm using Counter for majority voting. ```python import numpy as np from collections import Counter class KNN: def __init__(self, k): self.k = k def fit(self, X, y): self.X = X self.y = y def predict(self, X_test): y_pred = [] for x in X_test: dist = np.linalg.norm(x - self.X, axis=1) knn_idcs = np.argsort(dist)[:self.k] knn_labels = self.y[knn_idcs] label = Counter(knn_labels).most_common(1)[0][0] y_pred.append(label) return np.array(y_pred) from sklearn.model_selection import train_test_split x1 = np.random.randn(50,2) + 1 x2 = np.random.randn(50,2) - 1 X = np.concatenate([x1, x2], axis=0) y = np.concatenate([np.ones(50), np.zeros(50)]) print(X.shape, y.shape) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) knn = KNN(k=5) knn.fit(X_train, y_train) y_pred = knn.predict(X_test) print(y_pred) print(y_test) ``` -------------------------------- ### K-means Clustering Implementation Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/numpy_practice.ipynb Draft implementation of K-means clustering including data generation and iterative center updates. ```python ## Kmeans ``` ```python x1 = np.add(np.random.randn(10,2), 5) x2 = np.add(np.random.randn(10,2), -5) X = np.concatenate([x1,x2], axis=0) mu, clusters = kmeans(X,2) ``` ```python import random def dist(): pass def assign_clusters(X, mu): def kmeans(X,k): mu = random.sample(X,k) it = 1 max_it = 100 while it < max_it: # assign clusters to centers clusters = assign_clusters(X, mu) # calculate new centers mu = calculate_centers(mu, clusters) return mu, clusters ``` -------------------------------- ### Apply and Verify Index Conversion Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Converts tokens to indices and verifies the mapping by reversing the process. ```python token_inds = convert_tokens_to_inds(instance, word_2_id) pp.pprint(token_inds) ``` ```python print([id_2_word[tok_idx] for tok_idx in token_inds]) ``` -------------------------------- ### Implement a Stateful Feature Standardizer Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/pytorch-ml-coding.md Uses nn.Module buffers to store training statistics, ensuring they are saved in the state_dict and move correctly with the model. Requires fitting on training data before inference to prevent validation leakage. ```python import torch from torch import nn class FeatureStandardizer(nn.Module): def __init__(self, num_features: int, eps: float = 1e-6): super().__init__() self.eps = eps self.register_buffer("mean", torch.zeros(num_features)) self.register_buffer("scale", torch.ones(num_features)) self.register_buffer("is_fitted", torch.tensor(False)) @torch.no_grad() def fit(self, x: torch.Tensor) -> "FeatureStandardizer": if x.ndim != 2 or x.shape[1] != self.mean.numel(): raise ValueError("Expected [batch, num_features] with the configured width") # Accumulate statistics in float32 for low-precision input. work = x.float() if x.dtype in (torch.float16, torch.bfloat16) else x work = torch.nan_to_num(work) mean = work.mean(dim=0) scale = work.std(dim=0, unbiased=False).clamp_min(self.eps) self.mean.copy_(mean.to(device=self.mean.device, dtype=self.mean.dtype)) self.scale.copy_(scale.to(device=self.scale.device, dtype=self.scale.dtype)) self.is_fitted.fill_(True) return self def forward(self, x: torch.Tensor) -> torch.Tensor: if not bool(self.is_fitted): raise RuntimeError("FeatureStandardizer must be fitted before use") clean = torch.nan_to_num(x) return (clean - self.mean.to(dtype=clean.dtype)) / self.scale.to(dtype=clean.dtype) ``` -------------------------------- ### Backward Propagation Mathematical Steps Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/feedforward.ipynb Gradient calculations for updating weights and biases during backpropagation. ```python delta3 = probs delta3[range(len(X)), y] -= 1 dW2 = A1.T.dot(delta3) db2 = sum(delta3) delta2 = delta3.dot(W2.T) * (A1 > 0) dW1 = X.T.dot(delta2) db1 = sum(delta2) ``` -------------------------------- ### Define Test Data Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Sets up test sentences and labels for validation. ```python test_sents = [s.lower().split() for s in ["She comes from Paris"]] test_labels = [[0, 0, 0, 1]] assert all([len(test_sents[i]) == len(test_labels[i]) for i in range(len(test_sents))]) ``` -------------------------------- ### Optimized K-Means Clustering in Python Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_means.ipynb A class-based implementation of K-Means that utilizes random initialization, vectorized distance calculations, and early stopping to improve convergence and efficiency. ```python import numpy as np class KMeans: def __init__(self, k=3, max_iters=100, tol=1e-4): self.k = k self.max_iters = max_iters self.tol = tol def fit(self, X): # Initialize centroids randomly self.centroids = X[np.random.choice(X.shape[0], self.k, replace=False)] # Iterate until convergence or maximum number of iterations is reached for i in range(self.max_iters): # Assign each data point to the closest centroid distances = np.linalg.norm(X[:, np.newaxis] - self.centroids, axis=2) cluster_assignments = np.argmin(distances, axis=1) # Update the centroids based on the new cluster assignments new_centroids = np.array([np.mean(X[np.where(cluster_assignments == j)], axis=0) for j in range(self.k)]) # Check for convergence if np.linalg.norm(new_centroids - self.centroids) < self.tol: break self.centroids = new_centroids def predict(self, X): # Assign each data point to the closest centroid distances = np.linalg.norm(X[:, np.newaxis] - self.centroids, axis=2) cluster_assignments = np.argmin(distances, axis=1) return cluster_assignments ``` -------------------------------- ### Test Padding Function Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Applies padding to a sample sentence and verifies the result. ```python window_size = 2 instance = pad_sentence_for_window(train_sents[0], window_size) print(instance) ``` -------------------------------- ### Vectorize windows using Tensor.unfold Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Uses the PyTorch unfold operation to efficiently extract sliding windows from the input tensor. ```python dummy_input.unfold(1, 2*2+1, 1) ``` -------------------------------- ### Implement K-Means Clustering Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/.test.ipynb A class-based implementation of the K-Means algorithm using NumPy for distance calculations and centroid updates. ```python import numpy as np class KMeans: def __init__(self, k, max_it=100): self.k = k self.max_it = max_it # self.centroids = None def fit(self, X): # init centroids self.centroids = X[np.random.choice(X.shape[0], size=self.k, replace=False)] # for each it for i in range(self.max_it): # assign points to closest centroid # clusters = [] # for j in range(len(X)): # dist = np.linalg.norm(X[j] - self.centroids, axis=1) # clusters.append(np.argmin(dist)) dist = np.linalg.norm(X[:, np.newaxis] - self.centroids, axis=2) clusters = np.argmin(dist, axis=1) # update centroids (mean of clusters) for k in range(self.k): cluster_X = X[np.where(np.array(clusters) == k)] if len(cluster_X) > 0 : self.centroids[k] = np.mean(cluster_X, axis=0) # check convergence / termination if i > 0 and np.array_equal(self.centroids, pre_centroids): break pre_centroids = self.centroids self.clusters = clusters def predict(self, X): clusters = [] for j in range(len(X)): dist = np.linalg.norm(X[j] - self.centroids, axis=1) clusters.append(np.argmin(dist)) return clusters ``` -------------------------------- ### Fitting the model Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/linear_regression_md.ipynb Iterative training function using gradient descent to update weights. ```python def fit(W, X, Y, alpha, Lambda, max_itr): for i in range(max_itr): Y_est=F(X,W) E, c= cost(Y_est, Y, W, Lambda) Wg=gradient(E, X, W, Lambda) W=W - alpha * Wg if i%100==0: print(c) return W ``` -------------------------------- ### Generating random data Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_means_2.ipynb Creates a random dataset of size n by d. ```python X=np.random.random((n,d)) ``` -------------------------------- ### Perform tensor slicing, indexing, concatenation, and transposition Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/pytorch-ml-coding.md Demonstrates basic tensor manipulation operations. Note that transposed tensors may be noncontiguous in memory. ```python x = torch.arange(12).reshape(3, 4) first_two_columns = x[:, :2] selected_rows = x[torch.tensor([0, 2])] stacked_rows = torch.cat([x, x], dim=0) transposed = x.transpose(0, 1) ``` -------------------------------- ### Train and Evaluate KNN Classifier Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/knn.ipynb Demonstrates training the custom KNN model on the Iris dataset and calculating accuracy. ```python from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # Load the iris dataset iris = load_iris() # Split the data into training and test sets X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42) # Create a KNN classifier with k=5 and euclidean distance knn = KNN(k=5, distance='euclidean') # Train the classifier on the training data knn.fit(X_train, y_train) # Make predictions on the test data y_pred = knn.predict(X_test) # Compute the accuracy of the classifier accuracy = accuracy_score(y_test, y_pred) print(f"Accuracy: {accuracy}") ``` ```text Output: Accuracy: 1.0 ``` -------------------------------- ### Define dataset parameters Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_nearest_neighbors.ipynb Sets the dimensions for the synthetic dataset and the number of neighbors. ```python n, d, m=500, 20, 4 k=5 ``` -------------------------------- ### Mini-batch Training Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/feedforward.ipynb Updates model parameters using random subsets of the training data to improve computational efficiency. ```python # Mini-batch training batch_size = 64 num_batches = len(X) // batch_size for epoch in range(num_epochs): for i in range(num_batches): # Select a random batch of data batch_mask = np.random.choice(len(X), batch_size) X_batch = X[batch_mask] y_batch = y[batch_mask] # Forward and backward propagation using the batch data # ... ``` -------------------------------- ### Forward Propagation Mathematical Steps Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/feedforward.ipynb Basic mathematical operations for a single forward pass through a two-layer network. ```python Z1 = X.W1 + b1 A1 = ReLU(Z1) Z2 = A1.W2 + b2 exp_scores = exp(Z2) probs = exp_scores / sum(exp_scores) ``` -------------------------------- ### Perceptron Class Implementation Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/perceptron.ipynb A Python class implementing the perceptron algorithm with methods for training and prediction. ```python import numpy as np class Perceptron: def __init__(self, lr=0.01, n_iter=100): self.lr = lr self.n_iter = n_iter def fit(self, X, y): self.weights = np.zeros(1 + X.shape[1]) self.errors = [] for _ in range(self.n_iter): errors = 0 for xi, target in zip(X, y): update = self.lr * (target - self.predict(xi)) self.weights[1:] += update * xi self.weights[0] += update errors += int(update != 0.0) self.errors.append(errors) return self def net_input(self, X): return np.dot(X, self.weights[1:]) + self.weights[0] def predict(self, X): return np.where(self.net_input(X) >= 0.0, 1, -1) ``` -------------------------------- ### Linear Regression Skeleton Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/.test.ipynb A template class for implementing Linear Regression. ```python class LinearRegression: def __init__(self): self.m = None self.b = None def fit(self, X, y): def predict(self, X): pass ``` -------------------------------- ### Implement a DataLoader for a CSV dataset Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/pytorch-ml-coding.md Uses a custom Dataset class to load CSV data into tensors. For large files, consider preprocessing to a columnar format or using an iterable pipeline to avoid memory issues. ```python import pandas as pd import torch from torch.utils.data import DataLoader, Dataset class CsvDataset(Dataset): def __init__(self, path: str, feature_cols: list[str], target_col: str): frame = pd.read_csv(path) self.x = torch.tensor(frame[feature_cols].to_numpy(), dtype=torch.float32) self.y = torch.tensor(frame[target_col].to_numpy(), dtype=torch.long) def __len__(self) -> int: return self.y.shape[0] def __getitem__(self, index: int): return self.x[index], self.y[index] loader = DataLoader( CsvDataset("train.csv", ["f1", "f2"], "label"), batch_size=64, shuffle=True, num_workers=2, ) ``` -------------------------------- ### Handling bias and executing training Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/linear_regression_md.ipynb Concatenating a bias column to the feature matrix and running the fit function. ```python X=np.concatenate( (X, np.ones((n,1))), axis=1 ) W=np.concatenate( (W, np.random.random((1,p)) ), axis=0 ) W = fit(W, X, Y, alpha, Lambda, max_itr) ``` -------------------------------- ### Execute K-Means Clustering on Synthetic Data Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_means.ipynb Generates synthetic data and applies the KMeans class to perform clustering and retrieve centroids. ```python x1 = np.random.randn(5,2) + 5 x2 = np.random.randn(5,2) - 5 X = np.concatenate([x1,x2], axis=0) # Initialize the KMeans object with k=3 kmeans = KMeans(k=2) # Fit the k-means model to the dataset kmeans.fit(X) # Get the cluster assignments for the input dataset cluster_assignments = kmeans.predict(X) # Print the cluster assignments print(cluster_assignments) # Print the learned centroids print(kmeans.centroids) ``` -------------------------------- ### Create Zero Array Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/.test.ipynb Creates a NumPy array of zeros with a specified size. ```python np.zeros(2,) ``` -------------------------------- ### Defining model functions Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/linear_regression_md.ipynb Core functions for prediction, cost calculation, and gradient computation. ```python # F(x)= w[0]*x + w[1] def F(X, W): return np.matmul(X,W) def cost(Y_est, Y, W, Lambda): E=Y_est-Y return E, np.linalg.norm(E,2)+ Lambda * np.linalg.norm(W,2) def gradient(E,X, W, Lambda): return 2* np.matmul(X.T, E) + Lambda* 2* W ``` -------------------------------- ### Construct word windows iteratively Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Creates a windowed tensor using nested list comprehensions, which is computationally inefficient for large batches. ```python dummy_output = [[[dummy_input[i, j-2+k].item() for k in range(2*2+1)] for j in range(2, 6)] for i in range(2)] dummy_output = torch.LongTensor(dummy_output) print(dummy_output.size()) pp.pprint(dummy_output) ``` -------------------------------- ### Statistical Array Methods Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/numpy_practice.ipynb Calculates max, min, argmax, and argmin along specified axes. ```python a.max(axis = 0) ``` ```python a.argmax(axis=0) ``` ```python a.max(axis = 1) ``` ```python a.max() ``` ```python a.argmax() ``` -------------------------------- ### TwoLayerNet Class Implementation Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/feedforward.ipynb A complete implementation of a two-layer neural network including initialization, forward pass, loss calculation, and training loop. ```python import numpy as np class TwoLayerNet: def __init__(self, input_size, hidden_size, output_size): self.params = {} self.params['W1'] = np.random.randn(input_size, hidden_size) self.params['b1'] = np.zeros(hidden_size) self.params['W2'] = np.random.randn(hidden_size, output_size) self.params['b2'] = np.zeros(output_size) def forward(self, X): W1, b1 = self.params['W1'], self.params['b1'] W2, b2 = self.params['W2'], self.params['b2'] z1 = np.dot(X, W1) + b1 a1 = np.maximum(0, z1) # ReLU activation function z2 = np.dot(a1, W2) + b2 # probs = 1 / (1 + np.exp(-z2)) # Sigmoid activation function exp_z = np.exp(z2) probs = exp_z / np.sum(exp_z, axis=1, keepdims=True) return probs def loss(self, X, y): probs = self.forward(X) correct_logprobs = -np.log(probs[range(len(X)), y]) data_loss = np.sum(correct_logprobs) return 1.0/len(X) * data_loss def train(self, X, y, num_epochs, learning_rate=0.1): for epoch in range(num_epochs): # Forward propagation z1 = np.dot(X, self.params['W1']) + self.params['b1'] a1 = np.maximum(0, z1) # ReLU activation function z2 = np.dot(a1, self.params['W2']) + self.params['b2'] # probs = 1 / (1 + np.exp(-z2)) # Sigmoid activation function exp_z = np.exp(z2) probs = exp_z / np.sum(exp_z, axis=1, keepdims=True) # Backpropagation delta3 = probs delta3[range(len(X)), y] -= 1 dW2 = np.dot(a1.T, delta3) db2 = np.sum(delta3, axis=0) delta2 = np.dot(delta3, self.params['W2'].T) * (a1 > 0) # derivative of ReLU dW1 = np.dot(X.T, delta2) db1 = np.sum(delta2, axis=0) # Update parameters self.params['W1'] -= learning_rate * dW1 self.params['b1'] -= learning_rate * db1 self.params['W2'] -= learning_rate * dW2 self.params['b2'] -= learning_rate * db2 # Print loss for monitoring training progress if epoch % 100 == 0: loss = self.loss(X, y) print("Epoch {}: loss = {}".format(epoch, loss)) ``` -------------------------------- ### Import DataLoader dependencies Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Imports necessary modules for custom data loading. ```python from torch.utils.data import DataLoader from functools import partial ``` -------------------------------- ### Training Loop Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/logistic_regression_md.ipynb Iteratively updates weights using gradient descent. ```python def fit(W, X, Y, alpha, max_itr): for i in range(max_itr): F_x=F(X,W) Y_est=H(F_x) E, c= cost(Y_est, Y) Wg=gradient(Y_est, Y, X) W=W - alpha * Wg if i%1000==0: print(E, c) return W, Y_est ``` -------------------------------- ### Benchmark vectorized KNN Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_nearest_neighbors.ipynb Measures the execution time of the vectorized KNN function. ```python start=time.time() res = KNN_vectorized(X, Y, Z, k) print(time.time()-start,'seconds') ``` -------------------------------- ### Executing vectorized K-means Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_means_2.ipynb Runs the vectorized K-means function and measures execution time. ```python start=time.time() C, E, center_idx = k_means_vectorized(X, k) print(time.time()-start,'seconds') ``` -------------------------------- ### Evaluate Model Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Performs inference on the test set and prints predicted versus actual labels. ```python for test_instance, labs, _ in test_loader: outputs = model.forward(test_instance) print(torch.argmax(outputs, dim=2)) print(torch.argmax(labs, dim=2)) ``` -------------------------------- ### Generate Random Arrays Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/numpy_practice.ipynb Creates arrays with random values from uniform or normal distributions, or random integers. ```python # random.rand(): uniform distr over [0, 1) np.random.rand() np.random.rand(2) np.random.rand(2,3) ``` ```python # random.randn(): normal distr. np.random.randn(2,3) ``` ```python # random.randint: int in [low,high) / [0, high) np.random.randint(1,4) np.random.randint(1,4, (2,2)) ``` ```python np.random.randint(4) ``` -------------------------------- ### Learning Rate Decay Implementation Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/feedforward.ipynb Reduces the learning rate periodically during training to fine-tune weights as the optimization progresses. ```python # Learning rate decay learning_rate = 0.1 lr_decay = 0.95 lr_decay_epoch = 100 for epoch in range(num_epochs): # ... if epoch % lr_decay_epoch == 0: learning_rate *= lr_decay ``` -------------------------------- ### Implement vectorized KNN Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_nearest_neighbors.ipynb Optimizes distance calculation using matrix multiplication to improve execution speed. ```python def KNN_vectorized(X, Y, Z, k): # Find the distance from each point XX= np.tile(np.diag(np.matmul(X, X.T)), (m,1) ).T XZ=np.matmul(X, Z.T) ZZ= np.tile(np.diag(np.matmul(Z, Z.T)), (n,1)) D= np.sqrt(XX-2*XZ+ZZ) res=[] for j in range(m): c=np.argsort(D[:,j]) label=Counter(Y[c[0:k]]).most_common()[0][0] res.append(label) return res ``` -------------------------------- ### Generate synthetic data Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/k_nearest_neighbors.ipynb Creates random feature matrices and target labels for testing. ```python X=np.random.random((n,d)) Z=np.random.random((m,d)) Y=np.random.randint(3,size=n) ``` -------------------------------- ### Initialize zero-filled one-hot tensor Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/ww_classifier.ipynb Pre-allocates a zero-filled tensor for one-hot label representation. ```python one_hots = torch.zeros((2, len(l))) pp.pprint(("unfilled label instance", one_hots)) print(one_hots.size()) ``` -------------------------------- ### Adam Optimization Algorithm Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/feedforward.ipynb Updates parameters using adaptive moment estimation to improve convergence speed compared to standard SGD. ```python # Adam optimization beta1, beta2 = 0.9, 0.999 eps = 1e-8 mW1, vW1 = 0, 0 mW2, vW2 = 0, 0 for epoch in range(num_epochs): # Forward and backward propagation # ... # Update parameters using Adam optimization mW1 = beta1 * mW1 + (1 - beta1) * dW1 vW1 = beta2 * vW1 + (1 - beta2) * (dW1 ** 2) mW2 = beta1 * mW2 + (1 - beta1) * dW2 vW2 = beta2 * vW2 + (1 - beta2) * (dW2 ** 2) self.params['W1'] -= learning_rate * mW1 / (np.sqrt(vW1) + eps) self.params['b1'] -= learning_rate * db1 self.params['W2'] -= learning_rate * mW2 / (np.sqrt(vW2) + eps) self.params['b2'] -= learning_rate * db2 ``` -------------------------------- ### Define Model Functions Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/logistic_regression_md.ipynb Implements the forward pass, activation function, cost function, and gradient calculation. ```python # F(x)= w[0]*x + w[1] def F(X, W): return np.matmul(X,W) def H(F): return 1/(1+np.exp(-F)) def cost(Y_est, Y): E= - (1/n) * (np.sum(Y*np.log(Y_est) + (1-Y)*np.log(1-Y_est))) + np.linalg.norm(W,2) return E, np.sum(np.argmax(Y_est,1)==y)/n def gradient(Y_est, Y, X): return (1/n) * np.matmul(X.T, (Y_est - Y) ) + Lambda* 2* W ``` -------------------------------- ### Model Output Source: https://github.com/alirezadir/aimlinterviews/blob/main/src/MLC/notebooks/logistic_regression.ipynb The expected output after running the prediction on the sample data. ```text Output: [1 1] ```