DOCODIVE
Beginner Free Learning Path

Machine Learning Beginner Course

Learn the algorithms that power modern AI — KNN, Naive Bayes, SVM, gradient boosting, ensembles, and more. Build real models with scikit-learn and finish with an end-to-end classification project.

4–6 weeks 20 lessons 1 capstone Basic Python required
Start Learning
01

What Is Machine Learning?

15 min
What you'll learn
  • Define ML vs traditional programming
  • Understand the three learning types
  • See real-world ML systems

Machine learning flips traditional programming: instead of writing rules, you feed examples and let the algorithm learn patterns. Traditional code says 'if spam keywords, mark spam'; ML learns what spam looks like from thousands of labeled emails. The three types: supervised (labeled data), unsupervised (no labels), and reinforcement (learning from rewards). Every recommendation, fraud alert, and voice assistant you use is ML in production.

intro.py
# Traditional: rules
if 'free' in email and 'click' in email:
    print('spam')

# ML: learn from examples
model.fit(emails, labels)
model.predict(new_email)
Live Preview
What Is Machine Learning?
Define
Collect
Clean
Train
🔎 Important: If the problem is 'write clear rules', use code. If it's 'I have examples but no rules', use ML.
Try it yourself

Name one supervised and one unsupervised ML application.

Supervised = prediction; unsupervised = grouping.
Supervised: spam filter. Unsupervised: customer segmentation.
02

Supervised vs Unsupervised vs Reinforcement

18 min
What you'll learn
  • Distinguish the three paradigms
  • Pick the right approach
  • Understand what each solves

These three buckets organize all of ML. Supervised: you have input-output pairs (house features → price). Unsupervised: only inputs, find structure (group customers by behavior). Reinforcement: an agent takes actions and learns from rewards (game AI, robotics). Picking the right paradigm is the first design decision in any ML project — it determines your data needs, algorithms, and evaluation.

types.py
# Supervised: X -> y
X = [[2, 1], [3, 2]]
y = [4, 5]

# Unsupervised: only X
X = [[2, 1], [3, 2], [8, 9]]

# Reinforcement: state, action, reward
state = 'position'
action = 'move_left'
reward = 10
Live Preview
Supervised vs Unsupervised vs Reinforcement
🏷️Supervised
👥Unsupervised
🎮RL
💡 Tip: Ask first: do I have labels? Yes → supervised. No → unsupervised. Learning from interaction → RL.
Try it yourself

Classify: predicting tomorrow's stock price from historical data.

Labels = future prices.
Supervised (regression).
03

The ML Project Workflow

16 min
What you'll learn
  • Learn the 7-step ML workflow
  • Understand where projects fail
  • Plan before coding

Successful ML follows a disciplined workflow: define the problem, collect data, clean it, explore it, engineer features, train models, evaluate, and deploy. Most projects fail at step one — an ill-defined problem or no clear success metric. Before writing any model code, you should be able to answer: what am I predicting, what data do I have, and how will I know I've succeeded?

workflow.py
workflow = [
    '1. Define problem',
    '2. Collect data',
    '3. Clean data',
    '4. Explore (EDA)',
    '5. Engineer features',
    '6. Train & tune',
    '7. Evaluate & deploy'
]
for step in workflow:
    print(step)
Live Preview
The ML Project Workflow
1
2
3
4
5
6
7
✓ Best Practice: 60% of your time goes to steps 2-5 (data work), not model training.
Try it yourself

What's the FIRST thing you should define in an ML project?

Not the model.
The problem and success metric.
04

Getting Started with scikit-learn

18 min
What you'll learn
  • Install scikit-learn
  • Learn the estimator API
  • Fit and predict

scikit-learn is the standard ML library because every model shares one API: fit() trains, predict() outputs, transform() preprocesses. Master this triad once and you can use hundreds of algorithms. A typical flow: create the model object, call fit(X, y), then predict(X_new). This consistency is why scikit-learn is the best first ML library.

sklearn.py
from sklearn.neighbors import KNeighborsClassifier

