Machine Learning Concepts, Regression, 1
By Gencay
Published: 2024-02-10
URL: https://www.learnwithmeai.com/p/regression-tips-i-wish-i-knew-before

Welcome to another part of the #LearnAI series, where we go deeper into the realms of Machine Learning. Today, we're shifting our focus to a critical topic that every Data Scientist wishes they had grasped earlier: Regression.
In this one, we'll unpack the essentials of Regression. This article is tailored for those who aim to refine their understanding and application of Regression techniques, whether you're just starting out or looking to fill in the gaps.
By the end of this read, you'll develop a better understanding of Regression concepts. The things you’ll learn in this article can also be reached through our special GPT, LearnAIWithME. Let’s start!
The following special GPTs are ready for our paid subscribers.

\Image by Author\
Here is the link to LearnAIWithMe GPT.
Step 1: Overview of regression analysis.

Linear regression is a statistical method used to model the relationship between a dependent variable and one or more independent variables. The goal is to find a linear equation that best predicts the dependent variable from the independent variables.
Step 2: Most Used Regression Algorithms
Data We’ll Use
This air quality dataset can be downloaded from here.
Use this prompt with ChatGPT to see the explanation of this dataset after you’ve attached it to the GPT.
This explanation should be in bullet points, but it should be short and concise
Here is the output.

Let’s see the code to read this dataset in your Jupyter Notebook.
import pandas as pd
df = pd.read_csv("AirQualityUCI.csv", delimiter=';')
df.head()
Here is the output.

Now, before going further, let’s start with the basics of Linear Regression and apply regression algorithms to this data.
Linear Regression

\Result of our Model that we apply at the end.\
To apply linear regression to the air quality dataset, we'll predict the concentration of Benzene (C6H6) based on the sensor readings from PT08.S2 (NMHC). This application will help us understand the effectiveness of sensor readings in estimating pollutant concentrations.
Where Linear Regression Can Be Used?
Linear regression can be used in various fields, such as:
- Economics to predict future economic trends based on current data.
- Medicine to predict health outcomes based on patient metrics.
- Environmental science to model pollution levels based on various factors.
- Real estate to estimate property values based on features like location, size, and condition.
Application of Linear Regression
Let's proceed with the analysis:
- Preprocess the dataset: Handle missing values and convert data types if necessary.
- Split the dataset into training and testing sets.
- Fit a linear regression model using PT08.S2 (NMHC) as the independent variable and C6H6(GT) as the dependent variable.
- Evaluate the model's performance using appropriate metrics.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np
# Replace commas with dots and convert to float for all columns that require it
for column in ['CO(GT)', 'PT08.S1(CO)', 'NMHC(GT)', 'C6H6(GT)', 'PT08.S2(NMHC)', 'NOx(GT)', 'PT08.S3(NOx)', 'NO2(GT)', 'PT08.S4(NO2)', 'PT08.S5(O3)', 'T', 'RH', 'AH']:
if df[column].dtype == object:
df[column] = df[column].str.replace(',', '.').astype(float)
# Handle missing values (-200 is used for missing values)
df.replace(-200, np.nan, inplace=True)
df.dropna(subset=['C6H6(GT)', 'PT08.S2(NMHC)'], inplace=True)
# Define independent variable (X) and dependent variable (y)
X = df[['PT08.S2(NMHC)']]
y = df['C6H6(GT)']
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Fit a linear regression model
lr_model = LinearRegression()
lr_model.fit(X_train, y_train)
# Predict on the test set
y_pred = lr_model.predict(X_test)
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("Mean Squared Error:", mse)
print("R-Squared:", r2)
Here is the output.

The MSE is very low, indicating that the model's predictions are very close to average data points. The R² value is close to 1, which suggests that the model explains approximately 96.5% of the variance in the target variable. This is a strong indication that the model fits the data well.
However, a high R² value like this could also suggest that the model is overfitting, especially if this result is not consistent across different subsets of data or when applied to a validation set. Overfitting means the model is too closely tailored to the specific data it was trained on, and it may not perform as well on new, unseen data.
Decision Tree Regression

