1. Home
  2. Explore
  3. Computer Science
  4. Linear Regression with Scikit-Learn

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Linear Regression with Scikit-Learn

A Practical Introduction to Machine Learning with Python

Machine learning is a way to build systems that learn useful patterns from data. Instead of writing every decision rule by hand, a practitioner provides examples, chooses a model structure, and allows an optimization procedure to learn the model’s parameters.

A practical machine learning project usually involves much more than calling a training function. It includes understanding the business problem, examining the data, preparing features, selecting an appropriate model, evaluating performance honestly, improving the model, interpreting its predictions, and eventually deploying it for real users.

This lesson develops that complete workflow through several important models:

  • Linear regression for predicting continuous numerical values
  • Logistic regression for classification
  • Decision trees and random forests
  • Gradient boosting machines
  • Unsupervised learning, including clustering and dimensionality reduction
  • Deployment of a trained model as a web application or API

1. The Basic Structure of a Machine Learning Problem

A machine learning problem generally contains three elements:

  1. Inputs, also called features
  2. Targets, also called labels or outputs
  3. A model that describes a relationship between the inputs and targets

For example, an insurance company may have historical records containing:

  • Age
  • Sex
  • Body mass index
  • Number of children
  • Smoking status
  • Region
  • Annual medical charges

The goal may be to estimate medical charges for a new customer. In that case, the customer information is the input, and the medical charge is the target.

A model tries to approximate a relationship such as

medical charges≈f(age,BMI,children,smoking status,region).\text{medical charges} \approx f(\text{age}, \text{BMI}, \text{children}, \text{smoking status}, \text{region}).medical charges≈f(age,BMI,children,smoking status,region).

The model does not necessarily discover a perfect law. Instead, it learns a useful approximation from historical examples.

Machine learning is the process of learning model parameters that make predictions from input data while minimizing an appropriate measure of error.

Parameters and hyperparameters

A parameter is learned by the model from data. In a linear model, the weights applied to features are parameters.

A hyperparameter is chosen before training. Examples include:

  • The maximum depth of a decision tree
  • The number of trees in a random forest
  • The learning rate of a boosting model
  • The number of clusters in a clustering algorithm

This distinction matters because the model learns parameters automatically, while the practitioner experiments with hyperparameters to control the model’s behavior.


2. Regression and Classification

The first major decision is determining what kind of target the model must predict.

Regression

A regression problem predicts a continuous numerical quantity.

Examples include:

  • Annual medical expenses
  • House prices
  • Ocean temperature
  • Store sales
  • Taxi fares

If the target can take many numerical values, such as $8,425.50 or $12,100.75, the task is generally regression.

Classification

A classification problem assigns an input to one or more discrete categories.

Examples include:

  • Rain tomorrow: yes or no
  • Tumor: benign or malignant
  • Loan applicant: will repay or will not repay
  • Image: digit zero through nine

Classification can be:

  • Binary, with two possible classes
  • Multiclass, with more than two possible classes

For example, predicting whether it will rain tomorrow is binary classification, while recognizing handwritten digits is multiclass classification.

Supervised and unsupervised learning

Both regression and classification are forms of supervised learning because the historical data contains target values.

In unsupervised learning, the data does not contain target labels. The model instead tries to discover structure within the data, such as:

  • Groups of similar customers
  • Unusual or anomalous observations
  • A smaller representation of high-dimensional data

Clustering and dimensionality reduction are common unsupervised learning techniques.

Choosing an evaluation metric

The evaluation metric should reflect what matters in the application.

For regression, common metrics include:

  • Mean absolute error
  • Root mean squared error
  • Root mean squared logarithmic error
  • Coefficient of determination, commonly called R2R^2R2

For classification, common metrics include:

  • Accuracy
  • Precision
  • Recall
  • F1 score
  • Confusion matrix
  • Log loss
  • Area under the ROC curve

The most appropriate metric depends on the consequences of mistakes. For example, in a medical diagnosis system, a false negative may be much more serious than a false positive. In that case, recall may matter more than overall accuracy.


Think About It

A store wants to predict daily sales. A medical system wants to decide whether a tumor is cancerous. Which task is regression, which is classification, and which error would be more serious in each situation?


3. Exploring and Preparing Data

Before training a model, the data must be understood and prepared. This stage often requires more reasoning than the actual model-training code.

3.1 Downloading and loading a dataset

Datasets commonly arrive as CSV files, database tables, APIs, or files from several sources. A typical workflow is:

  1. Obtain the dataset
  2. Load it into a pandas DataFrame
  3. Inspect its rows and columns
  4. Check data types
  5. Check for missing values
  6. Examine numerical summaries
  7. Visualize distributions and relationships

A DataFrame’s structure can be inspected with operations equivalent to:

df.info()
df.describe()

These checks reveal:

  • The number of rows and columns
  • The type of each column
  • The number of non-missing entries
  • Means and standard deviations
  • Minimum and maximum values
  • Percentiles and medians

Why initial inspection matters

Initial inspection can reveal problems such as:

  • Negative ages
  • Impossible geographic coordinates
  • Unexpectedly large passenger counts
  • Missing target values
  • Values recorded in inconsistent units
  • Highly skewed targets
  • Duplicate rows
  • Columns that should not be used as features

A clean-looking dataset should still be examined. A model can produce impressive training results while learning from invalid or misleading data.


3.2 Exploratory data analysis

Exploratory data analysis, or EDA, investigates the distributions of individual variables and their relationships with the target.

Useful plots include:

  • Histograms for distributions
  • Box plots for medians, quartiles, and outliers
  • Scatter plots for relationships between numerical variables
  • Violin plots for distributions across categories
  • Bar charts for category counts
  • Heat maps for correlations or confusion matrices

For example, an insurance dataset may show that:

  • Age is broadly distributed across the eligible age range
  • BMI is approximately normally distributed
  • Medical charges are strongly skewed
  • Smokers have much higher median medical costs than nonsmokers
  • The number of children has only a weak relationship with charges

A weather dataset may show that:

  • Rain occurs on only a minority of days
  • The target classes are imbalanced
  • Humidity and rainfall are related to the chance of rain tomorrow
  • Some locations receive much more rainfall than others
  • Temperature and humidity together provide useful information

EDA helps determine whether a feature should be transformed, removed, combined, or represented differently.

Class imbalance

A classification dataset is imbalanced when one class appears much more often than another.

Suppose 78% of weather observations have no rain tomorrow and 22% have rain tomorrow. A model that always predicts “no rain” already achieves 78% accuracy without learning anything useful.

Therefore, accuracy must be compared with a baseline. A high accuracy score may be misleading when one class dominates.


3.3 Input and target columns

The target column must be separated from the input columns.

If a model is supposed to predict tomorrow’s rain, then “rain tomorrow” cannot also be provided as an input. Doing so would cause target leakage: the model would receive the answer while supposedly making a prediction.

The same issue occurs with derived columns. If a model is intended to use today’s information, a column containing tomorrow’s rainfall amount must not be included, even if it is technically a separate column from “rain tomorrow.”

Unique identifiers should also usually be removed. A customer ID or row ID generally identifies an observation but does not describe the underlying phenomenon.


3.4 Training, validation, and test sets

A dataset is commonly divided into three parts:

Training set

The model learns from the training set. It uses the inputs and targets to estimate its parameters.

Validation set

The validation set is used while developing the model. It helps compare:

  • Different model types
  • Different hyperparameters
  • Different feature-engineering strategies
  • Different preprocessing methods

The validation set should not be used to update the model’s learned parameters.

Test set

The test set is held aside until the end. It provides a final estimate of how the selected model performs on unseen data.

A common approximate split is:

  • 60% training
  • 20% validation
  • 20% test

The exact proportions depend on the size and structure of the dataset.

Random splits versus time-based splits

A random split is appropriate when rows are independent and have no important ordering.

However, time-series data requires special care. If a model will be used to predict the future, it should be trained on the past and evaluated on later dates.

For example:

  • Training: data through 2014
  • Validation: data from 2015
  • Test: data from 2016 and 2017

Randomly mixing future and past observations could allow the model to learn patterns from the future while predicting the past. Such a validation result would be overly optimistic.

Overfitting

A model overfits when it performs very well on training examples but poorly on unseen examples.

This often means that the model has memorized specific training cases instead of learning general relationships.

An analogy is memorizing the answers to practice questions without understanding the underlying concepts. Performance may be excellent on familiar questions but poor on a new examination.


3.5 Missing-value imputation

Many machine learning models cannot operate directly on missing values.

The process of filling in missing values is called imputation.

A simple strategy replaces missing numerical values with the column mean:

xmissing←1n∑i=1nxi.x_{\text{missing}} \leftarrow \frac{1}{n}\sum_{i=1}^{n} x_i.xmissing​←n1​i=1∑n​xi​.

Other strategies include:

  • Replacing values with the median
  • Replacing values with a fixed constant
  • Using neighboring observations
  • Predicting missing values from other features
  • Treating missingness as its own category

The median is often safer than the mean when a column contains strong outliers. For example, a few extremely high incomes can distort the mean, while the median is more robust.

The imputer must be fitted using the training data. Its learned statistic should then be applied to the validation, test, and future input data. The validation or test data must not be used to compute the training statistic.


3.6 Scaling numerical features

Numerical features may have very different ranges. For example:

  • Temperature may range from −8-8−8 to 484848
  • Wind speed may range from 000 to 135135135
  • Pressure may range from 970970970 to 104010401040

Some models and optimization algorithms are affected by these differences in scale. A feature with large numerical values may disproportionately affect calculations.

Min-max scaling

Min-max scaling transforms a feature into a specified range, commonly [0,1][0,1][0,1]:

xscaled=x−xmin⁡xmax⁡−xmin⁡.x_{\text{scaled}} = \frac{x-x_{\min}}{x_{\max}-x_{\min}}.xscaled​=xmax​−xmin​x−xmin​​.

The minimum value becomes approximately 000, and the maximum becomes approximately 111.

Standardization

Standardization centers and scales a feature:

xstandardized=x−μσ,x_{\text{standardized}} = \frac{x-\mu}{\sigma},xstandardized​=σx−μ​,

where μ\muμ is the feature mean and σ\sigmaσ is its standard deviation.

The transformed feature has mean approximately 000 and standard deviation approximately 111.

Scaling is especially important for linear models, distance-based algorithms, and gradient-based optimization. Tree models are generally less sensitive to feature scale because they split according to thresholds.


3.7 Encoding categorical features

Machine learning models generally require numerical inputs, so categorical values must be represented numerically.

Binary encoding

A category with two values can often be mapped to zero and one.

For example:

smoker = no  → 0
smoker = yes → 1

This is suitable when the two values represent the presence or absence of something.

One-hot encoding

A categorical variable with multiple unordered categories should generally be converted into one column per category.

For a region variable with four categories:

Northeast
Northwest
Southeast
Southwest

A row belonging to the Northeast could be represented as:

1, 0, 0, 0

A row belonging to the Southwest could be represented as:

0, 0, 0, 1

This avoids falsely implying that one region is numerically greater than another.

Ordinal encoding

If categories have a genuine natural order, they may be represented by ordered numbers.

For example:

cold → 1
neutral → 2
warm → 3
hot → 4

Ordinal encoding is appropriate only when the order has meaning. Assigning numbers to unordered categories can create an artificial relationship.


Think About It

Why would assigning the values 111, 222, 333, and 444 to four geographic regions be misleading, while assigning those values to “cold,” “warm,” “hot,” and “very hot” may be reasonable?


4. Correlation and Its Interpretation

A correlation coefficient measures the strength and direction of a linear relationship between two variables.

Its value lies between −1-1−1 and 111:

  • 111: perfect positive linear relationship
  • Values near 111: strong positive relationship
  • Values near 0.50.50.5: moderate positive relationship
  • Values near 000: little or no linear relationship
  • Values near −1-1−1: strong negative relationship
  • −1-1−1: perfect negative linear relationship

A positive correlation means that larger values of one variable tend to be associated with larger values of the other. A negative correlation means that larger values of one variable tend to be associated with smaller values of the other.

For instance, medical charges may have:

  • A moderate positive correlation with age
  • A weak positive correlation with BMI
  • A very strong positive correlation with smoking status after binary encoding
  • A weak correlation with number of children

Correlation is not causation

Correlation does not establish a cause-and-effect relationship.

Two variables may be correlated because:

  1. XXX causes YYY
  2. YYY causes XXX
  3. A third variable ZZZ causes both
  4. The relationship is accidental
  5. The data contains bias or selection effects

For example, if income differs between two demographic groups, it would be incorrect to conclude that group membership directly causes income differences. Other factors, including discrimination, educational access, geography, or historical inequality, may explain the relationship.

Automated systems can amplify correlations that reflect social bias. Therefore, model outputs require human interpretation, domain knowledge, and ethical scrutiny.

A correlation matrix summarizes correlations among many numerical columns. A heat map makes strong and weak relationships easier to see than a table of numbers.


5. Linear Regression

5.1 The idea of a linear model

Linear regression models a target as a weighted sum of input features.

With one feature, the model is

y=wx+b,y = wx+b,y=wx+b,

where:

  • xxx is the input
  • yyy is the predicted target
  • www is the weight or slope
  • bbb is the bias or intercept

In geometry:

  • www determines how much yyy changes when xxx changes
  • bbb is the value of yyy when x=0x=0x=0

For example, medical charges might be modeled from age as

charges^=w(age)+b.\widehat{\text{charges}}=w(\text{age})+b.charges​=w(age)+b.

With multiple features, the model becomes

y^=w1x1+w2x2+⋯+wnxn+b.\widehat{y} = w_1x_1+w_2x_2+\cdots+w_nx_n+b.y​=w1​x1​+w2​x2​+⋯+wn​xn​+b.

For medical expenses, this might be

charges^=w1(age)+w2(BMI)+w3(children)+w4(smoker code)+b.\widehat{\text{charges}} = w_1(\text{age}) +w_2(\text{BMI}) +w_3(\text{children}) +w_4(\text{smoker code}) +b.charges​=w1​(age)+w2​(BMI)+w3​(children)+w4​(smoker code)+b.

With one feature, the model fits a line. With two features, it fits a plane. With more features, it fits a hyperplane in a higher-dimensional space.


5.2 Training a linear model

The general training process is:

  1. Choose a model structure
  2. Initialize the parameters
  3. Generate predictions
  4. Compare predictions with targets
  5. Calculate a loss
  6. Adjust the parameters to reduce the loss
  7. Repeat until the model is sufficiently good

A manually chosen line can be adjusted visually, but a computer needs a numerical measure of how well the line fits the data.

Residuals

A residual is the difference between an actual target and a prediction:

ri=yi−y^i.r_i=y_i-\widehat{y}_i.ri​=yi​−y​i​.

A positive residual means the prediction is below the target. A negative residual means the prediction is above the target.

Root mean squared error

The root mean squared error, or RMSE, is

RMSE⁡=1n∑i=1n(yi−y^i)2.\operatorname{RMSE} = \sqrt{ \frac{1}{n} \sum_{i=1}^{n} \left(y_i-\widehat{y}_i\right)^2 }.RMSE=n1​i=1∑n​(yi​−y​i​)2​.

The process is:

  1. Calculate each prediction error
  2. Square each error
  3. Compute the mean of the squared errors
  4. Take the square root

Squaring prevents positive and negative errors from canceling each other. It also gives greater influence to large errors and outliers.

RMSE is expressed in the same units as the target. If the target is measured in dollars, an RMSE of $4,600 means that predictions are typically several thousand dollars away from the actual values, although individual errors may vary.

Mean absolute error

The mean absolute error uses absolute values instead:

MAE⁡=1n∑i=1n∣yi−y^i∣.\operatorname{MAE} = \frac{1}{n} \sum_{i=1}^{n} \left|y_i-\widehat{y}_i\right|.MAE=n1​i=1∑n​∣yi​−y​i​∣.

Compared with RMSE, MAE gives less extra emphasis to outliers.

The lower the loss, the closer the predictions are to the targets.


5.3 Ordinary least squares and gradient descent

Two important optimization approaches are:

Ordinary least squares

Ordinary least squares computes the parameters that minimize the sum of squared errors using direct mathematical operations involving linear algebra.

It works well for relatively small datasets but may become inefficient with very large datasets.

Gradient descent

Gradient descent adjusts parameters iteratively.

The idea is similar to walking downhill in darkness:

  1. Test a small change in a direction
  2. Determine whether the loss decreases
  3. Continue moving in a direction that reduces the loss
  4. Repeat until reaching a low point

The gradient describes the direction in which the loss changes most rapidly. The model updates its parameters in the opposite direction of the gradient.

A learning rate controls the size of each update. A learning rate that is too small makes training slow. A learning rate that is too large may cause unstable updates or overshoot a good solution.

In practice, Scikit-Learn performs these computations internally. The practitioner generally selects the model and its settings rather than implementing the optimization mathematics manually.


5.4 Using Scikit-Learn

The standard Scikit-Learn workflow is:

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(inputs, targets)
predictions = model.predict(new_inputs)

The input matrix must usually be two-dimensional, with shape

(number of samples,number of features).(\text{number of samples},\text{number of features}).(number of samples,number of features).

Even when there is only one feature, it should be represented as a two-dimensional table rather than a one-dimensional sequence.

The learned coefficients can be inspected through the model’s coefficient and intercept attributes. These correspond to the weights and bias in the linear equation.


5.5 Interpreting coefficients carefully

A coefficient indicates how the model changes its prediction when a feature changes, holding other features constant. However, interpretation becomes more difficult when:

  • Features are measured on different scales
  • Features are correlated with one another
  • Features have been standardized
  • Categorical variables have been encoded
  • The relationship is not truly linear

For example, a BMI coefficient may numerically exceed an age coefficient, but BMI may have a smaller practical effect if BMI ranges only from approximately 151515 to 404040, while age ranges across many more units.

Standardization makes coefficient magnitudes more comparable because the features are placed on a similar scale.


6. Logistic Regression

Linear regression predicts continuous values. Logistic regression is designed primarily for binary classification.

6.1 From a weighted sum to a probability

Logistic regression first calculates a weighted sum:

z=w1x1+w2x2+⋯+wnxn+b.z=w_1x_1+w_2x_2+\cdots+w_nx_n+b.z=w1​x1​+w2​x2​+⋯+wn​xn​+b.

It then applies the sigmoid function:

σ(z)=11+e−z.\sigma(z)=\frac{1}{1+e^{-z}}.σ(z)=1+e−z1​.

The sigmoid maps any real-valued number into the interval (0,1)(0,1)(0,1). The result is interpreted as the probability of the positive class.

For weather prediction, the positive class may be “rain tomorrow.” A prediction of 0.820.820.82 means that the model estimates an 82% probability of rain.

A threshold is then used to convert the probability into a class. With a threshold of 0.50.50.5:

  • Probability at least 0.50.50.5: predict yes
  • Probability below 0.50.50.5: predict no

The threshold can be changed when false positives and false negatives have different consequences.


6.2 Cross-entropy loss

Logistic regression commonly uses cross-entropy loss.

The loss is low when:

  • The model assigns a high probability to the correct class
  • The model assigns a low probability to the incorrect class

It is high when the model is confidently wrong.

For a binary target yyy and predicted probability ppp, binary cross-entropy is

−[ylog⁡(p)+(1−y)log⁡(1−p)].-\left[y\log(p)+(1-y)\log(1-p)\right].−[ylog(p)+(1−y)log(1−p)].

The model adjusts its weights to minimize the average cross-entropy across the training examples.


6.3 Classification metrics

Accuracy

Accuracy is the fraction of predictions that are correct:

Accuracy⁡=number of correct predictionstotal number of predictions.\operatorname{Accuracy} = \frac{\text{number of correct predictions}} {\text{total number of predictions}}.Accuracy=total number of predictionsnumber of correct predictions​.

Accuracy can be misleading when classes are imbalanced.

Confusion matrix

A confusion matrix compares predicted and actual classes:

Actual negativeActual positive
Predicted negativeTrue negativeFalse negative
Predicted positiveFalse positiveTrue positive
  • True positive: correctly predicts the positive class
  • True negative: correctly predicts the negative class
  • False positive: predicts positive when the actual class is negative
  • False negative: predicts negative when the actual class is positive

A weather system used to decide whether an outdoor sporting event should proceed may need to minimize false negatives. A medical screening system may also prioritize avoiding false negatives.

Precision and recall

Precision measures how reliable positive predictions are:

Precision⁡=TP⁡TP⁡+FP⁡.\operatorname{Precision} = \frac{\operatorname{TP}} {\operatorname{TP}+\operatorname{FP}}.Precision=TP+FPTP​.

Recall measures how many actual positive cases are detected:

Recall⁡=TP⁡TP⁡+FN⁡.\operatorname{Recall} = \frac{\operatorname{TP}} {\operatorname{TP}+\operatorname{FN}}.Recall=TP+FNTP​.

The F1 score combines precision and recall:

F1=2⋅Precision⁡⋅Recall⁡Precision⁡+Recall⁡.F_1 = 2\cdot \frac{\operatorname{Precision}\cdot\operatorname{Recall}} {\operatorname{Precision}+\operatorname{Recall}}.F1​=2⋅Precision+RecallPrecision⋅Recall​.

7. Decision Trees

A decision tree represents a sequence of binary decisions.

A manually designed decision process might be:

  1. Is the salary within an acceptable range?
  2. Is the office close to home?
  3. Does the company provide transportation?
  4. Accept or reject the job offer

A machine learning decision tree learns the questions and thresholds automatically.

For weather prediction, a tree might first ask:

  • Is humidity at 3 p.m. below a certain value?

Depending on the answer, it may ask:

  • Is rainfall below a certain value?
  • Is wind speed above a certain value?
  • Is pressure below a certain value?

Each path ends in a leaf node, which contains the final prediction.


7.1 How a tree chooses splits

At each node, the algorithm considers possible features and thresholds. It chooses a split that best separates the target classes.

A common measure for classification trees is the Gini impurity.

A node has low impurity when most observations in it belong to one class. A perfectly pure node has Gini impurity of zero.

Conceptually, the training process is:

  1. Examine possible features
  2. Examine possible split thresholds
  3. Calculate the impurity after each split
  4. Choose a split that produces the greatest reduction in impurity
  5. Repeat recursively for the resulting child nodes

A tree may continue splitting until each leaf contains a single training example. That produces nearly perfect training accuracy but usually causes severe overfitting.


7.2 Tree interpretability

Decision trees are highly interpretable because a prediction can be explained as a sequence of conditions.

For example:

  • Humidity is greater than a threshold
  • Rainfall is below another threshold
  • Wind speed is above a threshold
  • Therefore, predict rain

A tree can be displayed graphically or as text. It can also provide feature-importance values based on how much each feature contributes to impurity reduction.


8. Overfitting and Regularization

A deep decision tree can memorize training examples.

Suppose a tree has training accuracy of approximately 100% but validation accuracy of only 79%. The model has learned the training data very specifically but has not learned general patterns.

Regularization reduces overfitting by limiting model complexity.

Common decision-tree hyperparameters include:

  • Maximum depth
  • Maximum number of leaf nodes
  • Minimum samples required to split a node
  • Minimum samples required in a leaf
  • Minimum impurity decrease
  • Split criterion

Maximum depth

A shallow tree can capture only simple patterns. A very deep tree can memorize the training data.

The ideal depth is usually somewhere between these extremes.

Maximum leaf nodes

Limiting the number of leaves restricts how many distinct final regions the tree can create.

Minimum samples for splitting

A node may be split only if it contains enough observations.

Minimum samples per leaf

A split may be forbidden if it would create leaves containing too few observations.

Cost-complexity pruning

Cost-complexity pruning removes branches that do not provide enough improvement relative to the complexity they add.


8.1 The model-complexity curve

As model complexity increases:

  1. Training error usually decreases
  2. Validation error initially decreases
  3. Validation error eventually increases because of overfitting

The best model is often near the minimum validation error, before additional complexity begins to harm generalization.

This pattern applies not only to decision trees but to many machine learning models.


Think About It

Why can a tree with a lower training error perform worse in the real world than a smaller tree with a higher training error?


9. Random Forests

A random forest combines many decision trees.

Each tree is trained with some randomness, and the forest combines their predictions:

  • For classification, the trees vote for a class
  • For regression, the predictions are averaged

The central idea is that individual trees make different errors. When their outputs are combined, some errors cancel.

This is an example of ensemble learning.

9.1 Randomization in a forest

Random forests commonly introduce randomness in two ways:

Bootstrap sampling

Each tree is trained on a randomly sampled dataset. Sampling is performed with replacement, so some rows may appear more than once while others may not appear in a particular tree’s training sample.

Random feature selection

At each split, the tree considers only a random subset of features rather than all available features.

This prevents every tree from becoming identical. The resulting trees are diverse, which improves the benefit of averaging their predictions.

9.2 Random-forest hyperparameters

Important hyperparameters include:

  • Number of trees
  • Maximum depth
  • Maximum leaf nodes
  • Maximum number of features considered at each split
  • Minimum samples per split
  • Minimum samples per leaf
  • Bootstrap sampling
  • Number of samples per bootstrap
  • Class weights

More trees usually improve stability, but gains eventually diminish while training time increases.

Random forests can provide feature-importance values, although these should be interpreted as general model behavior rather than proof of causation.


10. Gradient Boosting Machines

A gradient boosting machine also combines decision trees, but it trains them sequentially rather than independently.

10.1 The residual-correction idea

Suppose the target values are:

700, 800, 970, 850

The model first predicts the average, perhaps approximately 820820820 for every example.

The residuals are then:

−120,  −20,  150,  30.-120,\;-20,\;150,\;30.−120,−20,150,30.

Instead of immediately trying to predict the target values from scratch, the first tree learns to predict these residuals.

The model’s updated prediction becomes:

previous prediction+scaled residual prediction.\text{previous prediction} + \text{scaled residual prediction}.previous prediction+scaled residual prediction.

A second tree then learns the remaining errors after the first correction. A third tree corrects the errors remaining after the second, and so on.

The model gradually improves its predictions by adding small corrective trees.


10.2 Learning rate

The correction from each tree is multiplied by a learning rate:

y^new=y^old+η⋅r^,\widehat{y}_{\text{new}} = \widehat{y}_{\text{old}} + \eta \cdot \widehat{r},y​new​=y​old​+η⋅r,

where:

  • η\etaη is the learning rate
  • r^\widehat{r}r is the tree’s predicted correction

A small learning rate makes each tree’s contribution modest. More trees may then be required, but the model can generalize better.

A large learning rate allows each tree to make a stronger correction, which can speed training but may increase overfitting.

10.3 Important hyperparameters

Common gradient-boosting settings include:

  • Number of estimators
  • Maximum tree depth
  • Learning rate
  • Subsample fraction
  • Fraction of features used by each tree
  • Minimum loss reduction required for a split
  • Regularization-related parameters

Gradient boosting is often highly effective for tabular data because it can model nonlinear relationships and interactions between features.

Random forests versus gradient boosting

Random forests:

  • Train trees independently
  • Average or vote across trees
  • Rely heavily on variance reduction through randomness

Gradient boosting:

  • Trains trees sequentially
  • Each tree corrects earlier errors
  • Often achieves strong accuracy with carefully tuned settings

Both methods can be useful, and the best choice depends on the dataset, interpretability requirements, training time, and evaluation metric.


11. Feature Engineering

Feature engineering creates new features by transforming, combining, or supplementing existing data.

It is often more valuable than extensive hyperparameter tuning.

Examples

Date features

A date such as 2015-07-31 can be decomposed into:

  • Year
  • Month
  • Day of month
  • Day of week
  • Week of year
  • Hour
  • Weekend indicator
  • Start or end of month
  • Start or end of quarter

A model may not learn useful calendar patterns from a raw date string, but it can use separate numerical features.

Geographic distance

For a taxi-fare problem, pickup and drop-off latitude and longitude can be transformed into an approximate trip distance.

The Haversine formula estimates distance over the Earth’s surface:

d=2Rarcsin⁡(sin⁡2(Δφ2)+cos⁡(φ1)cos⁡(φ2)sin⁡2(Δλ2)),d = 2R \arcsin \left( \sqrt{ \sin^2\left(\frac{\Delta\varphi}{2}\right) + \cos(\varphi_1)\cos(\varphi_2) \sin^2\left(\frac{\Delta\lambda}{2}\right) } \right),d=2Rarcsin(sin2(2Δφ​)+cos(φ1​)cos(φ2​)sin2(2Δλ​)​),

where:

  • RRR is the Earth’s radius
  • φ\varphiφ represents latitude
  • λ\lambdaλ represents longitude

Distance to important landmarks, such as airports or business districts, may also help a model because trips to such locations can have distinct pricing patterns.

Aggregated historical features

For store sales, useful features may include:

  • Average sales for the store
  • Average sales for the same month in the previous year
  • Sales trend over time
  • Store type
  • Promotion duration
  • Competition distance
  • Time since a competitor opened

Feature engineering incorporates domain knowledge into a form the model can use.


12. Baseline Models

Before training a sophisticated model, a simple baseline should be established.

Examples include:

  • Always predict the mean target
  • Always predict the most common class
  • Make a random prediction
  • Use the previous month’s average
  • Use the same store’s value from the previous year

A baseline answers an important question:

Is the machine learning model actually better than a simple alternative?

For regression, a mean-prediction baseline may produce:

y^i=y‾\widehat{y}_i=\overline{y}y​i​=y​

for every observation.

For classification, a majority-class baseline always predicts the most frequent class.

A complex model that fails to beat a baseline is not useful, regardless of how sophisticated its implementation appears.


13. Cross-Validation and Ensembling

13.1 K-fold cross-validation

In KKK-fold cross-validation, the training data is divided into KKK parts.

For each fold:

  1. Use one part as validation data
  2. Use the other K−1K-1K−1 parts for training
  3. Train a separate model
  4. Record the validation score

For five-fold cross-validation, each observation serves as validation data once and training data four times.

This provides a more stable estimate than relying on one particular validation split. It is especially useful when the dataset is not extremely large.

However, ordinary random K-fold cross-validation may be inappropriate for time-series data because it can mix future and past observations. Time-based validation is safer when temporal order matters.

13.2 Ensembling

Ensembling combines predictions from multiple models.

For regression:

y^ensemble=1m∑j=1my^j.\widehat{y}_{\text{ensemble}} = \frac{1}{m} \sum_{j=1}^{m} \widehat{y}_j.y​ensemble​=m1​j=1∑m​y​j​.

For classification, the ensemble may use majority voting or average predicted probabilities.

If models make different errors, combining them can improve generalization.

13.3 Stacking

Stacking trains a second-level model using the predictions of several first-level models.

For example:

  1. Train a linear regression model
  2. Train a random forest
  3. Train a gradient boosting model
  4. Use their predictions as inputs to another model
  5. Learn how much weight to give each model

Stacking can outperform simple averaging, but it introduces additional complexity and must be designed carefully to avoid leakage.


14. Interpreting Models and Presenting Results

A model should not be treated as an unexplained black box.

Useful interpretation tools include:

  • Linear coefficients
  • Decision-tree paths
  • Feature-importance scores
  • Confusion matrices
  • Predicted probabilities
  • Examples of correct and incorrect predictions
  • Examples where the model is uncertain

A strong presentation should explain:

  1. The business problem
  2. The data used
  3. The target and input features
  4. The preprocessing steps
  5. The selected model
  6. The evaluation metric
  7. The validation and test results
  8. The most important features
  9. The model’s limitations
  10. How the model could be improved

A metric alone is rarely enough. A statement such as “the RMSE is 2,300” is less informative than “the model’s predictions are typically about $2,300 away from actual fares, but it performs less reliably for unusually expensive trips.”

The model should also be examined on individual inputs. This can reveal:

  • Implausible predictions
  • Unexpected sensitivity to a feature
  • Data leakage
  • Bias
  • Missing features
  • Cases requiring a separate model

15. Unsupervised Learning

Unsupervised learning works without target labels.

15.1 K-means clustering

K-means attempts to divide observations into KKK clusters.

The basic process is:

  1. Choose KKK random cluster centers
  2. Assign each point to its nearest center
  3. Recalculate each center as the mean of its assigned points
  4. Reassign points using the new centers
  5. Repeat until the assignments stabilize
  6. Repeat from different random starting points and keep a strong solution

The distance between points in multiple dimensions is often Euclidean distance:

d(x,c)=∑j=1p(xj−cj)2.d(\mathbf{x},\mathbf{c}) = \sqrt{ \sum_{j=1}^{p} (x_j-c_j)^2 }.d(x,c)=j=1∑p​(xj​−cj​)2​.

K-means requires the number of clusters to be specified in advance.

Inertia

K-means evaluates a clustering using inertia, which is the total within-cluster squared distance from points to their cluster centers.

Lower inertia means points are closer to their assigned centers. However, inertia always tends to decrease when more clusters are added.

Elbow method

To select KKK:

  1. Train K-means for several values of KKK
  2. Record the inertia for each value
  3. Plot inertia against KKK
  4. Look for an elbow, where additional clusters produce only small improvements

Applications include:

  • Customer segmentation
  • Product grouping
  • Fraud detection
  • Feature engineering
  • Market analysis

15.2 DBSCAN

DBSCAN groups points based on local density rather than distance to a fixed center.

It uses:

  • ε\varepsilonε, the neighborhood radius
  • Minimum samples, the minimum number of nearby points needed to form a dense region

Points are classified as:

  • Core points: have enough nearby observations
  • Reachable or edge points: lie near a core point but do not have enough neighbors themselves
  • Noise points: do not belong to any dense cluster

DBSCAN can identify irregularly shaped clusters and outliers. Unlike K-means, it does not require the number of clusters to be specified.

However, DBSCAN generally does not provide a straightforward way to assign new unseen points to clusters without reconsidering the data structure.


15.3 Hierarchical clustering

Hierarchical clustering creates a tree of clusters.

A bottom-up approach begins with every point as its own cluster:

  1. Find the two closest clusters
  2. Merge them
  3. Recalculate the merged cluster’s center or distance
  4. Continue until all observations form one hierarchy

The resulting tree is called a dendrogram.

Hierarchical clustering is useful when relationships naturally form levels, such as:

  • Species and biological taxonomy
  • Product categories
  • Document topics
  • Organization structures

16. Dimensionality Reduction

A dataset with hundreds or thousands of features can be difficult to visualize and expensive to process.

Dimensionality reduction transforms high-dimensional data into fewer dimensions while attempting to preserve important structure.

16.1 Principal component analysis

Principal component analysis, or PCA, finds new axes that capture as much variance as possible.

The first principal component is the direction along which the data has the greatest spread. The second principal component is perpendicular to the first and captures as much remaining spread as possible. Further components continue similarly.

A dataset with four features might be transformed into two principal components:

z=Wx,\mathbf{z} = W\mathbf{x},z=Wx,

where WWW contains the directions of the selected components.

PCA is useful for:

  • Reducing computation
  • Removing redundancy
  • Visualizing high-dimensional data
  • Preparing data for other models

PCA is linear, so it may not preserve nonlinear structures well.

16.2 t-SNE and manifold learning

t-SNE is a nonlinear dimensionality-reduction method primarily used for visualization.

It attempts to preserve local neighborhoods:

  • Points close together in the original space remain close
  • Points far apart may be separated in the visualization

For example, handwritten-digit images represented by hundreds of pixel values can be projected into two dimensions, often forming visually distinct groups for different digits.

t-SNE is useful for exploring structure but is generally not treated as a simple feature transformation for production prediction. It is also sensitive to settings and should not be interpreted as a precise global map of distances.

A common workflow for very high-dimensional data is:

  1. Use PCA to reduce hundreds of dimensions to a moderate number
  2. Use t-SNE to reduce further to two dimensions for visualization

17. A Complete Machine Learning Project Workflow

A practical project commonly follows this sequence:

Step 1: Understand the business problem

Determine:

  • What decision must be improved?
  • Why is the problem important?
  • How is it solved currently?
  • Who will use the predictions?
  • What is the cost of incorrect predictions?
  • What data is available?
  • How was the data collected?
  • Are the data and labels trustworthy?
  • What performance would be useful to the business?