model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(predictions[:5])
Live Preview
Getting Started with scikit-learn
fit()
predict()
transform()
✓ Best Practice: fit + predict is the whole scikit-learn mental model — learn it once, use it everywhere.
Try it yourself

Import and instantiate a KNeighborsClassifier with 5 neighbors.

KNeighborsClassifier(n_neighbors=5).
from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier(n_neighbors=5)
05

K-Nearest Neighbors (KNN)

20 min
What you'll learn
  • Understand KNN intuition
  • Choose k wisely
  • Know distance metrics

KNN is the simplest ML algorithm: to classify a new point, find its k nearest neighbors and take a majority vote. No training needed — it stores all data and computes distances at prediction time. It's intuitive, needs no assumptions, and is great for small datasets. The key choice is k: too small overfits (noisy), too large underfits (blurry boundaries). Distance is usually Euclidean.

knn.py
from sklearn.neighbors import KNeighborsClassifier

model = KNeighborsClassifier(n_neighbors=5)
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
print(f'Accuracy: {accuracy:.3f}')
Live Preview
K-Nearest Neighbors (KNN)
💡 Tip: k is your bias/variance dial: odd values avoid vote ties. Start with sqrt(n_samples).
Try it yourself

Why scale features before KNN?

Distance-based.
KNN uses distances; unscaled features dominate the distance calculation.
06

Distance Metrics

16 min
What you'll learn
  • Compare Euclidean, Manhattan, cosine
  • Pick distance for data type
  • Understand distance's role

Distance is the backbone of KNN, clustering, and similarity search. Euclidean is straight-line distance; Manhattan is grid-like (city blocks); cosine measures angle, ignoring magnitude — great for text. Choosing the right metric depends on your data and what 'similar' means in your domain. For high-dimensional data, cosine often beats Euclidean.

distance.py
from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity
import numpy as np

a = np.array([[1, 2]])
b = np.array([[4, 6]])
print('Euclidean:', euclidean_distances(a, b)[0][0])
print('Cosine:', cosine_similarity(a, b)[0][0])
Live Preview
Distance Metrics
Euclidean√(Σ(x-y)²)
ManhattanΣ|x-y|
Cosineangle
🔎 Important: cosine_similarity of [1,2] and [4,6] is 1.0 (same direction), but their Euclidean distance is 5 — magnitude vs angle.
Try it yourself

Which distance measure is best for comparing document similarity?

Ignore document length.
Cosine similarity.
07

Bias-Variance Tradeoff

22 min
What you'll learn
  • Understand bias and variance
  • Recognize under/overfitting
  • Find the sweet spot

Every model's error decomposes into bias (wrong assumptions, underfitting) and variance (sensitivity to data, overfitting). Simple models have high bias, low variance; complex models the opposite. The goal is the sweet spot: enough complexity to capture real patterns, not enough to memorize noise. This single concept explains why regularization, cross-validation, and model selection all matter.

bias_variance.py
# High bias: model too simple (underfits)
# High variance: model too complex (overfits)
# Sweet spot: right complexity
error = bias**2 + variance + irreducible_noise
Live Preview
Bias-Variance Tradeoff
Total error = bias² + variance + noise
🔎 Important: Underfit: bad on train AND test. Overfit: great on train, bad on test. Diagnose first.
Try it yourself

A model has 99% train accuracy and 60% test accuracy. What's happening?

Big gap.
Overfitting — high variance.
08

Naive Bayes

20 min
What you'll learn
  • Understand Bayes' theorem
  • Learn the naive assumption
  • Classify text with NB

Naive Bayes applies Bayes' theorem to classification, with a 'naive' assumption: features are independent given the class. Despite being wrong in practice, it works surprisingly well for text — spam filtering, sentiment, topic classification. It's fast, needs little data, and gives probabilities. For text, MultinomialNB is the standard; for continuous features, GaussianNB.

bayes.py
from sklearn.naive_bayes import MultinomialNB

model = MultinomialNB()
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
print(f'Accuracy: {accuracy:.3f}')
Live Preview
Naive Bayes
P(class)
×
P(word|class)
💡 Tip: Naive Bayes is often the best first model for text — fast, simple, and surprisingly strong baseline.
Try it yourself

Which NB variant is for text counts?

Multinomial.
MultinomialNB.
09

Support Vector Machines (SVM)

24 min
What you'll learn
  • Understand maximum margin
  • Learn kernels
  • Use SVM for classification

SVM finds the line (hyperplane) that best separates classes with the largest margin — the widest 'street' between classes. The kernel trick lets it handle non-linear data by implicitly mapping to higher dimensions. SVM excels on small-to-medium datasets with clear margins, and the RBF kernel is the standard default. It's a workhorse for image, text, and biological classification.

svm.py
from sklearn.svm import SVC

model = SVC(kernel='rbf', C=1.0)
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
print(f'Accuracy: {accuracy:.3f}')
Live Preview
Support Vector Machines (SVM)
🔎 Important: C is your regularization: small C = wide margin (simpler), large C = fit data tightly.
Try it yourself

What does the kernel trick do?

Non-linear data.
Maps data to higher dimensions so non-linear boundaries become linear.
10

Gradient Boosting & XGBoost

26 min
What you'll learn
  • Understand boosting
  • Learn XGBoost/lightgbm
  • Build state-of-the-art models

Boosting trains trees sequentially, each fixing the mistakes of the previous — turning many weak learners into one strong model. XGBoost and LightGBM are the optimized implementations that dominate Kaggle competitions and production tabular ML. They handle missing values, feature importance, and regularization out of the box. For structured data, gradient boosting is usually the answer.

xgboost.py
from xgboost import XGBClassifier

model = XGBClassifier(n_estimators=100, learning_rate=0.1)
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
print(f'Accuracy: {accuracy:.3f}')
Live Preview
Gradient Boosting & XGBoost
✓ Best Practice: For tabular data, try gradient boosting FIRST — it's the strongest general-purpose algorithm.
Try it yourself

What does learning_rate control in boosting?

Step size.
How much each tree contributes — smaller = slower but often better.
11

Ensemble Methods

22 min
What you'll learn
  • Understand bagging vs boosting
  • Combine models for accuracy
  • Use voting classifiers

Ensembles combine multiple models to outperform any single one. Bagging (random forests) trains models in parallel on random subsets, reducing variance. Boosting (XGBoost) trains sequentially, reducing bias. Voting ensembles combine diverse models (SVM + RF + KNN) and take majority vote. The intuition: many models make different errors, and combining them cancels those errors out.

ensemble.py
from sklearn.ensemble import VotingClassifier, RandomForestClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier

ensemble = VotingClassifier([
    ('rf', RandomForestClassifier()),
    ('svm', SVC(probability=True)),
    ('knn', KNeighborsClassifier())
], voting='soft')
ensemble.fit(X_train, y_train)
print(ensemble.score(X_test, y_test))
Live Preview
Ensemble Methods
RF
SVM
KNN
Vote
✓ Best Practice: A diverse ensemble beats a single model — combine models that make DIFFERENT kinds of errors.
Try it yourself

Bagging reduces what — bias or variance?

Parallel + averaging.
Variance.
12

Model Evaluation Deep Dive

24 min
What you'll learn
  • Use confusion matrices
  • Compute precision/recall/F1
  • Read ROC curves

Accuracy hides the full story. The confusion matrix shows all four outcomes; precision is 'of my positives, how many right', recall is 'of real positives, how many caught', F1 balances both. The ROC curve plots true positive rate vs false positive rate across thresholds — AUC (area under curve) summarizes ranking quality. These tools tell you not just 'is it good', but 'where does it fail'.

eval.py
from sklearn.metrics import classification_report, roc_auc_score

