Linear Regression with Scikit-Learn
Practical Machine Learning with Python and Scikit-Learn
Machine learning uses data to learn relationships between inputs and targets so that predictions can be made for new examples. A typical workflow includes:
Understanding the problem and business objective.
Collecting, cleaning, and exploring data.
Engineering useful features.
Splitting data into training, validation, and test sets.
Selecting a model, loss function, and evaluation metric.
Training the model by optimizing its parameters.
Evaluating, interpreting, and improving the model.
Saving, deploying, and monitoring the model.
The major techniques covered include:
Linear regression
Logistic regression
Decision trees
Random forests
Gradient boosting
Clustering
Dimensionality reduction
End-to-end machine learning project development
Deployment of a trained model as a web application and API
1. Machine Learning Problem Types
Supervised learning
In supervised learning, the dataset contains both:
Input features: information used to make a prediction.
Targets or labels: the known answer associated with each input.
The model learns a relationship between the features and the target.
Two major supervised learning problem types are regression and classification.
Regression
A regression problem predicts a continuous numerical value.
Examples include:
Annual medical expenses
House prices
Taxi fares
Store sales
Ocean temperature
Tomorrow’s temperature
The target may be any value within a range, such as 5.50, 12,000, or 250,000.
Classification
A classification problem assigns each input to one or more discrete categories.
Examples include:
Rain tomorrow: yes or no
Tumor: benign or malignant
Loan: repayment likely or unlikely
Email: spam or not spam
Image: digit from 0 through 9
Classification may be:
Binary classification: exactly two classes.
Multiclass classification: more than two possible classes.
Unsupervised learning
In unsupervised learning, the dataset has no target labels. The objective is to discover structure within the data.
Common tasks include:
Clustering: grouping similar observations.
Dimensionality reduction: representing high-dimensional data using fewer dimensions.
Association and recommendation: finding related items or behaviors.
Anomaly detection: identifying unusual observations.
2. Linear Regression
Medical expense prediction
A practical regression task is predicting annual medical expenses for insurance customers using features such as:
Age
Sex
Body mass index
Number of children
Smoking status
Region
The target is the customer’s actual annual medical charge.
A trained model can estimate the expected medical expense of a new customer. That estimate may then help an insurance company determine an insurance premium.
The historical dataset contains one row per customer. The features are the customer information, and the charges column is the target.
2.1 Loading and inspecting data
A CSV dataset can be downloaded and loaded into a pandas DataFrame. The first stages of any machine learning project should include:
Checking the number of rows and columns.
Inspecting column names.
Examining data types.
Finding missing values.
Checking numerical ranges.
Looking for invalid or implausible values.
Calculating summary statistics.
Important DataFrame operations include:
info: displays data types and non-null counts.describe: displays count, mean, standard deviation, minimum, percentiles, and maximum.isnull: detects missing data.value_counts: counts categorical values.corr: computes correlations between numerical columns.
A clean dataset should still be checked carefully. Values can be syntactically valid but conceptually incorrect.
2.2 Numerical and categorical features
A dataset may contain different feature types.
Numerical features
Numerical features represent quantities:
Age
BMI
Number of children
Medical charges
They may be integers or floating-point values.
Categorical features
Categorical features represent groups or labels:
Sex
Smoking status
Region
Although categorical values may initially be stored as strings, machine learning algorithms generally require numerical inputs.
2.3 Exploratory data analysis
Exploratory data analysis, or EDA, is used to understand the dataset before modeling.
Useful visualizations include:
Histograms
Box plots
Scatter plots
Violin plots
Bar charts
Heat maps
Age distribution
The ages may be approximately uniformly distributed over a range, with unusually high counts at certain ages. Such irregularities may result from:
Insurance eligibility rules
Special pricing for younger customers
The legal age for purchasing insurance
Sampling differences
Observed patterns should be treated as hypotheses that require domain verification.
BMI distribution
BMI is defined as:
BMI categories are commonly interpreted as:
Less than 18.5: underweight
18.5 to 24.9: normal range
25 to 29.9: overweight
30 to 39.9: obese
At least 40: morbid obesity
BMI may be approximately normally distributed, with most observations near the mean and fewer observations farther away.
Medical charge distribution
Medical charges are usually highly skewed:
Many customers have relatively low expenses.
A small number have very high expenses.
Major illness, accidents, or genetic conditions may produce outliers.
The median can be much lower than the mean because a small number of expensive cases pull the mean upward.
Smoking status often creates a substantial difference in medical expenses. Smokers may have a much higher median expense than nonsmokers. However, correlation alone does not establish why the difference exists.
Visualization by categorical groups
Histograms and violin plots can be divided by:
Smoking status
Sex
Region
Number of children
A violin plot is useful when many observations overlap. Its width indicates the relative density of values at different target levels.
2.4 Correlation
A correlation coefficient measures the strength and direction of a linear relationship between two numerical variables.
The coefficient lies between −1 and 1:
1: perfect positive linear relationship
Close to 1: strong positive relationship
Close to 0: weak or nonexistent linear relationship
Close to −1: strong negative relationship
−1: perfect negative linear relationship
A positive coefficient means that larger values of one variable tend to accompany larger values of the other. A negative coefficient means that larger values of one variable tend to accompany smaller values of the other.
The Pearson correlation coefficient is:
Categorical data must first be encoded numerically before correlation can be calculated. For a binary feature such as smoking status:
No →0
Yes →1
A correlation matrix displays the correlations between all pairs of numerical columns. A heat map makes strong and weak relationships easier to see.
Correlation does not imply causation
A high correlation does not prove that one variable causes another.
Possible explanations include:
X causes Y.
Y causes X.
A third variable Z causes both X and Y.
The correlation is accidental or produced by sampling bias.
The data reflects social or systemic factors rather than an inherent causal relationship.
This is especially important in healthcare, finance, criminal justice, facial recognition, and other high-impact systems. An automated model may reproduce or amplify historical discrimination if correlations are interpreted without understanding their causes.
2.5 The single-feature linear regression model
Suppose medical charges are estimated using only age. A linear model assumes:
For medical expenses:
where:
x is the input age.
y is the target charge.
y is the predicted charge.
w is the slope or weight.
b is the intercept or bias.
The slope controls how much the prediction changes when the input changes:
The intercept is the predicted value when the input is zero. Geometrically, it is where the line crosses the vertical axis.
The values w and b are the model’s parameters. The model structure remains linear while the parameters determine the precise position and slope of the line.
A basic prediction function can be represented mathematically as:
The model will not predict every customer’s expense exactly because medical costs depend on many factors and contain uncertainty. The aim is to learn a useful general trend.
2.6 Model error: residuals and RMSE
For an observation, the residual is the difference between the actual target and the prediction:
Positive and negative errors can cancel when added directly. To avoid this, squared errors are used.
The mean squared error is:
The root mean squared error is:
RMSE is expressed in the same units as the target. For medical expenses, it can be interpreted approximately as the average size of the prediction error in dollars.
RMSE penalizes large errors strongly because the errors are squared. This makes outliers have a large influence.
The mean absolute error is:
MAE is less sensitive to extreme outliers than RMSE.
A model’s error is also called its loss or cost. Lower loss generally indicates a better model.
2.7 Training a linear regression model with Scikit-Learn
The standard Scikit-Learn workflow is:
Create the input matrix X.
Create the target vector y.
Instantiate a model.
Fit the model using training data.
Generate predictions.
Evaluate the predictions.
For one feature, X must still be two-dimensional, with shape:
Thus, a single feature should be selected as a one-column DataFrame rather than a one-dimensional Series.
The fitted model stores:
Coefficients or weights
An intercept or bias
The learned relationship between features and target
The coefficient for age represents the change in predicted charges per unit of the transformed age feature. The intercept represents the baseline component.
Scikit-Learn’s linear regression model uses the ordinary least squares approach by default.
2.8 Multiple linear regression
With multiple features, the model becomes:
For medical expenses:
With two features, the model represents a plane rather than a line. With more features, it represents a hyperplane in a higher-dimensional space.
The workflow does not change:
Create a two-dimensional input matrix.
Fit the linear regression model.
Generate predictions.
Calculate the loss.
Inspect the learned coefficients.
Adding a feature does not necessarily improve a model. A feature with weak or irrelevant information may have almost no effect on the loss.
2.9 Encoding categorical features
Binary encoding
A binary category has two possible values and can often be represented by zero and one.
Example:
Female →0
Male →1
No smoker →0
Smoker →1
The model can then learn an additional contribution associated with the presence of the category.
One-hot encoding
A categorical feature with more than two unordered categories should generally be converted into separate binary columns.
For the four regions:
Northeast
Northwest
Southeast
Southwest
Each row receives a vector such as:
or:
Each row has one active category and zeros in the other category columns. This is called one-hot encoding.
Ordinal encoding
If categories have a meaningful natural order, they may be represented numerically.
Example:
Cold →1
Neutral →2
Warm →3
Hot →4
Ordinal encoding is appropriate only when the order itself has meaning. Arbitrary categories such as geographic regions should not be assigned numbers that imply a false ordering.
2.10 Standardization and feature scaling
Feature weights cannot be compared directly when features have very different ranges.
For example:
Age may range from 18 to 64.
BMI may range from approximately 16 to 53.
A one-hot feature ranges only from 0 to 1.
A large numerical range can disproportionately influence optimization and make coefficients difficult to interpret.
Standardization
Standardization transforms each numerical feature using:
where:
μ is the feature mean.
σ is the feature standard deviation.
The transformed feature has approximately:
Mean 0
Standard deviation 1
Min-max scaling
Min-max scaling transforms values into a specified interval, commonly [0,1]:
Scaling is especially useful for numerical optimization because:
Features have comparable ranges.
No feature dominates merely because of its units.
Gradient-based methods generally behave more reliably.
Numerical overflow and precision problems are reduced.
Categorical binary and one-hot features are already in a small range and usually do not require additional scaling.
3. Logistic Regression
Predicting rain in Australia
A weather dataset may contain approximately ten years of daily observations from many Australian weather stations. Features include:
Location
Minimum and maximum temperature
Rainfall
Evaporation
Sunshine
Wind direction and speed
Humidity
Atmospheric pressure
Cloud cover
Whether it rained today
The target is whether it will rain tomorrow.
This is a binary classification problem because the target has two possible values:
Yes
No
3.1 Logistic regression model structure
Logistic regression begins with a weighted sum, just like linear regression:
It then applies the sigmoid function:
The sigmoid converts any real-valued input into a value between 0 and 1.
The output is interpreted as the probability of the positive class:
For rainfall prediction:
A value near 1 indicates high probability of rain.
A value near 0 indicates high probability of no rain.
A value near 0.5 indicates uncertainty.
A classification decision can be made by applying a threshold, commonly 0.5:
Probability at least 0.5 → yes
Probability below 0.5 → no
Logistic regression is called regression because it models a continuous probability, but it is used as a classification algorithm.
3.2 Cross-entropy loss
For binary classification, logistic regression commonly uses binary cross-entropy, also called log loss:
The loss is:
Low when the model assigns high probability to the correct class.
High when the model is confidently wrong.
Especially severe when a probability close to 1 is assigned to an incorrect class.
The training process remains the same as in regression:
Initialize parameters.
Generate predictions.
Compare predictions with targets.
Calculate loss.
Optimize model parameters.
Repeat until the model improves sufficiently.
3.3 Weather data preparation
A weather dataset may contain missing values in both features and target columns.
Rows with missing target values should generally be removed because the model cannot learn from an example without a known answer.
If a feature is especially important, rows missing that feature may also be removed, though this decision depends on:
How many rows would be lost.
Whether the feature is essential.
Whether the missingness is systematic.
Whether the feature can be reliably imputed.
Imputation
The process of filling missing values is called imputation.
A simple strategy is mean imputation:
Other strategies include:
Median imputation
Most-frequent-value imputation
Fixed-value imputation
Model-based imputation
Using related features to estimate missing values
Median imputation is often preferable when outliers could distort the mean.
Feature scaling
Weather features may have very different numerical ranges. Min-max scaling or standardization gives features a more equal influence during optimization.
Categorical encoding
Categorical columns such as location, wind direction, and rain today must be encoded numerically.
Binary columns can be mapped to zero and one.
Multiclass columns can be one-hot encoded.
Unseen categories during prediction should be handled explicitly, commonly by ignoring them or mapping them to an unknown category.
3.4 Accuracy and class imbalance
Accuracy is the proportion of correct predictions:
Accuracy can be misleading when classes are imbalanced.
If rain occurs on only 20% of days, a model that always predicts “no rain” achieves approximately 80% accuracy without learning anything useful.
Therefore, model performance should be compared with simple baseline models such as:
Random guessing
Always predicting the majority class
Always predicting no rain
A useful model must outperform these baselines meaningfully.
3.5 Confusion matrix
A confusion matrix compares actual classes with predicted classes.
True negative
The actual class is negative and the model predicts negative.
Example: It does not rain, and the model predicts no rain.
True positive
The actual class is positive and the model predicts positive.
Example: It rains, and the model predicts rain.
False positive
The actual class is negative but the model predicts positive.
Example: It does not rain, but the model predicts rain.
False negative
The actual class is positive but the model predicts negative.
Example: It rains, but the model predicts no rain.
The importance of each error depends on the application:
For planning an outdoor event, false negatives may be particularly costly.
For cancer detection, false negatives may be dangerous because a disease could be missed.
For medical treatment decisions, false positives may also be harmful because a healthy person could receive unnecessary treatment.
Additional classification metrics include:
Precision
Recall
F1 score
Balanced accuracy
Area under the ROC curve
Log loss
3.6 Probabilistic predictions
Logistic regression can produce:
A class prediction using
predict.Class probabilities using
predict_proba.
For each input, the probabilities across all classes sum to 1.
Probabilities provide more information than a class label. A prediction of “rain” with probability 0.51 is much less certain than a prediction with probability 0.99.
4. Training, Validation, and Test Sets
A model should not be evaluated only on the data used to train it.
Training set
The training set is used to learn model parameters.
Validation set
The validation set is used during development to:
Compare models.
Tune hyperparameters.
Compare preprocessing strategies.
Select features.
Detect overfitting.
The validation set must not be used to directly update model parameters.
Test set
The test set is held aside until the end. It is used for the final performance estimate.
A typical division might be:
60% training
20% validation
20% test
The exact proportions depend on the dataset size and problem.
Random splitting
Random splitting is appropriate when observations are independent and have no meaningful order.
A fixed random seed makes the split reproducible.
Time-based splitting
For time-series data, random splitting can leak future information into training. A better strategy is:
Earlier dates: training set
Later dates: validation set
Latest dates: test set
This better simulates deployment, where the model learns from the past and predicts the future.
Overfitting
Overfitting occurs when a model performs very well on training data but poorly on unseen data.
It usually means the model has memorized examples rather than learning general relationships.
5. Decision Trees
A decision tree represents a hierarchy of binary decisions.
For example, a tree might decide whether to accept a job offer by checking:
Whether the salary lies within an acceptable range.
Whether the office is near the applicant’s home.
Whether transportation is provided.
Whether other conditions are satisfied.
A machine learning decision tree learns the decision rules automatically.
For rainfall prediction, the tree may learn decisions such as:
Is humidity at 3 p.m. below a threshold?
Is rainfall below a threshold?
Is wind speed below a threshold?
Is atmospheric pressure below a threshold?
Each path from the root to a leaf produces a prediction.
5.1 Decision tree training
For each candidate split, the model evaluates how well the split separates classes.
A common criterion is the Gini impurity:
where pk is the proportion of observations belonging to class k in a node.
For binary classification:
Gini impurity 0 means all observations belong to one class.
Higher impurity means classes are more mixed.
The training process is conceptually:
Evaluate possible features and split points.
Select a split producing low impurity.
Divide the data into child nodes.
Repeat recursively for each child node.
Stop when a stopping condition is reached.
Stopping conditions may include:
Maximum depth
Minimum number of samples for splitting
Minimum number of samples in a leaf
Minimum impurity decrease
Maximum number of leaf nodes
5.2 Decision tree overfitting
An unrestricted tree may continue splitting until it memorizes the training set.
This produces:
Very high training accuracy.
Poor validation accuracy.
Large difference between training and validation performance.
Limiting the tree’s complexity is called regularization.
Important hyperparameters include:
max_depth: maximum number of levels.max_leaf_nodes: maximum number of leaf nodes.min_samples_split: minimum samples required to split a node.min_samples_leaf: minimum samples allowed in a leaf.min_impurity_decrease: minimum improvement required for a split.criterion: impurity measure such as Gini or entropy.splitter: best or random split selection.
A shallow tree may underfit, while a very deep tree may overfit. The best value lies between these extremes and should be selected using validation performance.
5.3 Interpreting decision trees
Decision trees are highly interpretable because their decisions can be:
Visualized graphically.
Exported as text.
Followed from the root to a leaf.
A tree also provides feature importance values. These indicate how much each feature contributes to impurity reduction throughout the tree.
Feature importance can reveal:
Which measurements the model relies on.
Whether important features contain many missing values.
Whether feature engineering was useful.
Whether an unexpected feature dominates the model.
6. Random Forests
A random forest is an ensemble of decision trees.
Each tree is trained with some randomization. The forest combines their predictions.
Classification
The forest uses voting:
Each tree predicts a class.
The most common class becomes the forest prediction.
Regression
The forest averages the numerical predictions from all trees.
6.1 Why random forests work
Individual trees can make different errors. When their predictions are combined, some errors cancel out.
This is related to the wisdom of the crowd: the average of many imperfect estimates may be more accurate than one estimate.
Randomness is introduced in several ways:
Different bootstrap samples of rows.
Random subsets of features.
Randomized split decisions.
6.2 Bootstrap sampling and bagging
A bootstrap sample is created by repeatedly sampling rows with replacement.
Some rows may appear more than once, while others may not appear at all.
Training each tree on a different bootstrap sample produces a diverse collection of trees. This approach is called bagging, short for bootstrap aggregating.
6.3 Random forest hyperparameters
Important random forest hyperparameters include:
n_estimators: number of trees.max_depth: maximum depth of each tree.max_leaf_nodes: maximum leaf nodes per tree.max_features: number or fraction of features considered for each split.min_samples_split: minimum samples needed to split.min_samples_leaf: minimum samples in a leaf.bootstrap: whether bootstrap samples are used.max_samples: size of each bootstrap sample.class_weight: weights assigned to classes.
Increasing the number of trees often improves stability, but the improvement eventually shows diminishing returns.
Using all features at every split can cause trees to become too similar. Restricting the number of candidate features introduces diversity and can improve generalization.
Class weights can help when one class is underrepresented.
6.4 Random forest interpretation
Random forests provide:
Class or numerical predictions.
Class probabilities for classification.
Feature importance values.
Access to the individual decision trees.
The feature importance of a random forest combines information from its individual trees. It is useful for ranking features, though it should not automatically be interpreted as causation.
7. Gradient Boosting and XGBoost
A gradient boosting machine, or GBM, builds models sequentially.
Unlike a random forest, where trees are trained independently, each new tree in a boosting model attempts to correct errors made by the existing model.
7.1 Gradient boosting process
The process begins with a simple prediction, often the mean target value in regression.
For each training example:
Calculate the current prediction.
Calculate the residual or error.
Train a small decision tree to predict the residual.
Multiply the tree’s prediction by a learning rate.
Add the scaled prediction to the previous model.
Repeat.
The prediction after several trees is conceptually:
where:
ft(x) is the prediction of tree t.
η is the learning rate.
T is the number of trees.
Each tree predicts corrections rather than the full target.
7.2 Learning rate
The learning rate controls how much each new tree changes the overall model.
A small learning rate makes each update cautious.
A large learning rate makes each update aggressive.
A small learning rate usually requires more trees. This may improve generalization but increase training time.
The learning rate helps reduce overfitting by preventing a single tree from making an excessively large correction.
7.3 Boosting versus bagging
Random forest: bagging
Trees are trained independently.
Each tree attempts to solve the original problem.
Predictions are combined by voting or averaging.
Randomness is central.
Gradient boosting: boosting
Trees are trained sequentially.
Each tree corrects previous errors.
The model gradually improves.
The learning rate controls update size.
7.4 XGBoost configuration
XGBoost is an efficient implementation of gradient boosting.
Important hyperparameters include:
Number of estimators
Learning rate
Maximum tree depth
Row subsampling
Column subsampling
Minimum split requirements
Regularization parameters
Objective or loss function
The model can use decision trees or, in some configurations, linear base learners.
The most important parameters commonly include:
Number of trees
Tree depth
Learning rate
Row subsample fraction
Column subsample fraction
The model may be trained using CPUs or GPUs. GPU training can greatly accelerate large matrix and tree computations.
8. Feature Engineering
Feature engineering is the process of transforming existing data or incorporating external data to create features that are more useful for modeling.
Examples include:
Extracting year, month, day, weekday, and hour from a date.
Computing distance between two geographical coordinates.
Calculating distance to important landmarks.
Combining width and length into area.
Calculating how long a competitor has been present.
Determining whether a promotion is active.
Applying logarithmic transformations.
Creating rolling averages or historical statistics.
A model may be unable to discover a useful relationship from raw data if the relationship is hidden in an unsuitable representation.
For example, a linear model may not discover the relationship between house price and area if it is given only width and length. Creating an area feature may make the relationship much easier to learn.
Feature engineering is often more valuable than extensive hyperparameter tuning.
9. End-to-End Machine Learning Project Workflow
A professional machine learning project is not simply a process of fitting a model. It begins with understanding the business problem.
9.1 Understand the business requirements
Important questions include:
What business problem is being solved?
Why is the problem important?
What impact will the solution have?
How is the problem currently solved?
Could a simpler non-machine-learning solution work?
Who will use the predictions?
How will the predictions fit into existing processes?
What type of prediction is required?
What cost is associated with incorrect predictions?
What historical data is available?
How was the data collected?
Is the data representative of the real population?
What features are available?
Are the desired target values available?
Are there known data-quality problems?
Where is the data stored?
Who has access to it?
Are there privacy, ethical, or legal restrictions?
A project may be infeasible if:
The problem is too ambitious.
There is insufficient data.
The target is unavailable.
Features do not contain useful signal.
The model’s expected benefit is smaller than its development cost.
9.2 Select an evaluation metric
The evaluation metric should reflect business needs.
For regression, possible metrics include:
RMSE
MAE
Root mean squared logarithmic error
R2
Root mean squared percentage error
For classification, possible metrics include:
Accuracy
Precision
Recall
F1 score
Balanced accuracy
Log loss
ROC-AUC
The metric should be agreed upon with stakeholders before model development.
A loss function is used by the machine learning algorithm during optimization, while an evaluation metric is used by people to judge the model’s usefulness. They may be the same, but they do not have to be.
9.3 Clean and explore the data
The data preparation process should include:
Removing invalid rows.
Handling missing values.
Checking duplicates.
Parsing dates.
Inspecting ranges and distributions.
Studying relationships with the target.
Identifying outliers.
Detecting data leakage.
Checking class imbalance.
Creating useful features.
Data cleaning decisions should use both statistical evidence and domain knowledge.
9.4 Build baseline models
A baseline model provides a minimum performance standard.
Examples include:
Always predicting the mean target.
Always predicting the majority class.
Random guessing.
Using the previous month’s average.
Using the previous year’s average for the same store and month.
A machine learning model that performs worse than a simple baseline is not useful.
A manually designed rule may sometimes outperform a machine learning model. If the rule satisfies the business requirements and is easier to explain, it may be the better solution.
9.5 Compare modeling strategies
A systematic experiment process includes:
Listing possible model types.
Predicting what each model may achieve.
Training a basic version.
Recording training and validation results.
Comparing the results with expectations.
Tuning promising approaches.
Recording the best models and features.
A spreadsheet or experiment-tracking system should record:
Model type
Date
Features used
Hyperparameters
Training score
Validation score
Test score
Training duration
Notes
Notebook or code version
Possible models include:
Linear regression
Ridge regression
Lasso regression
Elastic net
Logistic regression
Decision trees
Random forests
Gradient boosting
Support vector machines
Nearest neighbors
Neural networks
9.6 Regularization and hyperparameter tuning
Hyperparameters are settings chosen before training. Examples include:
Tree depth
Number of trees
Learning rate
Minimum leaf size
Feature subsampling
Class weights
As model capacity increases:
Training error usually decreases.
Validation error may initially decrease.
Validation error eventually increases when overfitting begins.
The ideal model complexity is near the minimum validation error.
Grid search
Grid search tries combinations of predefined hyperparameter values and selects the best combination according to validation performance.
Cross-validation
In K-fold cross-validation:
Divide the data into K folds.
Train using K−1 folds.
Validate using the remaining fold.
Repeat until each fold has served as validation data.
Average the results.
Cross-validation uses more of the available data for both training and validation, but random cross-validation must be used carefully with time-ordered data.
9.7 Ensembling and stacking
Ensembling combines predictions from several models.
For regression, predictions may be averaged:
For classification, the most common predicted class can be selected.
Weighted ensembling gives different models different influence:
Stacking trains another model to learn the best combination of predictions from several base models.
The purpose of ensembling is to combine different model perspectives so that individual errors may cancel.
9.8 Interpret and present results
A model should be interpreted before deployment.
Useful interpretation tools include:
Feature coefficients for linear models.
Feature importance for tree models.
Confusion matrices.
Class probabilities.
Individual prediction analysis.
Misclassified examples.
Uncertain examples.
Prediction-versus-target comparisons.
Presentations for nontechnical stakeholders should emphasize:
The business objective.
The evaluation metric.
Practical accuracy.
Important features.
Strengths and limitations.
Examples of correct and incorrect predictions.
Risks and possible biases.
How the model can be improved.
How often it should be retrained.
Technical jargon and code should be minimized. Visualizations are usually more understandable than raw tables of numbers.
10. Rossmann Store Sales Project
The Rossmann problem predicts daily store sales using information such as:
Store
Date
Day of the week
Promotions
Holidays
Store type
Product assortment
Competition distance
Competition opening date
Company-wide promotions
The training data contains sales and customer counts. The test data contains input features but hides the sales target.
Feature engineering examples
Date features
Extract:
Year
Month
Day of month
Week of year
Weekday
Weekend indicator
Start or end of month
Start or end of quarter
Store metadata
Merge store-level data into daily sales data using the store identifier.
Competition duration
Instead of using competition opening year and month separately, calculate the number of months the competitor has been open:
Negative values should be replaced with zero when the competitor had not yet opened.
Promotions
Features can indicate:
Whether a promotion is active.
How long a promotion has been active.
Whether a new promotion begins during the current month.
Whether a store participates in a recurring company-wide promotion.
Store closure
If sales are always zero when a store is closed, the model does not need to learn this relationship. The rule can be handled directly:
Closed store → sales of zero.
Open store → use the machine learning model.
This reduces the complexity the model must learn.
11. Unsupervised Learning
11.1 Clustering
Clustering groups observations so that observations in the same group are more similar to each other than to observations in other groups.
Applications include:
Customer segmentation
Product recommendation
Fraud detection
Anomaly detection
Taxonomy creation
Feature engineering
11.2 K-means clustering
K-means requires the number of clusters, K, to be specified in advance.
The algorithm:
Select K initial cluster centers.
Assign each point to its nearest center.
Recalculate each center as the mean of its assigned points.
Reassign points using the updated centers.
Repeat until the assignments stabilize.
Repeat from different initial centers and select a low-variance solution.
For a point x and cluster center μj, the Euclidean distance is:
The point is assigned to the cluster with the smallest distance.
The inertia is the total within-cluster squared distance:
Lower inertia means that points lie closer to their cluster centers.
Choosing K
An elbow curve plots:
Number of clusters on the horizontal axis.
Inertia on the vertical axis.
The appropriate number of clusters is often near the point where adding more clusters produces diminishing improvement.
Mini-batch K-means
Mini-batch K-means uses small subsets of data to update the cluster centers. It is faster for large datasets and requires less memory.
11.3 DBSCAN
DBSCAN stands for density-based spatial clustering of applications with noise.
It identifies clusters based on point density rather than cluster centers.
Important parameters include:
ε: neighborhood radius.
Minimum samples: minimum number of nearby points needed to form a dense region.
Points may be classified as:
Core points: enough neighboring points exist.
Reachable or edge points: close to a core point but not dense themselves.
Noise points: not connected to any dense cluster.
DBSCAN is useful for irregularly shaped clusters and naturally identifies outliers.
Unlike K-means, DBSCAN does not require the number of clusters to be specified directly. However, it does not naturally provide a simple prediction function for assigning future points because adding a point can change the density structure.
11.4 Hierarchical clustering
Hierarchical clustering builds a hierarchy of nested clusters.
A bottom-up procedure is:
Treat every point as its own cluster.
Find the two closest clusters.
Merge them.
Compute the center of the merged cluster.
Repeat until all points belong to one cluster.
The result can be represented as a dendrogram, a tree showing how individual observations and clusters are progressively merged.
Hierarchical clustering is useful for:
Taxonomy creation
Biological classification
Grouping related products or documents
Exploring nested relationships
12. Dimensionality Reduction
High-dimensional datasets may contain hundreds or thousands of features.
Problems with many dimensions include:
Increased computation time.
Greater memory requirements.
More difficult visualization.
Increased risk of overfitting.
Redundant or highly correlated features.
Dimensionality reduction attempts to represent the data using fewer features while preserving important structure.
12.1 Principal component analysis
Principal component analysis, or PCA, creates new axes called principal components.
The first principal component is the direction that captures the greatest possible variance in the data. The second component is perpendicular to the first and captures the greatest remaining variance. Further components follow the same principle.
PCA can reduce p original features to q components, where q<p.
The components are linear combinations of the original features. They are not necessarily directly interpretable as individual physical variables.
PCA is useful for:
Reducing computation.
Removing redundancy.
Visualizing high-dimensional data.
Preparing data for other algorithms.
If 200 features can be reduced to five with little information loss, later processing may become much faster.
12.2 t-SNE
t-distributed stochastic neighbor embedding, or t-SNE, is a nonlinear dimensionality-reduction method mainly used for visualization.
Its objective is to preserve local neighborhoods:
Points close together in the original space should remain close in the reduced space.
Points far apart should generally be separated.
t-SNE can reveal clusters that are difficult to see using linear projections such as PCA.
A common workflow is:
Use PCA to reduce a very high-dimensional dataset to a moderate number of dimensions.
Use t-SNE to reduce those dimensions to two or three for visualization.
t-SNE is generally not used as a general-purpose feature transformation for future prediction because the embedding depends on the full dataset and is computationally expensive.
13. Model Saving and Loading
A trained model contains:
The model type.
Its configuration.
Learned parameters.
Preprocessing objects required for new inputs.
A deployment system may need to save:
The trained model.
Imputers.
Scalers.
Encoders.
Input column names.
Target column names.
Any feature-engineering configuration.
These objects can be stored together in a dictionary and serialized with Joblib.
The same preprocessing objects must be used during prediction. A new input must undergo exactly the same:
Missing-value imputation.
Feature scaling.
Categorical encoding.
Feature ordering.
Feature engineering.
Creating a new imputer, scaler, or encoder during prediction can produce inconsistent results because it would use statistics different from those learned during training.
14. Deploying a Machine Learning Model
A trained model becomes useful when it is integrated into a software system.
A simple deployment architecture can use:
GitHub for source control.
A Conda environment for dependency management.
Flask for a Python web application.
HTML and CSS for a user interface.
Render or another cloud service for hosting.
An API route for programmatic access.
14.1 Flask application structure
A Flask application typically includes:
An application object.
Routes.
Request handling.
Template rendering.
Model loading.
Prediction logic.
A route maps a URL to a Python function.
A basic application may include:
A home route that displays a form.
A prediction route that receives form data and returns a result.
An API prediction route that receives JSON and returns JSON.
14.2 HTML form
The form may include:
A text area for an email body.
A submission button.
A result section displaying spam or not spam.
The form sends a POST request to the prediction route.
The server:
Reads the submitted input.
Applies the required preprocessing.
Uses the trained model.
Converts the model output into a user-friendly result.
Renders the result in the HTML template.
14.3 API route
An API route accepts structured JSON such as:
{
"content": "Email text goes here"
}The server:
Parses the JSON body.
Extracts the email content.
Applies the tokenizer or vectorizer.
Calls the model.
Returns a JSON response.
A response might indicate a prediction using a class label or probability.
14.4 Deployment requirements
A deployment project should include a dependency file listing required packages. The hosting platform uses this file to install the application environment.
The application must also specify:
The startup command.
The Python version when necessary.
The application module.
The Flask application object.
Differences in library versions can cause code to work locally but fail in the cloud. Reproducible environments reduce this problem.
14.5 Production considerations
A basic deployment may later require:
Authentication.
Authorization.
Input validation.
Rate limiting.
Error handling.
Logging.
Monitoring.
Model versioning.
Secure storage of model files.
Protection against malicious inputs.
Automatic retraining.
Performance scaling.
The deployed model should be monitored because real-world data can change over time. Model performance may decline when the data distribution, user behavior, or underlying environment changes.
15. Central Principles
The major principles are:
Machine learning learns relationships from data rather than relying entirely on hand-coded rules.
The model type, loss function, evaluation metric, and optimizer are separate choices.
Good data preparation and feature engineering are often more important than complex modeling.
A model must be evaluated on data it did not use for training.
Validation and test sets must reflect how the model will be used in the real world.
Baseline models establish whether machine learning adds value.
Overfitting occurs when a model memorizes training data instead of learning general patterns.
Regularization controls model complexity and improves generalization.
Correlation indicates association, not causation.
Feature importance does not automatically establish causal importance.
Interpretability is essential in high-impact fields.
Random forests reduce variance by combining diverse trees.
Gradient boosting improves predictions by sequentially correcting errors.
Clustering discovers structure without labels.
Dimensionality reduction represents data using fewer dimensions.
Deployment requires saving both the model and every preprocessing step.
A useful model is defined by its practical business value, not by accuracy alone.
All models are imperfect; the goal is to find models that are useful, reliable, interpretable, and appropriate for their intended purpose.

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