Introduction to Machine Learning
Machine Learning (ML) is a subset of artificial intelligence that enables systems to learn and improve from experience without being explicitly programmed. ML algorithms build mathematical models based on sample data (training data) to make predictions or decisions.
Core ML Paradigms:
Supervised Learning
Learning with labeled data. The algorithm learns from input-output pairs.
Unsupervised Learning
Finding patterns in unlabeled data without predefined categories.
Mathematical Foundation
The general ML problem can be formulated as:
Given a dataset \( D = \{(x_1, y_1), (x_2, y_2), ..., (x_n, y_n)\} \), find a function \( f: X \rightarrow Y \) that minimizes the loss \( L(f(x), y) \).
Where:
- \( x_i \in X \) are input features
- \( y_i \in Y \) are target labels
- \( L \) is a loss function measuring prediction error
Supervised Learning Algorithms
Supervised learning algorithms learn the mapping function from input variables to output variables using labeled training data.
Linear Regression
Models relationship between dependent and independent variables using linear equation.
Logistic Regression
Models probability of binary outcome using logistic function.
Decision Trees
Tree-like model of decisions based on feature values.
Linear Regression Visualization
Adjust the parameters to see how linear regression fits the data:
Mean Squared Error
R² Score
Optimal Parameters
Unsupervised Learning Algorithms
Unsupervised learning algorithms discover hidden patterns or intrinsic structures in input data without labeled responses.
Clustering Algorithms:
K-Means Clustering
Partitions data into K clusters where each observation belongs to the cluster with the nearest mean.
Objective: Minimize within-cluster variance:
\[ J = \sum_{i=1}^{k} \sum_{x \in C_i} \|x - \mu_i\|^2 \]
Where \( \mu_i \) is the centroid of cluster \( C_i \).
Dimensionality Reduction:
Principal Component Analysis (PCA)
Projects data onto orthogonal axes that maximize variance.
First principal component:
\[ w_1 = \arg\max_{\|w\|=1} \text{Var}(w^T X) \]
Where \( X \) is the data matrix.
K-Means Clustering Visualization
Adjust parameters to see how K-Means clusters data:
Inertia (Within-cluster SSE)
Silhouette Score
Optimal K (Elbow Method)
Model Training and Optimization
Training machine learning models involves optimizing parameters to minimize a loss function using optimization algorithms.
Gradient Descent Algorithm:
The parameter update rule in gradient descent:
\[ \theta_{t+1} = \theta_t - \eta \nabla J(\theta_t) \]
Where:
- \( \theta_t \) - parameters at iteration t
- \( \eta \) - learning rate
- \( \nabla J(\theta_t) \) - gradient of loss function
Optimization Parameters:
Gradient Descent Visualization:
Learning Curves and Bias-Variance Tradeoff
Adjust model complexity to observe learning curves and bias-variance decomposition:
Bias
Variance
Total Error
Generalization Gap
Introduction to Neural Networks
Neural networks are computational models inspired by biological neural networks. They consist of interconnected nodes (neurons) organized in layers.
Neuron Structure:
A single neuron computes:
\[ z = \sum_{i=1}^{n} w_i x_i + b \]
\[ a = \sigma(z) \]
Where:
- \( x_i \) - input features
- \( w_i \) - weights
- \( b \) - bias
- \( \sigma \) - activation function
Activation Functions:
Neural Network Visualization:
Decision Boundary Visualization
Visualize how different classifiers create decision boundaries:
Training Accuracy
Test Accuracy
Decision Boundary Complexity
Machine Learning Implementation Exercise
In this comprehensive exercise, you'll implement a complete machine learning pipeline from scratch using scikit-learn. You'll work with a real-world dataset to predict house prices.
Implementation Steps:
Models to Implement:
Exercise Controls:
Implementation Hints
- Use
train_test_split(X, y, test_size=0.2, random_state=42)for splitting - For scaling:
scaler = StandardScaler(); X_train_scaled = scaler.fit_transform(X_train) - Linear Regression:
model = LinearRegression(); model.fit(X_train, y_train) - Model evaluation:
mse = mean_squared_error(y_test, y_pred); r2 = r2_score(y_test, y_pred) - Cross-validation:
cv_scores = cross_val_score(model, X, y, cv=5, scoring='r2')
Complete Solution:
# COMPLETE SOLUTION
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
from sklearn.pipeline import Pipeline
# 1. Data Preparation
np.random.seed(42)
n_samples = 500
data = {...} # Same as above
df = pd.DataFrame(data)
# 2. EDA
print("Correlation matrix:")
print(df.corr()['price'].sort_values(ascending=False))
# 3. Feature Engineering
X = df.drop('price', axis=1)
y = df['price']
# Create interaction features
X['bed_bath_ratio'] = X['bedrooms'] / X['bathrooms']
X['age_per_sqft'] = X['age'] / X['square_feet']
# 4. Data Splitting and Scaling
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 5. Model Training
models = {
'Linear Regression': LinearRegression(),
'Ridge Regression': Ridge(alpha=1.0),
'Decision Tree': DecisionTreeRegressor(max_depth=5, random_state=42),
'Random Forest': RandomForestRegressor(n_estimators=100, random_state=42),
'Gradient Boosting': GradientBoostingRegressor(n_estimators=100, random_state=42)
}
# 6. Model Evaluation
results = []
for name, model in models.items():
model.fit(X_train_scaled, y_train)
y_pred = model.predict(X_test_scaled)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
results.append([name, mse, rmse, r2, mae])
# 7. Hyperparameter Tuning (Random Forest as example)
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [None, 10, 20, 30],
'min_samples_split': [2, 5, 10]
}
rf = RandomForestRegressor(random_state=42)
grid_search = GridSearchCV(rf, param_grid, cv=5, scoring='r2', n_jobs=-1)
grid_search.fit(X_train_scaled, y_train)
# 8. Final Model
best_model = grid_search.best_estimator_
final_predictions = best_model.predict(X_test_scaled)
print(f"Best Model: {grid_search.best_params_}")
print(f"Best R² Score: {grid_search.best_score_:.4f}")
print(f"Test R² Score: {r2_score(y_test, final_predictions):.4f}")
Module 5 Quiz: Machine Learning Fundamentals
Test your understanding of machine learning concepts, algorithms, and principles.
1. What is the primary goal of regularization in machine learning?
2. In the bias-variance tradeoff, which of the following is true about high bias?
3. Which loss function is typically used for binary classification problems?
4. What does the learning rate parameter control in gradient descent?
5. In K-Means clustering, what is the "elbow method" used for?
6. Which of the following is NOT an advantage of decision trees?
7. What is the main difference between bagging and boosting ensemble methods?
8. In neural networks, what is the purpose of the activation function?
Your Score: 0/8
Detailed Explanations:
- Regularization adds a penalty term to the loss function to discourage complex models, thus preventing overfitting. L1 (Lasso) and L2 (Ridge) are common regularization techniques.
- High bias occurs when a model makes overly simplistic assumptions about the data, leading to underfitting. It fails to capture the underlying patterns in the data.
- Binary Cross-Entropy is designed for classification problems with two classes. It measures the dissimilarity between predicted probabilities and true labels.
- Learning rate determines how big of a step to take in the direction of the negative gradient during optimization. Too high can overshoot minima, too low can be slow.
- Elbow method in K-Means plots the within-cluster sum of squares (inertia) against the number of clusters. The "elbow" point indicates diminishing returns.
- Decision trees are prone to overfitting, especially with deep trees. Pruning, limiting depth, or using ensemble methods are needed to prevent this.
- Bagging (Bootstrap Aggregating) trains multiple models independently on random subsets, while boosting trains models sequentially, each correcting the previous.
- Activation functions like ReLU, sigmoid, or tanh introduce non-linearities, enabling neural networks to learn complex patterns beyond linear relationships.
Machine Learning Resources
- scikit-learn: Classical ML algorithms, preprocessing, model evaluation
- TensorFlow/Keras: Deep learning framework with high-level API
- PyTorch: Dynamic neural networks, popular for research
- XGBoost/LightGBM: Optimized gradient boosting implementations
- scipy: Scientific computing, optimization algorithms
- statsmodels: Statistical modeling and hypothesis testing
ML Project Checklist
Use this comprehensive checklist for your machine learning projects: