Introduction to Regression along with prerequisites
I took Introduction to Artificial Intelligence class at my university given by Swati Ahirao ma’am. This blog covers prerequisites for regression, common terminologies used in regression, basics of Regression, gradient descent, ways of using categorical data in regression and regularization in regression.
Things to know before learning Regression,
1.Correlation is usually defined as a measure of the linear relationship between two quantitative variables . Correlation varies between -1 to 1.
[Image no longer available]
Credits: https://web.cs.ucla.edu/~mtgarip/images/pearson.png
2.Co-variance indicates how two variables are related. A positive covariance means the variables are positively related, while a negative covariance means the variables are inversely related.
[Image no longer available: Picture 10]
x = the independent variable
y = the dependent variable
n = number of data points in the sample
X ^ – = the mean of the independent variable _x
_Y ^ -= the mean of the dependent variable y
Correlation Vs Co-variance
Covariance measures variables that have different units of measurement. Using covariance, you could determine whether units were increasing or decreasing, but it was impossible to measure the degree to which the variables moved together because covariance does not use one standard unit of measurement. To measure the degree to which variables move together, you must use correlation.

To calculate the correlation coefficient for two variables, you would use the correlation formula,
[Image no longer available: Picture 4]
r(x,y) = correlation of the variables x and y
COV(x, y) = covariance of the variables x and y
sx = sample standard deviation of the random variable x
sy = sample standard deviation of the random variable y
What do you mean by Regression?
Regression is a supervised learning technique where Y (output) is continuous/quantitative.
Common methodologies used in Regression,
1.Independent variables: A change in the independent variable directly causes a change in the dependent variable. The effect on the dependent variable is measured and recorded.
2.Dependent variable: they are “dependent” on the independent variable. When you take data in an experiment, the dependent variable is the one being measured.

Credits: https://explorable.com/sites/default/files/independent-and-dependent-variable2.png
3.Target variable: the variable that is or should be the output.
4.Predictor variables: the variables that are mapped to the target variable through an empirical relation ship usually determined through the data.
5.Features: they are individual independent variables which acts as the input in the system. Prediction models uses these features to make predictions.
New features can also be extracted from old features using a method known as ‘feature engineering’. Features are also called attributes and the number of features is dimensions
6.Label: they are the final output or target Output. It can also be considered as the output classes. We obtain labels as output when provided with features as input.

7.Epochs: An epoch elapses when an entire dateset is passed forward and backward through the model exactly one time. If the entire dataset cannot be passed into the algorithm at once, it must be divided into mini-batches.
8.The number of iterations is equivalent to the number of batches needed to complete one epoch.
9.Under fitting: When our model can’t find the pattern in the data this maybe due to various reasons such as less data fed to the model for training.
10.Over fitting: When our model can find the pattern in our test data set and not in every data set this maybe due to too much details or features in the data set.
An example to explain under fitting and over fitting will be studying for a test,
- Under fitted students are the students who did not prepare that well for the test.
- Over fitted students are the students who basically memorized the entire study material given, but will have problems with questions outside the material given. As they did not understand the topic they simply mugged it up.
- Generalized/Robust students are the students who learned the concept from the study material and can solve similar questions outside from the study material.

11.Noise in a data set: the data points that don’t really represent the true properties of your data, but random chance.
12.Significance level: tells you how likely it is that your result has not occurred by chance.
Significance is expressed as a probability that your results have occurred by chance. You are generally looking for it to be less than a certain value.
13.Confidence level: A confidence interval (or confidence level) is a range of values that have a given probability that the true value lies within it.
Confidence intervals and significance are standard ways to show the quality of your statistical results. This will ensure that your data set and model is valid and reliable.
Simple Linear Regression
Linear regression is a statistical model that examines the linear relationship between two or more variables a dependent variable and independent variable(s).
Linear relationship basically means that when one (or more) independent variables increases (or decreases), the dependent variable increases (or decreases) too.
Simple Linear Regression predicts Y on the basis of a single Predictor variable X. It assumes that there is a linear relationship between X and Y
y = θ0+ θ1.X, where θ0 = Intercept at Y and θ1 = slope.
- θ0 and θ1 are known as model coefficients or parameters
- θ0 is the expected value of Y when X=0.
- Θ1 is the average increase in Y as per one unit increase in X.

Fitting Simple Linear Regression?
We fit Linear Regression model using training data and estimate model coefficients θ0 and θ1. We can predict future ŷ for the particular x as
- Y-hat ŷ = θ0 + θ1.X
- ŷ indicates prediction of Y on the basis of X=x
The most common approach of measuring closeness involves minimizing the least squares criterion.
Ordinary Least Square ?
Ordinary Least Squares is a method in Linear Regression for estimating the unknown parameters by creating a model which will minimize the sum of the squared errors between the observed data and the predicted one.
It works by making the total of the square of the errors as small as possible (that is why it is called “least squares”). So, when we square each of those errors and add them all up, the total is as small as possible.
[Image no longer available: Picture 7]
What do you mean by Hypothesis and Cost Function?
1.Hypothesis here represents probability of observing an outcome. We want a hypothesis that is bounded between zero and one, regression hypothesis line extends beyond this limits.
- h (hypothesis): A single hypothesis, e.g. an instance or specific candidate model that maps inputs to outputs and can be evaluated and used to make predictions.
- H (hypothesis set): A space of possible hypotheses for mapping inputs to outputs that can be searched, often constrained by the choice of the framing of the problem, the choice of model and the choice of model configuration.
[Image no longer available: Picture 3]
Here we represent h(x) as the hypothesis and j() as the cost function
2.Cost function: There’s a hypothesis function to be found. More precisely we have to find the parameters _θ_0 and _θ_1 so that the hypothesis function best fits the training data. By tweaking _θ_0 and _θ_1 we want to find a line that represents at best our data.
We need a function that will minimize the parameters over our data set. One common function that is often used is mean squared error, which measure the difference between the estimator (the data set) and the estimated value (the prediction).
To understand the math behind cost function ,
What do you mean by Gradient descent?
Let’s say you are at top of a hill and you want to reach the bottom of the hill. You have two options to reach the bottom or minima of the hill. You could either,
- Take small steps and cover small distance per step. This will ensure we reach the bottom, it might be time consuming but it guarantees reaching the bottom.
- Take a snowboard and cover large distances. This will ensure that you are really quick but it might make you miss the bottom and go further away from the bottom.
θj+1 := θj − α ∂/∂θj (J(θ)) where,
θj is the old position
θj+1 is the new position
α is the learning rate
∂/∂θj (J(θ)) is the gradient of function J for θj
[Image no longer available]
Credits: https://www.fromthegenesis.com/wp-content/uploads/2019/10/gd1510.png
Depending on the amount of data, we make a trade-off between the accuracy of the parameter update and the time it takes to perform an update.
- Batch Gradient Descent: It processes all the training examples for each iteration of gradient descent. But if the number of training examples is large, then batch gradient descent is computationally very expensive.
- Stochastic Gradient Descent: It processes 1 training example per iteration. Hence, the parameters are being updated after one iteration in which a single example has been processed. Hence it’s quite faster than batch gradient descent. But again, when the number of training examples is large, even then it processes only one example which can be additional overhead for the system as the number of iterations will be quite large.
- Mini Batch gradient descent: It works faster than both batch gradient descent and stochastic gradient descent. If the number of training examples is large, it is processed in batches of b training examples in one go. Thus, it works for larger training examples and that too with lesser number of iterations.
For gradient descent, the learning rate( size of steps ) is a hyper parameter. A parameter that is set before the learning process begins. These parameters are set in order to find ideal values of parameters, where we minimize the least squares error.
[Image no longer available: Picture 2]
Here alpha is the learning rate
A model converges when additional training will not improve the model. Gradient descent can converge to local minimum, event with the learning rate Alpha fixed. As we approach a local minimum , gradient descent will automatically take smaller steps. So, no need to decrease alpha over time.

If we substitute equation of linear regression into gradient descent algorithm, we could find the local minimum in the model. The equation should look similar to this,

Categorical Data?
Our Machine Learning Algorithms can’t process categorical data, so how should we handle categorical data?
We use a variety of encoding algorithms, let us consider this data set for an example

Let us consider how we will, use two algorithms to make categorical data work in regression
1.Label Encoding
- Take the unique values from categorical column and store them in a list.
- Sort list in ascending order.
- Replace the values of unique values in categorical column by their index positions in the list.
Hence A=0,B=1 and C=1

2.One hot Encoding
- Take the unique values from categorical column.
- Create a column for each unique categorical column

Multiple and Polynomial Linear regression?
Multiple linear regression is used to estimate the relationship between two or more independent variables and one dependent variable. You can use multiple linear regression when you want to know.

Credits:https://www.i2tutorials.com/wp-content/media/2019/11/Regressions-i2tutorials.png
Where y = the predicted value of the dependent variable, b0 = Intercept at Y and bn = the regression coefficient (bn) of the nth independent variable (Xn)
We have to find the degree of polynomial that fits our requirements if we choose a low degree of polynomial we might face under fitting but if we choose a high degree of polynomial we might face over fitting. So, we have to look for the correct power to generate a generalized model.
[Image no longer available: Picture 2]
How to solve the problem of over fitting(Regularization)?
The model will have a low accuracy if it is overfitting. This happens because your model is trying too hard to capture the noise in your training dataset.
Ridge regression discourages learning a more complex or flexible model, so as to avoid the risk of over fitting. If there is noise in the training data, then the estimated coefficients won’t generalize well to the future data. This is where regularization comes in and shrinks or regularizes these learned estimates towards zero.
[Image no longer available]
Credits: https://www.andreaperlato.com/img/ridge.png
It is a useful technique that can help in improving the accuracy of your regression models. Another example is Lasso regression.
For more information ,
- https://medium.com/swlh/gradient-descent-algorithm-3d3ba3823fd4
- https://online.stat.psu.edu/stat462/node/91/
- https://www.machinecurve.com/index.php/2020/11/02/machine-learning-error-bias-variance-and-irreducible-error-with-python/
- https://www.simplilearn.com/tutorials/machine-learning-tutorial/regularization-in-machine-learning
GitHub repository containing the code: https://github.com/kakabisht/AI_lab