print(classification_report(y_test, y_pred))
print('AUC:', roc_auc_score(y_test, y_prob))
Live Preview
Model Evaluation Deep Dive
50
5
3
52
⚠️ Common Mistake: Pick the metric that matches your business goal: recall for fraud (catch everything), precision for recommendations (don't annoy).
Try it yourself

High recall but low precision means?

Catch vs accuracy.
You catch most positives but also many false positives.
13

Feature Selection

22 min
What you'll learn
  • Remove irrelevant features
  • Use feature importance
  • Understand the curse of dimensionality

More features isn't always better — the curse of dimensionality means too many features make data sparse and models overfit. Feature selection keeps the useful ones: filter methods (correlation), wrapper methods (try subsets), and embedded methods (feature importance from trees). Fewer, better features = faster training, simpler models, and often better accuracy.

select.py
from sklearn.feature_selection import SelectKBest, f_classif

selector = SelectKBest(f_classif, k=5)
X_selected = selector.fit_transform(X, y)
print('Original features:', X.shape[1])
print('Selected:', X_selected.shape[1])
Live Preview
Feature Selection
age
income
city
💡 Tip: Start with feature importance from a random forest — it's the fastest way to spot your most useful features.
Try it yourself

Why does too many features hurt a model?

Sparse data.
Curse of dimensionality — data becomes sparse, models overfit.
14

Dimensionality Reduction with PCA

24 min
What you'll learn
  • Understand PCA intuition
  • Reduce feature dimensions
  • Visualize high-dimensional data

PCA finds the directions of maximum variance in data and projects onto a few principal components — compressing 100 features into 2-3 that capture most information. It's used for visualization (plot high-dim data in 2D), speeding up training, removing noise, and as a preprocessing step. The trade-off: you lose interpretability because components are combinations of original features.

pca.py
from sklearn.decomposition import PCA

pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
print('Explained variance:', pca.explained_variance_ratio_)
Live Preview
Dimensionality Reduction with PCA
🔎 Important: explained_variance_ratio_ tells you how much info each component keeps — sum them to see total retained.
Try it yourself

What does explained_variance_ratio_[0] = 0.62 mean?

Variance captured.
The first component captures 62% of the data's variance.
15

Time Series Forecasting Intro

22 min
What you'll learn
  • Understand time series data
  • Learn trend/seasonality
  • Build a simple forecast

Time series data has order — stock prices, sales, temperature. Forecasting means predicting future values. Key components: trend (long-term direction), seasonality (repeating patterns), and noise. Simple methods like moving averages and exponential smoothing work surprisingly well as baselines. The critical rule: never shuffle time data, and always use past to predict future.

timeseries.py
import pandas as pd

# Moving average baseline
df['MA7'] = df['sales'].rolling(window=7).mean()
forecast = df['MA7'].iloc[-1]
print(f'Next day forecast: {forecast:.1f}')
Live Preview
Time Series Forecasting Intro
⚠️ Common Mistake: Time order matters — train on past, test on future. Random splits leak future info into training.
Try it yourself

What are the three components of a time series?

T, S, N.
Trend, seasonality, and noise.
16

Recommendation Systems Intro

22 min
What you'll learn
  • Understand collaborative filtering
  • Learn content-based vs collaborative
  • Build a simple recommender

Recommendation systems suggest items users will like. Content-based: recommend items similar to what the user liked (by features). Collaborative filtering: recommend what similar users liked (by behavior). The 'users who bought X also bought Y' pattern is collaborative filtering. Hybrid systems combine both and power Netflix, Amazon, and Spotify.

recommend.py
# Collaborative filtering idea
# similarity between users -> recommend items from similar users
user_a = {'item1': 5, 'item2': 4, 'item3': 3}
user_b = {'item1': 5, 'item2': 4}
# user_b hasn't rated item3; user_a (similar) rated it 3
recommend = 'item3'
Live Preview
Recommendation Systems Intro
📚
🎬
🎵
🎮
💡 Tip: Cold start is the classic problem — new users/items have no history. Content-based helps there.
Try it yourself

Content-based vs collaborative — which uses user behavior?

Behavior = ratings.
Collaborative filtering.
17

A/B Testing for ML

22 min
What you'll learn
  • Understand controlled experiments
  • Measure model impact
  • Avoid common pitfalls

A/B testing is how you prove a model actually improves things: split users into control (old system) and treatment (new model), then compare the metric (click rate, conversion). It's the bridge between offline accuracy and real-world value. Pitfalls: too-small samples, peeking early, and ignoring statistical significance. A model with higher offline accuracy but no A/B lift is a failure.

abtest.py
# A/B test comparison
control_conv = 0.10  # 10% conversion
variant_conv = 0.12   # 12% with new model
lift = (variant_conv - control_conv) / control_conv
print(f'Lift: {lift*100:.1f}%')
Live Preview
A/B Testing for ML
Control 10%
Variant 12%
🔎 Important: Offline accuracy ≠ business value — always validate with an A/B test before full rollout.
Try it yourself

Why can a higher-accuracy model still fail in production?

Metric vs value.
Accuracy may not correlate with the business metric users care about.
18

Model Interpretability

24 min
What you'll learn
  • Explain predictions
  • Use feature importance
  • Understand SHAP basics

A model that can't be explained is a liability. Interpretability tells you WHY a prediction was made — essential for trust, debugging, and compliance (GDPR 'right to explanation'). Tree models expose feature_importances_ directly. SHAP values give per-prediction explanations: which features pushed this specific decision up or down. Interpretable models make ML accountable.

interpret.py
from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier()
model.fit(X, y)
importances = model.feature_importances_
for name, imp in sorted(zip(feature_names, importances), key=lambda x: -x[1]):
    print(f'{name}: {imp:.3f}')
Live Preview
Model Interpretability
age
income
city
✓ Best Practice: If an unfair feature (gender, race) drives predictions, that's bias — interpretability exposes it.
Try it yourself

Name one reason interpretability matters.

Trust or compliance.
Building trust with users, debugging, or regulatory compliance.
19

ML Ethics & Fairness

22 min
What you'll learn
  • Recognize algorithmic bias
  • Audit models for fairness
  • Design responsibly

ML models learn from data — and if that data reflects historical bias, the model reproduces it. Fairness means different groups receive equal treatment (similar accuracy, similar false positive rates across demographics). Responsible ML requires auditing data, measuring group-wise metrics, and consciously designing for fairness. It's not just ethics — biased models cause legal, reputational, and financial harm.

fairness.py
# Audit fairness: accuracy per group
for group in ['group_a', 'group_b']:
    acc = accuracy_score(y_true[group], y_pred[group])
    print(f'{group}: {acc:.3f}')
Live Preview
ML Ethics & Fairness
Group A 95%
Group B 80%
⚠️ Common Mistake: A 15% accuracy gap between groups is a red flag — investigate your data and model.
Try it yourself

What's the first step in auditing ML fairness?

Look at data.
Examine training data for group representation imbalance.
20

Capstone: End-to-End Classification Project

50 min
What you'll learn
  • Apply the full ML workflow
  • Compare multiple models
  • Select and justify the best

Your capstone: a complete classification project. Load a dataset, clean it, explore with EDA, engineer features, then train and compare KNN, SVM, random forest, and gradient boosting. Evaluate each with cross-validation, pick the best, interpret its decisions, and write up why it won. This is the exact deliverable of a working ML engineer — portfolio-ready proof you can do the job.

capstone.py
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score

models = {
    'RF': RandomForestClassifier(),
    'XGB': XGBClassifier(eval_metric='logloss'),
    'SVM': SVC()
}
for name, model in models.items():
    scores = cross_val_score(model, X, y, cv=5)
    print(f'{name}: {scores.mean():.3f} (+/- {scores.std():.3f})')
Live Preview
Capstone: End-to-End Classification Project
XGB 0.93
RF 0.91
SVM 0.89
✓ Best Practice: Comparing models with cross-validation is the interview-answer to 'how do you pick a model?'
Try it yourself

Run 5-fold CV on a random forest and print the mean.

cross_val_score(model, X, y, cv=5).mean().
scores = cross_val_score(RandomForestClassifier(), X, y, cv=5)
print(scores.mean())
You've completed all 20 lessons. Ready for more?

Continue to Machine Learning Intermediate for advanced algorithms and tuning.

📱 Scan this QR code with your phone camera to instantly open this page.

Works on iOS, Android, and any modern device. No app installation required.

Account Verified!

Your email has been verified successfully.