Multiple Linear Regression with Scikit-Learn
Multiple Linear Regression is one of the most important algorithms in supervised machine learning. It predicts a numerical value using multiple independent variables (features) instead of just one.
For example, imagine you're trying to predict a startup's profit. Its profit might depend on several factors:
- How much it spends on research and development.
- How much it spends on administration.
- How much it spends on marketing.
- Which state it operates in.
Instead of considering only one factor, Multiple Linear Regression considers all these factors together to make a prediction.
In this tutorial, we'll understand the intuition behind Multiple Linear Regression, learn how categorical data is handled, and build a regression model step by step using Python and Scikit-learn.
We'll also explore regression assumptions, feature selection, and model evaluation.
We'll use the 50 Startups dataset, where our goal is to predict a startup's profit based on its spending and state.
1. Where This Fits
Machine learning algorithms are commonly divided into three categories: supervised learning, unsupervised learning, and reinforcement learning. Multiple Linear Regression belongs to supervised learning.
In supervised learning, we train a model on labeled data. Each row contains both:
- Input features: the information we give the model.
- Target variable: the correct answer we want the model to learn to predict.
For example, consider a dataset of houses:
| House Size (sq ft) | Bedrooms | Price |
|---|---|---|
| 1,000 | 2 | $150,000 |
| 1,500 | 3 | $220,000 |
| 2,000 | 4 | $300,000 |
House Size and Bedrooms are the input features, and Price is the target variable. The model learns the relationship between them.
What is Regression?
Regression is a type of supervised learning used to predict continuous numerical values. A continuous numerical value is a number that can take many possible values within a range. Examples include house prices, employee salaries, startup profits, temperature, and product demand.
Simple vs. Multiple Linear Regression
Previously, we learned about Simple Linear Regression, which uses one independent variable to predict a dependent variable.
Multiple Linear Regression extends this idea by using multiple independent variables.
| Model | Independent variables | Example |
|---|---|---|
| Simple Linear Regression | 1 | Predict profit using R&D spending |
| Multiple Linear Regression | 2 or more | Predict profit using R&D, administration, and marketing spending |
The main difference: Simple Linear Regression uses one feature, while Multiple Linear Regression uses several at once.
2. Understanding the Equation
Here is how Multiple Linear Regression makes predictions:
Don't worry if this looks complicated. Let's break it down.
| Symbol | Meaning |
|---|---|
| Dependent variable: what we want to predict | |
| Intercept (constant): the prediction when every feature is 0 | |
| Independent variables or features | |
| Coefficients representing the contribution of each feature | |
| Total number of independent variables |
What is a Coefficient?
A coefficient is how much the predicted value changes when its feature increases by one unit, while holding all other features constant.
Suppose a model learned this equation (illustrative numbers, not estimates from our dataset):
- Intercept (8): The predicted profit when all three spending values are zero.
- R&D coefficient (3): Increasing R&D spending by one unit increases predicted profit by 3 units, assuming other features remain unchanged.
- Administration coefficient (−0.54): Increasing administration spending by one unit decreases predicted profit by 0.54 units, assuming other features remain unchanged.
- Marketing coefficient (0.04): Increasing marketing spending by one unit increases predicted profit by 0.04 units, assuming other features remain unchanged.
Every feature has its own coefficient, and the model combines them all into one prediction.
Remember: Multiple Linear Regression doesn't mean that the model draws multiple separate regression lines. It learns one equation that combines multiple features.
3. Understanding Our Dataset
We'll use the 50 Startups dataset. Each row represents a startup, and each column contains information about that company.
| Feature | Description | Type |
|---|---|---|
| R&D Spend | Research and development expenses | Numerical |
| Administration | Administration expenses | Numerical |
| Marketing Spend | Marketing expenses | Numerical |
| State | State where the startup operates | Categorical |
| Profit | Startup's profit | Numerical |
Our objective is to predict Profit. Therefore:
- Dependent variable (y): Profit
- Independent variables (X): R&D Spend, Administration, Marketing Spend, and State
Numerical vs. Categorical Features
Numerical features are measurable quantities: age (25), salary (50,000), house size (1,500 sq ft), marketing spend (100,000).
Categorical features represent groups rather than quantities: gender (Male, Female), state (California, Florida, New York), department (Engineering, Marketing, Finance).
State is categorical because it holds state names, not numbers. Scikit-learn's Linear Regression requires numerical input, so we'll convert it using One-Hot Encoding.
4. Importing Libraries
First, let's import the libraries we'll need.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pdLet's understand their purposes:
| Library | Purpose |
|---|---|
| NumPy | Numerical operations and array handling |
| Matplotlib | Data visualization |
| Pandas | Loading and manipulating datasets |
We'll also use Scikit-learn for preprocessing, splitting the dataset, building a machine learning pipeline, and training our regression model.
5. Importing the Dataset
First, download the 50 Startups dataset. Save the file as mlr-50-startups.csv so the code below works without changes
Load the CSV with whichever option matches your environment:
# Option A: a local file (Jupyter, VS Code, etc.)
CSV_PATH = 'mlr-50-startups.csv'
# Option B: Google Colab with Google Drive (uncomment and edit the path)
# from google.colab import drive
# drive.mount('/content/drive')
# CSV_PATH = '/content/drive/MyDrive/path/to/mlr-50-startups.csv'
dataset = pd.read_csv(CSV_PATH)
dataset.head()read_csv() reads the file into a Pandas DataFrame, a two-dimensional table like a spreadsheet. head() shows the first five rows so we can see the structure before working with it.
Checking the Dataset Columns
Let's verify that our dataset contains the expected columns.
print(dataset.columns.tolist())Expected output:
['R&D Spend', 'Administration', 'Marketing Spend', 'State', 'Profit']We should also check the dataset's structure:
dataset.info()And check whether any values are missing:
print(dataset.isnull().sum())These checks help us understand the data before preprocessing.
6. Separating Independent and Dependent Variables
Before training, we separate the input features from the target:
- Independent variables (X): the information used to make predictions.
- Dependent variable (y): the value we want to predict.
target_column = 'Profit'
X = dataset.drop(columns=[target_column])
y = dataset[target_column]
print(X.shape, y.shape)Expected output:
(50, 4) (50,)drop() removes Profit from the inputs, because the model must never see the answer as an input. X has 50 rows and 4 features (a two-dimensional shape), and y has 50 target values (one-dimensional).
Notice that we keep X as a DataFrame, so we can refer to columns by name ('State') instead of by fragile positions like index 3. The code keeps working even if the column order changes.
7. Encoding Categorical Data
State holds text such as New York, California, and Florida. A regression model needs numbers, so how do we convert them? One common solution is One-Hot Encoding.
7.1 What is One-Hot Encoding?
One-Hot Encoding converts each category into its own binary column (0 or 1). Our three states become three columns:
| State | California | Florida | New York |
|---|---|---|---|
| New York | 0 | 0 | 1 |
| California | 1 | 0 | 0 |
| Florida | 0 | 1 | 0 |
Each new column is a dummy variable, and it works like a switch: 1 means the category is present, 0 means it is absent. A startup in Florida has California = 0, Florida = 1, New York = 0.
7.2 Why Not Simply Assign Numbers to Categories?
We might try California = 0, Florida = 1, New York = 2. But that invents an order that doesn't exist: the model would treat New York as "greater than" Florida and Florida as "greater than" California. One-Hot Encoding avoids this by representing each category independently.
7.3 Trying the Encoder by Hand
Let's see what OneHotEncoder produces. This step is only a demonstration. In Section 10, the encoder will live inside a pipeline, which is what we'll actually use for the model.
Version note:
sparse_output=Falseis available in Scikit-learn 1.2 and later. With older versions, usesparse=Falseinstead.
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse_output=False)
encoded_states = encoder.fit_transform(X[['State']])
encoded_states[:5]fit_transform()first fits (learns the unique categories), then transforms (converts them to binary columns).sparse_output=Falsereturns a regular dense NumPy array instead of a sparse matrix, which is easier to inspect. Older Scikit-learn versions call this argumentsparse=False.
7.4 What Happens After Encoding?
Our original dataset contains four independent features. The State feature has three categories. After One-Hot Encoding, we get:
- California
- Florida
- New York
- R&D Spend
- Administration
- Marketing Spend
Therefore, we now have six independent features instead of four. This happens because one categorical feature has been expanded into three binary features. But there's an important problem with keeping all three dummy variables.
8. Understanding the Dummy Variable Trap
When we use One-Hot Encoding, we create a separate dummy variable for every category. In our example, we created three dummy variables:
- California
- Florida
- New York
We create one dummy variable for each state:
| State | California | Florida | New York |
|---|---|---|---|
| California | 1 | 0 | 0 |
| Florida | 0 | 1 | 0 |
| New York | 0 | 0 | 1 |
Notice something interesting. Every row contains exactly one 1, and the remaining values are 0. Therefore, the sum of the three dummy variables is always equal to 1.
Mathematically:
This means that if we know the values of two dummy variables, we can always determine the third. If California = 0 and Florida = 0, then New York must be 1. The third column adds no new information.
8.1 What Is the Dummy Variable Trap?
In Multiple Linear Regression, we normally include an intercept in our equation. If we include all three dummy variables alongside the intercept, the model receives duplicate information. This creates a problem called perfect multicollinearity. Perfect multicollinearity means that one feature can be perfectly represented using a combination of other features.
In our example:
Think of it simply: if you know two dummies, you already know the third. If = 0 and = 0, it must be New York. So the third dummy adds nothing new. It's just a copy of what the intercept and the other two already tell us.
Because of this mathematical relationship, the coefficients are not uniquely identifiable: multiple combinations of coefficients can produce the same predictions. Analogy: you and a friend split $10. If I only tell you "the total is $10," there's no unique answer ($5/$5, $6/$4, $10/$0 all work). Same here: the coefficients become hard to interpret. This is the Dummy Variable Trap.
Scikit-learn's LinearRegression can still fit a model with all three dummies because it uses a least-squares solution, but the resulting coefficients are non-unique and harder to interpret so you should still drop a dummy to avoid the trap.
8.2 How Do We Avoid It?
The solution is simple. We remove one dummy variable and use its category as the reference category. For example, let's remove California. Our encoded data becomes:
| State | Florida | New York |
|---|---|---|
| California | 0 | 0 |
| Florida | 1 | 0 |
| New York | 0 | 1 |
Now, each state can still be represented:
- California = Florida 0, New York 0.
- Florida = Florida 1, New York 0.
- New York = Florida 0, New York 1.
California becomes our reference category.
8.3 What Is a Reference Category?
A reference category is the category against which the other categories are compared. In our example, California is the reference category. The model learns how Florida and New York differ from California.
For example:
- The Florida coefficient represents the difference between Florida and California.
- The New York coefficient represents the difference between New York and California.
The effect of California is already included in the intercept, so we do not need a separate California dummy variable.
8.4 Applying This in Scikit-learn
encoder = OneHotEncoder(drop='first', sparse_output=False)
encoded_states = encoder.fit_transform(X[['State']])drop='first' drops the first category in alphabetical order, which is California. Three states now produce only two dummy variables.
The general rule: for a categorical feature with N categories, use N − 1 dummy variables when the model includes an intercept. If you have several categorical features, apply the rule to each one separately.
| Number of categories | Number of dummies |
|---|---|
| 2 | 1 |
| 3 | 2 |
| 9 | 8 |
| 100 | 99 |
Note: Dropping one dummy is the right move for ordinary linear regression with an intercept. It isn't a universal requirement for every machine learning algorithm (tree-based models, for example, don't need it).
9. Splitting the Dataset into Training and Test Sets
Imagine studying for an exam with a set of questions and then being graded on exactly the same questions. You might score very well because you've already seen the answers, but that doesn't mean you can solve new ones. Machine learning has the same problem: if we train and evaluate on the same data, we can't tell how well the model handles unseen data. So we divide the dataset into two parts:
- Training set: the data used to teach the model.
- Test set: data the model hasn't seen, used only to evaluate it.
We'll use an 80/20 split, and we do it before any preprocessing (the next section explains why).
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=0
)Understanding the parameters
| Parameter | Meaning |
|---|---|
X |
Independent variables |
y |
Dependent variable |
test_size=0.2 |
20% of the data goes into the test set |
random_state=0 |
Makes the split reproducible |
Scikit-learn picks the test rows randomly. random_state fixes the random number generator, so you get the same split every time you run the code. A different value gives a different split and slightly different results.
Our 50 startups split like this:
| Dataset | Number of startups |
|---|---|
| Training set | 40 |
| Test set | 10 |
Let's inspect the shapes:
print(X_train.shape, y_train.shape)
print(X_test.shape, y_test.shape)Expected output:
(40, 4) (40,)
(10, 4) (10,)Both feature sets still have 4 columns because the encoding happens later, inside the pipeline.
10. Building and Training the Multiple Linear Regression Model
Before training, there is one important concept to understand: data leakage.
10.1 What Is Data Leakage, and How Do We Prevent It?
Data leakage happens when information from outside the training data improperly influences the model. Suppose we one-hot encode the entire dataset before splitting. The encoder has then learned from the test rows too. For one-hot encoding, the harm is tiny, but real workflows learn much more during preprocessing:
- Averages used to fill in missing values,
- Standard deviations used for feature scaling,
- Feature selection criteria,
- Other statistical information.
If these are computed on the full dataset before splitting, test-set information leaks into training, and your results look better than they should.
To prevent this, follow this order:
- Split the original dataset into training and test sets.
- Fit preprocessing using only the training data.
- Apply (transform) the fitted preprocessing to both training and test data.
- Train the model on the transformed training data.
- Evaluate it on the transformed test data.
Scikit-learn provides a useful tool called Pipeline to manage these steps.
10.2 Understanding ColumnTransformer
We previously learned that our dataset contains both numerical and categorical features. We need to apply One-Hot Encoding only to the State column while keeping the numerical columns unchanged. We can use ColumnTransformer for this.
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
preprocessor = ColumnTransformer(
transformers=[
('state_encoder', OneHotEncoder(drop='first'), ['State'])
],
remainder='passthrough',
verbose_feature_names_out=False
)transformers: a list of(name, transformer, columns). Here we applyOneHotEncoder(drop='first')to theStatecolumn, selected by name.remainder='passthrough': keeps every column we didn't transform. Our numerical columns stay as they are.verbose_feature_names_out=False: keeps the output feature names clean (State_Floridainstead ofstate_encoder__State_Florida).
Why don't we set
handle_unknown='ignore'? The default ishandle_unknown='error', so the encoder raises an error if it encounters a state it did not see during fitting. This is useful here because an unknown state should not silently receive a prediction. If you sethandle_unknown='ignore', an unseen category is encoded as all zeros.
10.3 Understanding Pipeline
A Pipeline connects preprocessing and the model into one workflow:
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
regressor = Pipeline(steps=[
('preprocessor', preprocessor),
('model', LinearRegression())
])The pipeline first encodes State and passes the numerical columns through, then feeds the result to Linear Regression.
10.4 Training the Model
regressor.fit(X_train, y_train)That's it! Calling fit() fits the encoder on the training data only and then trains the regression. Later, predict() reuses the already-learned encoding without fitting again.
10.5 What Happens During Training?
The model searches for the best coefficients in:
Here, ŷ is the predicted value, b₀ is the intercept, and b₁ … bₙ are the learned coefficients. It picks the coefficients that minimize the sum of squared prediction errors on the training data, a method called Ordinary Least Squares (OLS).
Suppose a model makes these predictions:
| Actual profit | Predicted profit | Error (Actual − Predicted) |
|---|---|---|
| 100,000 | 95,000 | 5,000 |
| 120,000 | 125,000 | −5,000 |
| 150,000 | 140,000 | 10,000 |
OLS squares each error and adds them up:
Squaring stops positive and negative errors from cancelling out, and it gives larger errors more influence. The coefficients that produce the smallest total are the ones the model keeps.
10.6 Inspecting the Learned Coefficients
model = regressor.named_steps['model']
feature_names = regressor.named_steps['preprocessor'].get_feature_names_out()
coefficients = pd.DataFrame({
'Feature': feature_names,
'Coefficient': model.coef_
})
print('Intercept:', model.intercept_)
print(coefficients)The encoded columns come first, followed by the passthrough columns:
| Index | Feature |
|---|---|
| 0 | State_Florida |
| 1 | State_New York |
| 2 | R&D Spend |
| 3 | Administration |
| 4 | Marketing Spend |
The pipeline now works with 5 columns, even though X_train still has 4. The feature names and coef_ must have the same length (5 each), so if you change the encoder, check that they still match.
How to read the output. With this dataset and the split used in this tutorial, R&D Spend has a positive coefficient of about 0.77. In this fitted model, that means one additional dollar of R&D spending is associated with roughly 77 cents more predicted profit, while the other features remain constant. Your exact output is printed by the code above. Coefficient size depends on each feature's units, so don't compare dollar-scaled features and 0/1 dummy variables by size alone.
11. Predicting the Test Set Results
Now we use the trained model to predict profits for startups it hasn't seen:
y_pred = regressor.predict(X_test)X_testholds the input features of the unseen startups.y_predholds the profits our model predicts.y_testholds the actual profits.
Let's compare the predictions with the actual values.
comparison = pd.DataFrame({
'Actual': y_test.values,
'Predicted': y_pred,
'Difference': y_test.values - y_pred
})
comparisonYour table will look something like this (illustrative values):
| Actual | Predicted | Difference |
|---|---|---|
| 103282.38 | 103015.20 | 267.18 |
| 144259.40 | 132582.28 | 11677.12 |
| 146121.95 | 132447.74 | 13674.21 |
The difference is Actual − Predicted, so:
- Positive: the model underpredicted the profit.
- Negative: the model overpredicted it.
- Close to zero: the prediction was close.
For example, an actual profit of 100,000 and a prediction of 90,000 gives a difference of +10,000: the model under-predicted by 10,000. Comparing individual rows isn't enough to judge the model overall, so we need evaluation metrics. A simple plot also helps us see how closely predictions follow the actual values
plt.figure(figsize=(7, 5))
plt.scatter(y_test, y_pred)
# Reference line: perfect predictions would fall on this line
minimum = min(y_test.min(), y_pred.min())
maximum = max(y_test.max(), y_pred.max())
plt.plot([minimum, maximum], [minimum, maximum], linestyle='--')
plt.xlabel('Actual Profit')
plt.ylabel('Predicted Profit')
plt.title('Actual vs. Predicted Profit')
plt.show()Points closer to the diagonal reference line indicate more accurate predictions.
12. Evaluating the Model
For regression, we commonly use MAE, MSE (and its square root, RMSE), and R² for comparing models.
12.1 Mean Absolute Error (MAE)
MAE is the average absolute difference between actual and predicted values; in other words, how far off the predictions are on average:
Here, n is the number of observations, the actual value, and the predicted value. For example:
| Actual | Predicted | Absolute error |
|---|---|---|
| 100 | 90 | 10 |
| 200 | 220 | 20 |
| 300 | 280 | 20 |
MAE = (10 + 20 + 20) / 3 = 16.67. These three rows are a separate toy example, not observations from the 50 Startups dataset. MAE is easy to explain because it uses the same unit as the target. If we predict profit in dollars, MAE is in dollars. A lower MAE means better predictions.
12.2 Mean Squared Error (MSE) and RMSE
Mean Squared Error measures the average of squared prediction errors.
Using the same example:
| Actual | Predicted | Error | Squared error |
|---|---|---|---|
| 100 | 90 | 10 | 100 |
| 200 | 220 | −20 | 400 |
| 300 | 280 | 20 | 400 |
MSE = (100 + 400 + 400) / 3 = 300. These rows are the same separate toy example, not startup data. Because errors are squared, large errors have a much bigger influence. The catch is that MSE is in squared units (dollars², for profit), which is awkward to interpret. So we usually also report its square root:
RMSE is back in the target's units (√300 ≈ 17.32). Because it weighs big misses more, RMSE is always at least as large as MAE, and a big gap between them signals a few large errors.
12.3 R-squared (R²)
R-squared measures how much of the variation in the target variable is explained by the model compared with a baseline that always predicts the mean of the target values.
Where:
- = Sum of squared residuals.
- = Total sum of squares around the actual target mean.
Let's understand the intuition.
Imagine we're predicting startup profits. A simple baseline model could predict the average profit for every startup. Our Linear Regression model tries to do better by using the available features. R-squared compares the model's prediction errors against the errors of that mean-based baseline.
- R² = 1: perfect predictions on the evaluated data.
- R² = 0: no better than predicting the mean.
- R² < 0: worse than predicting the mean (possible on test data).
A high R² does not automatically mean the model is reliable. We still need to ask whether it generalizes, whether the assumptions hold, whether the data is representative, and whether the model is overfitting.
12.4 Computing the Metrics
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
print(f'MAE: {mae:,.2f}')
print(f'MSE: {mse:,.2f}')
print(f'RMSE: {rmse:,.2f}')
print(f'R²: {r2:.4f}')With the standard 50 Startups CSV and random_state=0, the expected test-set results are approximately MAE = $7,514.29 and R² = 0.9347. Your run may differ if the CSV or split changes; use the values printed by your own execution.
13. Assumptions of Linear Regression
Before using Linear Regression on real-world data, we should understand its assumptions.
Why Do Assumptions Matter?
Linear Regression tries to model the relationship between independent variables and a dependent variable using a linear equation. But a linear equation may not describe every dataset accurately.
For example, imagine predicting house prices based on house size. If house prices increase approximately linearly with house size, Linear Regression might be suitable. But what if prices increase rapidly at first and then gradually flatten? A straight-line model might not describe that relationship well. This is why understanding regression assumptions is important.
The takeaway: Don't apply Linear Regression blindly. Check whether your data is suitable first.
There are five main assumptions and one additional check. Let's understand each one.
13.1 Linearity: Is a straight line a good fit?
The idea: The relationship between the input variables and the target variable should be approximately linear.
Example: Imagine predicting startup profit using R&D spending.
If profit increases by roughly the same amount whenever R&D spending increases, the relationship is approximately linear.
But if profit increases quickly at first and then starts to flatten, the relationship is curved. A straight line may not fit it well.
Good (approximately linear)
/
/
/
/
/
/
Potentially problematic (curved)
______
__/
_/
_/
_/
How to check: Create scatter plots of your input variables against the target. Look for patterns that are approximately straight rather than strongly curved.
13.2 Homoscedasticity: Are the errors equally spread out?
The idea: Prediction errors (residuals) should have roughly the same spread across different predicted values.
Example: Imagine predicting house prices.
- For cheaper houses, your prediction errors are around $5,000.
- For expensive houses, your prediction errors are also around $5,000.
This is a good sign. But if errors increase from 100,000 for expensive houses, the errors are not equally spread out.
A bad pattern often looks like a cone or funnel:
Good (roughly equal spread)
. . . .
. . . .
. . . .
. . . .
Bad (funnel-shaped spread)
. .
. . .
. . .
. .
.
How to check: Plot residuals against predicted values. We generally want a random cloud of points without a clear funnel-shaped pattern.
13.3 Normality of Errors: Are the Residuals Approximately Normally Distributed?
The idea: If you collect all your prediction errors, most should be small, with only a few large ones, and they should be balanced on both sides (some too high, some too low). This forms the classic bell curve.
Example: Imagine throwing darts at a target. Most darts land near the center, while fewer land far away.
Why it matters: This assumption is particularly important when calculating confidence intervals and testing whether a variable is statistically significant (p-values).
How to check: Create a histogram of the residuals. A histogram that looks approximately bell-shaped is a useful initial indication.
13.4 Independence: Are the Observations Independent?
The idea: Each row of data should be separate from the others. One row’s error shouldn’t tell you anything about the next row’s error.
Example: Stock prices break this rule. Today’s price depends heavily on yesterday’s price, which depends on the day before. The rows are linked like a chain.
In contrast, 50 different startups chosen independently are usually separate from each other. One startup’s profit doesn’t directly cause another’s.
This is sometimes called “no autocorrelation.” It matters most for time-based data.
How to check: Ask yourself: “Does the order of my rows matter, or does one row affect another?” If yes, linear regression may not be suitable.
13.5 Lack of Multicollinearity: Are the Independent Variables Too Similar?
The idea: Your inputs (predictors) shouldn’t be strongly correlated with each other.
Example: Imagine predicting a person's weight using both:
- Weight in kilograms
- Weight in pounds
Both columns represent exactly the same information. The model may struggle to distinguish their individual effects, making the coefficients unreliable. This is called multicollinearity.
💡 This is the same problem as the dummy variable trap you learned about earlier. There, one dummy column could be predicted perfectly from the others.
How to check: Look at the correlation between your input columns. If two are very strongly correlated, consider removing one.
dataset.drop(columns=["State"]).corr()13.6 Outlier Check: Are There Unusual Data Points?
This is not a true assumption, but it’s an important extra check.
The idea: An outlier is a data point that is very different from the rest. Even a single outlier can pull the regression line toward it and distort the whole model.
Example: Imagine 49 startups earn between 150,000, and one startup earns $5,000,000. That one startup can drag the line upward and make the predictions worse for everyone else.
What should you do? Investigate first. Don’t delete it automatically.
- Is it a data entry error (e.g., an extra zero by mistake)? Fix or remove it.
- Is it a genuine, real observation (e.g., a truly exceptional startup)? It might be important, so keep it.
⚠️ Important: Never remove outliers just because they’re inconvenient. Use your knowledge of the data and the business to decide.
Quick Summary
| Assumption | Question to ask | Warning sign |
|---|---|---|
| Linearity | Is a linear relationship reasonable? | Curved pattern in residuals |
| Homoscedasticity | Is the error spread consistent? | Funnel-shaped residual plot |
| Normality of errors | Are residuals roughly bell-shaped? | Strong skew or heavy tails |
| Independence | Are observations unrelated? | Time-dependent or grouped data |
| No severe multicollinearity | Are features too similar? | High correlations or VIF |
| Outlier check | Are there unusual points? | Points far from the rest |
What Should You Do as a Beginner?
- For practice exercises: Focus on understanding these assumptions. You don't need to perform every statistical test immediately.
- For real-world datasets: Use plots and simple diagnostic checks to identify potential problems.
- Don't memorize complicated definitions: Remember the question behind each assumption and understand why it matters.
The goal is not just to build a model that produces predictions, but to understand whether those predictions and statistical results are trustworthy.
14. Selecting the Right Features
Should we always include every available feature? Not necessarily. Some features are irrelevant or redundant. Feature selection means choosing a useful subset of features. It can give you:
- Simpler, more interpretable models: fewer features are easier to explain.
- Less overfitting: removing noise can help the model generalize.
- Lower cost: fewer features mean less training time.
14.1 Feature Selection Methods
There are five methods:
| Method | How it works |
|---|---|
| All-in | Include all selected predictors in the model. |
| Backward elimination | Start with all predictors and gradually remove the least useful ones. |
| Forward selection | Start with no predictors and gradually add the most useful ones. |
| Bidirectional elimination | Add and remove predictors step by step until no further changes are needed. |
| Score comparison | Build different combinations of models and select the one with the best score. |
14.2 All-in
The simplest approach: use all four original features (R&D Spend, Administration, Marketing Spend, State). It's a reasonable starting point when you have a limited number of meaningful features, and it's what we've done so far.
14.3 Backward Elimination
Backward elimination starts with all predictors and removes the least statistically significant one at a time, using p-values.
Step-by-step process:
- Choose a significance level, usually 0.05.
- Fit a model with all predictors.
- Find the predictor with the highest p-value.
- If it exceeds the significance level, remove it and refit.
- Repeat until every remaining p-value is below the level.
What is a p-value? It asks: "If this feature actually did nothing, how surprising would these results be?"
- Small p-value (e.g. 0.01) → surprising if the feature were useless → probably a real effect → keep it.
- Large p-value (e.g. 0.60) → totally normal even if the feature were useless → probably just noise → drop it.
At the end, we have a model containing only the predictors that meet our significance criterion.
However, a p-value does not measure a feature's practical importance or guarantee better prediction performance.
14.4 Forward Selection
Forward selection works in the opposite direction: start with an empty model and add predictors one at a time.
Step-by-step process:
- Choose a significance level, usually 0.05.
- Build separate models using each predictor individually.
- Find the predictor with the lowest p-value.
- If its p-value is below 0.05, add it to the model.
- Try adding each of the remaining predictors one at a time.
- Add the predictor that provides the most significant improvement.
- Repeat until no remaining predictor meets the chosen significance level.
The final model contains the predictors selected during this process.
14.5 Bidirectional Elimination
Bidirectional Elimination combines Backward Elimination and Forward Selection. It can both add new predictors and remove previously selected predictors. The process continues until no more predictors need to be added or removed.
14.6 Score Comparison
Another approach is to fit models with every combination of features and compare them using a chosen metric. With three predictors, that means seven models (each predictor alone, each pair, and all three). But the number grows exponentially: for n features, there are 2ⁿ − 1 non-empty combinations. This quickly becomes computationally impractical.
Important Notes About Feature Selection
These methods help us understand traditional statistical feature selection. In practical machine learning, we should also consider:
- Validation performance: Does removing a feature improve or maintain performance on unseen data?
- Domain knowledge: Is the feature important for the real-world problem?
- Overfitting: Does the model perform well on training data but poorly on new data?
Remember: More features do not always mean a better model. The goal is to find a useful set of features that helps the model make reliable predictions.
15. Complete Code
Now that we understand the individual steps, let's put everything together.
The following implementation uses a Scikit-learn Pipeline to handle preprocessing and model training safely.
# ============================================================
# 1. Importing libraries
# ============================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score
)
# ============================================================
# 2. Importing the dataset
# ============================================================
CSV_PATH = 'mlr-50-startups.csv' # edit for your environment (see Section 5)
dataset = pd.read_csv(CSV_PATH)
print(dataset.head())
dataset.info()
print(dataset.isnull().sum())
# ============================================================
# 3. Separating independent and dependent variables
# ============================================================
target_column = "Profit"
X = dataset.drop(columns=[target_column])
y = dataset[target_column]
print("X shape:", X.shape)
print("y shape:", y.shape)
# ============================================================
# 4. Splitting into training and test sets
# ============================================================
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=0
)
print("Train:", X_train.shape, y_train.shape)
print("Test: ", X_test.shape, y_test.shape)
# ============================================================
# 5. Encoding categorical data
# ============================================================
preprocessor = ColumnTransformer(
transformers=[
('state_encoder', OneHotEncoder(drop='first'), ['State'])
],
remainder='passthrough',
verbose_feature_names_out=False
)
# ============================================================
# 6. Building the Multiple Linear Regression model
# ============================================================
regressor = Pipeline(steps=[
('preprocessor', preprocessor),
('model', LinearRegression())
])
# ============================================================
# 7. Training the model
# ============================================================
regressor.fit(X_train, y_train)
# ============================================================
# 8. Inspecting the learned coefficients
# ============================================================
model = regressor.named_steps['model']
feature_names = regressor.named_steps['preprocessor'].get_feature_names_out()
print('Intercept:', model.intercept_)
print(pd.DataFrame({'Feature': feature_names, 'Coefficient': model.coef_}))
# ============================================================
# 9. Predicting the test set results
# ============================================================
y_pred = regressor.predict(X_test)
comparison = pd.DataFrame({
'Actual': y_test.values,
'Predicted': y_pred,
'Difference': y_test.values - y_pred
})
print(comparison)
# ============================================================
# 10. Evaluating the model
# ============================================================
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
print(f'MAE: {mae:,.2f}')
print(f'MSE: {mse:,.2f}')
print(f'RMSE: {rmse:,.2f}')
print(f'R²: {r2:.4f}')
# ============================================================
# 11. Visualizing actual vs. predicted values
# ============================================================
plt.figure(figsize=(7, 5))
plt.scatter(y_test, y_pred)
minimum = min(y_test.min(), y_pred.min())
maximum = max(y_test.max(), y_pred.max())
plt.plot([minimum, maximum], [minimum, maximum], linestyle='--')
plt.xlabel('Actual Profit')
plt.ylabel('Predicted Profit')
plt.title('Actual vs. Predicted Profit')
plt.show()16. Key Takeaways
- Multiple Linear Regression predicts a numerical value from several independent variables, with one coefficient per feature. Each coefficient is that feature's effect while holding the others constant.
- Independent variables (X) are the inputs; the dependent variable (y) is what we predict.
- Categorical variables must be converted to numbers. One-Hot Encoding creates binary dummy variables, which beat arbitrary integer labels.
- The Dummy Variable Trap occurs when all dummies are included alongside an intercept, creating perfect multicollinearity. Keep N − 1 dummies and interpret them against the reference category.
- Split first, then preprocess. A
Pipelinefits preprocessing on training data only, which prevents data leakage. - Ordinary Least Squares (OLS) finds coefficients by minimizing the sum of squared residuals.
fit()trains the model, andpredict()generates predictions.- Evaluate with several metrics: MAE, MSE, and R-squared help evaluate regression performance.
- Regression assumptions help us understand whether the model and its statistical results are appropriate.
- Feature selection helps us identify useful predictors and build simpler models.
The main idea: Simple Linear Regression learns the relationship between one feature and a target. Multiple Linear Regression extends that idea by learning how several features work together to predict the target.