The model should not be built merely because a dataset exists. It should serve a clear purpose.

Step 2: Classify the problem

Determine whether the task is:

  • Supervised or unsupervised
  • Regression or classification
  • Binary or multiclass classification
  • Clustering or dimensionality reduction

Step 3: Choose an evaluation metric

Agree on a metric that reflects the real objective.

Step 4: Obtain and inspect the data

Load the data, examine its structure, and investigate distributions, invalid values, missing values, duplicates, and class balance.

Step 5: Split the data

Create training, validation, and test sets. Use time-based splits when future prediction is involved.

Step 6: Engineer features

Transform dates, calculate distances, combine columns, obtain external information when appropriate, and remove features that leak target information.

Step 7: Prepare the data

  • Impute missing values
  • Scale numerical features when appropriate
  • Encode categorical features
  • Ensure training, validation, test, and future inputs receive identical transformations

Step 8: Establish baselines

Compare the machine learning model against simple rules such as the mean prediction or majority-class prediction.

Step 9: Train several model types

Begin with simple models:

  • Linear regression
  • Logistic regression
  • A basic decision tree

Then try more powerful models:

  • Random forests
  • Gradient boosting
  • Other suitable algorithms

Step 10: Tune hyperparameters

Use validation data or cross-validation to study parameters such as tree depth, number of estimators, learning rate, and regularization strength.

Step 11: Examine errors

Inspect incorrect and uncertain predictions. Error analysis often reveals more than a single score.

Step 12: Evaluate once on the test set

Use the test set only after selecting the model and approach. This provides a final estimate of real-world performance.

Step 13: Interpret and communicate

Explain the model, its strengths, limitations, important features, and examples of its behavior.

Step 14: Save and deploy

Save the model and every preprocessing object required to transform new inputs correctly.


18. Saving and Deploying a Model

A trained model is not just its learned coefficients. A usable prediction system may require:

  • The model
  • The imputer
  • The scaler
  • The categorical encoder
  • Input-column names
  • Encoded-column names
  • Any feature-engineering rules
  • The expected input format

These objects can be stored together in a serialized file, for example with joblib.

artifacts = {
    "model": model,
    "imputer": imputer,
    "scaler": scaler,
    "encoder": encoder,
    "input_columns": input_columns
}

When a new input arrives, it must pass through exactly the same transformations used during training:

  1. Convert the raw input to the expected structure
  2. Create engineered features
  3. Impute missing values
  4. Scale numerical features
  5. Encode categorical features
  6. Arrange columns in the correct order
  7. Pass the transformed input to the model
  8. Return the prediction

If preprocessing is skipped or applied differently, the model may receive values in an unfamiliar representation and produce unreliable results.

Web application deployment

A simple deployment architecture contains:

  1. A webpage with an input form
  2. A server-side application
  3. A route that receives the input
  4. The preprocessing pipeline
  5. The trained model
  6. A returned prediction

A Flask application can define routes such as:

  • A home route that displays the form
  • A prediction route that accepts the form submission
  • An API route that accepts JSON data

An API request might contain:

{
  "content": "Example input text"
}

The server processes the input and returns a response such as:

{
  "prediction": "not spam"
}

The web interface and the API are different ways of interacting with the same underlying model.

Deployment considerations

A production system should also consider:

  • Input validation
  • Error handling
  • Authentication
  • Logging
  • Monitoring
  • Model versioning
  • Data drift
  • Retraining schedules
  • Response time
  • Scalability
  • Security of serialized model files

A model that performs well during development may degrade when real-world data changes. Deployment is therefore not the final end of machine learning; monitoring and improvement continue after release.


Comprehensive Review

Machine learning begins with a problem that can be expressed through data. The practitioner identifies inputs, targets, constraints, and an appropriate evaluation metric.

Regression predicts continuous quantities. Classification predicts discrete classes. Supervised learning uses labeled targets, while unsupervised learning discovers structure without labels.

A complete project requires careful data work:

  • Explore distributions and relationships
  • Detect invalid values and outliers
  • Separate inputs from targets
  • Avoid target leakage
  • Impute missing data
  • Scale numerical features when appropriate
  • Encode categorical features
  • Split data into training, validation, and test sets

Linear regression models a target as a weighted sum of features. Logistic regression applies a sigmoid function to a weighted sum so that the output can be interpreted as a probability. Decision trees represent hierarchical decisions, random forests combine independently randomized trees, and gradient boosting builds trees sequentially to correct previous errors.

Overfitting occurs when a model memorizes training examples instead of learning general patterns. Regularization, validation, feature selection, limited tree complexity, subsampling, and careful hyperparameter tuning help control it.

Baseline models establish whether a machine learning model is actually useful. Cross-validation provides more stable evaluation, while ensembling and stacking combine models to reduce individual weaknesses.

Unsupervised techniques reveal structure without targets. K-means assigns points to a chosen number of centers, DBSCAN finds dense regions and noise, hierarchical clustering builds a tree of related groups, PCA finds linear directions of maximum variance, and t-SNE provides nonlinear visualizations of local structure.

Finally, a model becomes useful in practice only when it can receive new data, apply the same preprocessing steps, produce a prediction, and communicate that prediction reliably. The central objective is not merely a low training loss or an impressive metric, but a model that generalizes, can be interpreted, and provides dependable value in the real world.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent