Machine Learning for Beginners
Machine Learning for Everyone: Comprehensive Study Notes
What is Machine Learning?
Machine learning (ML) is a subdomain of computer science focused on algorithms that enable computers to learn from data without explicit programming. Instead of a programmer writing specific rules, the computer discovers patterns and makes decisions based on examples.
Artificial Intelligence (AI): The broader field aiming to enable machines to perform human-like tasks and simulate human behavior.
Machine Learning (ML): A subset of AI that uses data to make predictions or decisions.
Data Science: A field that finds patterns and draws insights from data, often using ML.
These fields overlap significantly, with ML being a core tool in both AI and data science.
Types of Machine Learning
Three main types exist:
Supervised Learning: Uses labeled inputs — each training example has a corresponding output label. The model learns to map inputs to outputs so it can predict labels for new, unseen data. Example: classifying images of cats, dogs, and lizards where each image is already labeled.
Unsupervised Learning: Uses unlabeled data to discover patterns or structure (e.g., clustering data points into groups without knowing the group names beforehand). Example: grouping similar images without being told what each group represents.
Reinforcement Learning: An agent learns by interacting with an environment, receiving rewards or penalties based on its actions. The agent learns to maximize cumulative reward. Example: training a dog (or a computer) by rewarding desired behaviors.
This course focuses on supervised and unsupervised learning.
Supervised Learning: Core Concepts
The Learning Framework
Inputs (features) go into a model, which produces an output (prediction).
The set of inputs for one sample is the feature vector.
Each feature can be qualitative (categorical) or quantitative (numerical).
Types of Features
Qualitative Features
Nominal data: No inherent order (e.g., nationality, gender). Use one-hot encoding to represent categories as binary vectors (1 for the matching category, 0 otherwise).
Ordinal data: Has inherent order (e.g., age groups: baby, toddler, teenager; ratings: bad, mediocre, good). Can be mapped to numbers (1 to 5) because the order and relative distances matter.
Quantitative Features
Discrete: Integer values (e.g., number of children).
Continuous: Any real number (e.g., length, temperature).
Types of Predictions (Tasks)
Classification: Predict discrete classes.
Binary classification: Only two categories (e.g., hot dog vs. not hot dog; spam vs. not spam).
Multi-class classification: More than two categories (e.g., cat, dog, lizard; types of fruit).
Regression: Predict a continuous numerical value (e.g., tomorrow's temperature, house price).
Data Splitting: Training, Validation, Test
To evaluate how well a model generalizes to new data, the available dataset is divided into three parts:
Training set (~60-80%): Used to train the model.
Validation set (~10-20%): Used as a "reality check" during or after training to tune hyperparameters and avoid overfitting. The loss from the validation set is not used to update the model.
Test set (~10-20%): Used only once after model selection to report the final performance. This simulates unseen data.
Key idea: If a model performs well on training data but poorly on validation/test data, it has overfit — it memorized the training set instead of learning general patterns.
Loss Functions
Loss measures the difference between the model's prediction and the true label. Lower loss means better performance.
L1 loss (Mean Absolute Error): ∣ytrue−ypred∣ — linear penalty for errors.
L2 loss (Mean Squared Error): (ytrue−ypred)2 — quadratic penalty, heavily penalizes large errors.
Binary Cross-Entropy Loss: Used for binary classification; decreases as predicted probabilities align with true labels.
Accuracy is another performance measure: total predictionsnumber of correct predictions.
Precision and Recall
From a confusion matrix:
True Positives (TP): Correctly predicted positive class.
False Positives (FP): Incorrectly predicted positive.
False Negatives (FN): Missed positive.
True Negatives (TN): Correctly predicted negative.
Precision: TP+FPTP — of all positive predictions, how many were correct?
Recall: TP+FNTP — of all actual positives, how many did we catch?
F1 Score: Harmonic mean of precision and recall: 2×precision+recallprecision×recall.
Supervised Learning Models: Classification (with Code Examples)
Data Preparation (Magic Gamma Telescope Dataset)
The dataset contains features of patterns recorded by a gamma telescope, used to classify particles as gamma (g) or hadron (h). Steps:
Import libraries:
numpy,pandas,matplotlib.Load CSV, assign column names, convert class labels to numeric (0 for gammas, 1 for hadrons).
Split into train, validation, test sets (e.g., 60/20/20).
Scale features using
StandardScalerfromsklearn.preprocessingso all features have mean 0 and variance 1.Oversample the training set to balance classes (e.g., using
RandomOverSampler) — important because the dataset has more gammas than hadrons.
1. K-Nearest Neighbors (KNN)
Concept: Classify a new point based on the majority label among its k closest neighbors in feature space. Distance is usually Euclidean distance: (x1−x2)2+(y1−y2)2.
Choose k (e.g., 3 or 5). The model looks at the k nearest points and picks the most common class.
Simple, non-parametric, works well with small to medium datasets.
Implementation:
sklearn.neighbors.KNeighborsClassifier(n_neighbors=k). Fit on training data, predict on test data.Performance on the dataset: ~82% accuracy with k=5.
2. Naive Bayes
Concept: Based on Bayes' Theorem and the naive assumption that features are independent given the class.
Bayes' rule:
For classification, the posterior probability of class Ck given feature vector x=(x1,x2,...,xn) is proportional to:
Prior: P(Ck) — probability of class Ck in the population.
Likelihood: P(xi∣Ck) — probability of seeing xi given class Ck.
Evidence (denominator) is constant across classes, so we ignore it for classification.
The predicted class is the one that maximizes this expression (Maximum A Posteriori or MAP).
Naive because it assumes feature independence, which is rarely true but often works well.
Implementation:
sklearn.naive_bayes.GaussianNB(for continuous features). Performance: ~72% accuracy.
3. Logistic Regression
Concept: Despite the name, this is a classification model. It models the probability that a sample belongs to a class using the sigmoid function.
Linear model: z=b0+b1x1+...+bnxn.
Sigmoid function: σ(z)=1+e−z1, which outputs a value between 0 and 1.
The model predicts the probability of the positive class. A threshold (usually 0.5) decides the class.
Interpretation: The log-odds of the probability are linear in the features: ln(1−PP)=z.
Implementation:
sklearn.linear_model.LogisticRegression. Performance: ~77% accuracy (with L2 regularization).
4. Support Vector Machines (SVM)
Concept: Find a hyperplane that best separates classes, maximizing the margin — the distance between the hyperplane and the nearest data points (support vectors).
Margin: The gap between the decision boundary and the closest points from each class. SVM aims for the largest margin.
Support vectors: The data points that lie on the margin boundaries and define the hyperplane.
Kernel trick: SVM can handle non-linear separability by projecting data into higher dimensions using a kernel function (e.g., polynomial, RBF). The projection finds a separating hyperplane in the new space.
Sensitive to outliers because a single outlier can drastically shift the margin.
Implementation:
sklearn.svm.SVC. Performance: ~87% accuracy — best among the simpler models.
5. Neural Networks
Concept: Inspired by the brain, a neural network consists of interconnected neurons arranged in layers: input layer, hidden layers, and output layer.
Each connection has a weight and each neuron has a bias. The neuron computes a weighted sum of inputs plus bias, then applies an activation function.
Activation functions introduce non-linearity; otherwise, the entire network collapses to a linear model. Common ones:
Sigmoid: 1+e−x1 (output 0 to 1)
Tanh: output -1 to 1
ReLU (Rectified Linear Unit): f(x)=max(0,x) (most common in hidden layers)
Training: Uses backpropagation and gradient descent to minimize loss (e.g., binary cross-entropy for classification).
The loss function measures error.
Gradient descent updates weights by moving in the direction that reduces loss, scaled by a learning rate α.
Implementation with TensorFlow/Keras:
tf.keras.Sequentialstacks layers.tf.keras.layers.Denseadds fully connected layers with specified units and activation.For binary classification, output layer with 1 unit and sigmoid activation.
Compile with optimizer (Adam) and loss (binary crossentropy).
Fit with epochs, batch size, and validation split.
Performance: ~87% accuracy (similar to SVM). Neural networks are powerful but require careful tuning of hyperparameters (number of layers, units, learning rate, dropout). Dropout randomly turns off neurons during training to prevent overfitting.
Supervised Learning: Regression
Regression predicts a continuous value (e.g., number of bikes rented, house price).
Linear Regression
Concept: Find the line of best fit that minimizes the error between predicted and actual values.
Simple linear regression (one feature): y^=b0+b1x
Multiple linear regression (multiple features): y^=b0+b1x1+b2x2+...+bnxn
Residuals (errors): The vertical distance between each actual data point and the regression line: yi−y^i.
The line of best fit minimizes the sum of squared residuals (Ordinary Least Squares).
Assumptions for linear regression:
Linearity: The relationship between features and target is linear.
Independence: Observations are independent of each other.
Normality: Residuals are normally distributed.
Homoscedasticity: The variance of residuals is constant across all values of the features.
Evaluation Metrics for Regression
Mean Absolute Error (MAE): n1∑i=1n∣yi−y^i∣ — average absolute error, in same units as target.
Mean Squared Error (MSE): n1∑i=1n(yi−y^i)2 — penalizes large errors more, but units are squared.
Root Mean Squared Error (RMSE): MSE — in same units, easier to interpret.
R-squared (R2): 1−TSSRSS, where RSS = sum of squared residuals and TSS = total sum of squares (around the mean). Ranges from 0 to 1; higher means better fit. Adjusted R2 penalizes adding extra features.
Linear Regression in Code (Seoul Bike Sharing Dataset)
Use
sklearn.linear_model.LinearRegression.Fit:
model.fit(X_train, y_train)Coefficients and intercept give the equation.
Score:
model.score(X_test, y_test)returns R2.For one feature (temperature), R2≈0.38; for multiple features, R2≈0.52.
Neural network regression: Use TensorFlow with a normalizer layer and dense layers (e.g., 32 units with ReLU), output 1 unit linearly (or ReLU if non-negative). Compare MSE with linear model.
Unsupervised Learning
Unsupervised learning works with unlabeled data to discover hidden patterns.
K-Means Clustering
Concept: Partition data into k clusters, each represented by its centroid (center). The algorithm aims to minimize within-cluster variance.
Steps:
Choose k random points as initial centroids.
Expectation step: Assign each data point to the nearest centroid (using Euclidean distance).
Maximization step: Recompute centroids as the mean of all points assigned to that cluster.
Repeat steps 2-3 until centroids stop changing (convergence).
k must be predefined. The final clusters depend on initial centroids; running multiple times may be necessary.
Applications: Customer segmentation, image compression, anomaly detection.
Implementation:
sklearn.cluster.KMeans(n_clusters=3). Use.labels_to get cluster assignments.
Example using wheat seed dataset: Without using the true class labels, K-means (k=3) groups the seeds into three clusters that roughly correspond to the wheat varieties. When using only two features (e.g., compactness and asymmetry), performance is poor; with all seven features, clusters align well with true classes.
Principal Component Analysis (PCA)
Concept: A dimensionality reduction technique that transforms data into a new set of orthogonal axes (principal components) that capture the maximum variance.
The first principal component is the direction of largest variance.
Subsequent components capture remaining variance under the constraint of being orthogonal to previous components.
PCA can be viewed as either maximizing variance or minimizing projection residuals (the perpendicular distance from points to the component direction).
Uses: Reduce number of features (e.g., from 7 to 2) while retaining most information, visualize high-dimensional data, remove noise.
Calculation involves eigenvectors/eigenvalues of the covariance matrix (not covered in detail).
Implementation: sklearn.decomposition.PCA(n_components=2). Fit-transform the feature matrix. The transformed data (e.g., 2D) can be plotted or used in clustering.
Wheat seed example: After PCA, the 2D representation shows clear separation among the three wheat types. K-means on the PCA-transformed data also performs well, demonstrating that PCA preserves cluster structure.
Summary of Key Techniques
Supervised Learning uses labeled data to predict outcomes.
Classification: KNN, Naive Bayes, Logistic Regression, SVM, Neural Networks.
Regression: Linear Regression (simple & multiple), Neural Networks.
Unsupervised Learning finds patterns in unlabeled data.
Clustering: K-Means.
Dimensionality Reduction: PCA.
Each model has strengths and weaknesses; the best choice depends on the dataset, problem type, and available computational resources. Neural networks are powerful but require more tuning, while simpler models like SVM or KNN can perform comparably on many tasks.

Ask anything
We've read this whole study set, so questions about it get the best answers.