Decision Tree can be used to do regression and classification.
Where Decision Tree Regression Can Be Used?
Decision Tree Regression can be useful in a variety of contexts:
- Complex Non-Linear Relationships: Decision trees can model these effectively when the relationship between the independent and dependent variables is non-linear and complex.
- Variable Interactions: They can capture the interactions between different variables without explicitly creating those interactions in the feature set.
- Easy Interpretability: The model can be visualized and understood by non-experts, which is valuable for business decisions.
- Non-Parametric Method: They don’t require the data to follow a particular distribution.
Application of Decision Tree Regression
To apply Decision Tree Regression to the air quality dataset:
- We create a Decision Tree Regressor model.
- We train (or 'fit') this model on our training data.
- We make predictions on our test data.
- We evaluate the performance of the model using metrics like MSE and R².
Let’s see the code.
from sklearn.tree import DecisionTreeRegressor
# Create a Decision Tree Regression model
dt_model = DecisionTreeRegressor(random_state=42)
# Fit the model to the training data
dt_model.fit(X_train, y_train)
# Predict on the test set
y_dt_pred = dt_model.predict(X_test)
# Evaluate the model
dt_mse = mean_squared_error(y_test, y_dt_pred)
dt_r2 = r2_score(y_test, y_dt_pred)
print("Decision Tree Regression MSE:", dt_mse)
print("Decision Tree Regression R²:", dt_r2)
Here is the output.

This model yielded an MSE of approximately 0.0017 and an R² of nearly 1, which are both very good results. However, due to the risk of overfitting, it would be prudent to perform further evaluation, such as cross-validation, or to visualize the tree to understand better how it's making decisions.
Random Forest Regression
Random Forest Regression utilizes an ensemble of decision trees to improve prediction accuracy. It combines multiple decision trees to form a "forest," enhancing the model's performance by reducing overfitting.
Where Random Forest Regression Can Be Used?
Random Forest Regression is a versatile machine-learning method that can be used for various applications:
- Predictive Maintenance: It can predict the time until the failure of machines or components, which is crucial in manufacturing and production.
- Finance: In finance, it can be used to predict stock prices and market trends by incorporating numerous factors and indicators.
- Medical Field: It can help in predicting disease progression based on patient data and has been used in genomics to predict the effects of genetic variations.
- Real Estate: It can estimate property prices based on various features, like location, size, and condition, by considering complex interactions between features.
Application of Random Forest Regression
To apply Random Forest Regression to the air quality dataset:
- We instantiate a Random Forest Regressor.
- We train this ensemble model on our data.
- We make predictions using this model.
- We assess the model's performance using evaluation metrics.
Here's the code to apply Random Forest Regression to our dataset:
from sklearn.ensemble import RandomForestRegressor
# Create a Random Forest Regression model
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
# Fit the model to the training data
rf_model.fit(X_train, y_train)
# Predict on the test set
y_rf_pred = rf_model.predict(X_test)
# Evaluate the model
rf_mse = mean_squared_error(y_test, y_rf_pred)
rf_r2 = r2_score(y_test, y_rf_pred)
print("Random Forest Regression MSE:", rf_mse)
print("Random Forest Regression R²:", rf_r2)
Here is the output.

These results indicate that the Random Forest model is performing exceptionally well on the test data. The MSE is very low, suggesting the predictions are very close to the actual values. Similarly, the R² is extremely close to 1, which implies the model can explain nearly all the variance in the target variable.
However, as with the Decision Tree Regression, such high performance could signal overfitting, especially if the model has not been validated on an independent dataset.
Regression Evaluation Metrics

Step 3: Initial Steps in Regression
Data Preprocessing
Before applying any regression model, it's important to prepare the data:
- Handle Missing Values: Replace or remove missing values in the dataset.
- Data Transformation: Convert categorical variables to numerical values through encoding, normalizing, or scaling numerical values if required.
- Outlier Detection: Identify and handle outliers as they can skew the regression model results.
Feature Selection and Engineering
Selecting the right features and engineering new ones can significantly impact model performance:
- Correlation Analysis: Identify and select features that have a strong correlation with the target variable.
- Dimensionality Reduction: Use techniques like PCA to reduce the number of features while retaining variance.
- Feature Creation: Combine features or create new ones that might capture more complex relationships within the data.
Splitting Data for Training and Testing
Properly evaluating the performance of a regression model involves splitting the dataset:
- Training Set: A subset of the data used to train the model.
- Testing Set: A separate subset used to evaluate the model's performance to ensure it generalizes well to new data.
- Validation Set (if necessary): Another subset used to fine-tune the model's hyperparameters before the final evaluation of the test set.
Typically, you might use a 70/30 or 80/20 split for training and testing. Cross-validation, like k-fold cross-validation, can also be used to ensure that the model's performance is consistent across different subsets of the data.
Here are the steps for building an advanced regression algorithm.

How to Learn These By Using LearnAIWithME GPT
Now, let’s use the following prompt to learn the same things you learned in this one.
Let's start with regression. Give me the curriculum of it and start with the first part.

It will continue; let’s use this prompt to learn what you see in this article.
Let's start with 1.

Of course, if you want to see further steps or evaluation metrics, take a screenshot of these and send them back to our GPT to learn them too.
Final Thoughts
Now, if you see the subtitle of this article,
Machine Learning Concepts, Regression, Part: 1
You may have a question on your mind about it, so you can use our GPT to find answers to your questions.
Thanks for reading this article!