Module - 3
Module - 3
Pre-processing refers to the transformations applied to our data before feeding it to the
algorithm. Data Preprocessing is a technique that is used to convert the raw data into a
clean data set. In other words, whenever the data is gathered from different sources it is
collected in raw format which is not feasible for the analysis.
Library which contains Mathematical functions and is used for scientific computing while
respectively.
Step 2: Importing the Dataset
Data sets are available in .csv format. A CSV file stores tabular data in plain text. Each line of
the file is a data record. We use the read_csv method of the pandas library to read a local
After carefully inspecting our dataset, we are going to create a matrix of features in our
dataset (X) and create a dependent vector (Y) with their respective observations. To read the
columns, we will use iloc of pandas (used to fix the indexes for selection) which takes two
The data we get is rarely homogenous. Sometimes data can be missing and it needs to be
handled so that it does not reduce the performance of our machine learning model.
To do this we need to replace the missing data by the Mean or Median of the entire column.
For this we will be using the [Link] Library which contains a class called
Imputer which will help us in taking care of our missing data.
from [Link] import Imputer
imputer = SimpleImputer(missing_values = "NaN", strategy = "mean", axis = 0)
Our object name is imputer. The Imputer class can take parameters like :
1. missing_values : It is the placeholder for the missing values. All occurrences of
missing_values will be imputed. We can give it an integer or “NaN” for it to find missing
values.
2. strategy : It is the imputation strategy — If “mean”, then replace missing values using
the mean along the axis (Column). Other strategies include “median” and
“most_frequent”.
3. axis : It can be assigned 0 or 1, 0 to impute along columns and 1 to impute along rows.
Now replacing the missing values with the mean of the column by using transform method.
X[:, 1:3] = [Link](X[:, 1:3])
Any variable that is not quantitative is categorical. Examples include Hair color, gender, field
One hot encoding transforms categorical features to a format that works better with
fromsklearn.model_selectionimporttrain_test_split
Now to build our training and test sets, we will create 4 sets —
1. X_train (training part of the matrix of features),
2. X_test (test part of the matrix of features),
3. Y_train (training part of the dependent variables associated with
4. the X train sets, and therefore also the same indices) ,
5. Y_test (test part of the dependent variables associated with the X test sets, and
therefore also the same indices).
We will assign to them the test_train_split, which takes the parameters — arrays (X and Y),
Further we will transform our X_test set while we will need to fit as well as transform our
X_train set.
The transform function will transform all the data to a same standardized scale.
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
Regression
Regression analysis is a statistical method to model the relationship
between a dependent (target) and independent (predictor) variables with
one or more independent variables. More specifically, Regression analysis
helps us to understand how the value of the dependent variable is
changing corresponding to an independent variable when other
independent variables are held fixed. It predicts continuous/real values
such as temperature, age, salary, price, etc.
which helps in finding the correlation between variables and enables us to predict the
continuous output variable based on the one or more predictor variables. It is mainly used
for prediction, forecasting, time series modeling, and determining
the causal-effect relationship between variables.
In Regression, we plot a graph between the variables which best fits the
given datapoints, using this plot, the machine learning model can make
predictions about the data. In simple words, "Regression shows a line
or curve that passes through all the datapoints on target-
predictor graph in such a way that the vertical distance between
the datapoints and the regression line is minimum." The distance
between datapoints and line tells whether a model has captured a strong
relationship or not.
Types of Regression
There are various types of regressions which are used in data science and
machine learning. Each type has its own importance on different
scenarios, but at the core, all the regression methods analyze the effect of
the independent variable on dependent variables. Here we are discussing
some important types of regression which are given below:
o Linear Regression
o Logistic Regression
o Polynomial Regression
o Support Vector Regression
o Decision Tree Regression
o Random Forest Regression
o Ridge Regression
o Lasso Regression:
Simple Linear Regression
Simple Linear Regression is a type of Regression algorithms that models
the relationship between a dependent variable and a single independent
variable. The relationship shown by a Simple Linear Regression model is
linear or a sloped straight line, hence it is called Simple Linear Regression.
y= 𝛽₀ + 𝛽₁𝑥₁ + ⋯ + 𝛽ᵣ𝑥ᵣ + 𝜀
Where,
This equation is the regression equation. 𝛽₀, 𝛽₁, …, 𝛽ᵣ are
the regression coefficients, and 𝜀 is the random error.
Here we are taking a dataset that has two variables: salary (dependent
variable) and experience (Independent variable). The goals of this
problem is:
we will create a Simple Linear Regression model to find out the best fitting
line for representing the relationship between these two variables.
The first step for creating the Simple Linear Regression model is data pre-
processing
First, we will import the three important libraries, which will help us for
loading the dataset, plotting the graphs, and creating the Simple Linear
Regression model.
import numpy as nm
import [Link] as mtp
import pandas as pd
data_set= pd.read_csv('Salary_Data.csv')
The above output shows the dataset, which has two variables: Salary and
Experience.
After that, we need to extract the dependent and independent
variables from the given dataset. The independent variable is years of
experience, and the dependent variable is salary. Below is code for it:
x= data_set.iloc[:, :-1].values
y= data_set.iloc[:, 1].values
In the above lines of code, for x variable, we have taken -1 value since we
want to remove the last column from the dataset. For y variable, we have
taken 1 value as a parameter, since we want to extract the second
column and indexing starts from the zero.
In the above output image, we can see the X (independent) variable and Y
(dependent) variable has been extracted from the given dataset.
Next, we will split both variables into the test set and training set. We
have 30 observations, so we will take 20 observations for the training set
and 10 observations for the test set. We are splitting our dataset so that
we can train our model using a training dataset and then test the model
using a test dataset. The code for this is given below:
By executing the above code, we will get x-test, x-train and y-test, y-train
dataset. Consider the below images:
Test-dataset:
Training Dataset:
Now the second step is to fit our model to the training dataset. To do so,
we will import the LinearRegression class of the linear_model library
from the scikit learn. After importing the class, we are going to create an
object of the class named as a regressor. The code for this is given
below:
In the above code, we have used a fit() method to fit our Simple Linear
Regression object to the training set. In the fit() function, we have passed
the x_train and y_train, which is our training dataset for the dependent
and an independent variable. We have fitted our regressor object to the
training set so that the model can easily learn the correlations between
the predictor and target variables. After executing the above lines of
code, we will get the below output.
Output:
Out[7]: LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None,
normalize=False)
We will create a prediction vector y_pred, and x_pred, which will contain
predictions of test dataset, and prediction of training set respectively.
On executing the above lines of code, two variables named y_pred and
x_pred will generate in the variable explorer options that contain salary
predictions for the training set and test set.
Output:
You can check the variable by clicking on the variable explorer option in
the IDE, and also compare the result by comparing values from y_pred
and y_test. By comparing these values, we can check how good our model
is performing.
Now in this step, we will visualize the training set result. To do so, we will
use the scatter() function of the pyplot library, which we have already
imported in the pre-processing step. The scatter () function will create a
scatter plot of observations.
In the x-axis, we will plot the Years of Experience of employees and on the
y-axis, salary of employees. In the function, we will pass the real values of
training set, which means a year of experience x_train, training set of
Salaries y_train, and color of the observations. Here we are taking a green
color for the observation, but it can be any color as per the choice.
Now, we need to plot the regression line, so for this, we will use the plot()
function of the pyplot library. In this function, we will pass the years of
experience for training set, predicted salary for training set x_pred, and
color of the line.
Next, we will give the title for the plot. So here, we will use
the title() function of the pyplot library and pass the name ("Salary vs
Experience (Training Dataset)".
After that, we will assign labels for x-axis and y-axis using xlabel() and
ylabel() function.
Finally, we will represent all above things in a graph using show(). The
code is given below:
Output:
By executing the above lines of code, we will get the below graph plot as
an output.
In the above plot, we can see the real values observations in green dots
and predicted values are covered by the red regression line. The
regression line shows a correlation between the dependent and
independent variable.
The good fit of the line can be observed by calculating the difference
between actual values and predicted values. But as we can see in the
above plot, most of the observations are close to the regression
line, hence our model is good for the training set.
Here we are also changing the color of observations and regression line to
differentiate between the two plots, but it is optional.
Output:
By executing the above line of code, we will get the output as:
In the above plot, there are observations given by the blue color, and
prediction is given by the red regression line. As we can see, most of the
observations are close to the regression line, hence we can say our Simple
Linear Regression is a good model and able to make good predictions.
Multiple Linear Regression
Multiple Linear Regression is an extension of Simple Linear regression as it
takes more than one predictor variable to predict the response variable.
Multiple Linear Regression is one of the important regression algorithms which models
the linear relationship between a single dependent continuous variable and more than one
independent variable.
Example:
MLR equation:
In Multiple Linear Regression, the target variable(Y) is a linear
combination of multiple predictor variables x 1, x2, x3, ...,xn. Since it is an
enhancement of Simple Linear Regression, so the same is applied for the
multiple linear regression equation, the equation becomes:
Where,
Y= Output/Response variable
Since we need to find the Profit, so it is the dependent variable, and the
other four variables are independent variables. Below are the main steps
of deploying the MLR model:
, which we have already discussed in this tutorial. This process contains the below steps:
o Importing libraries: Firstly, we will import the library which will
help in building the model. Below is the code for it:
# importing libraries
import numpy as nm
import [Link] as mtp
import pandas as pd
In above output, we can clearly see that there are five variables, in which
four variables are continuous and one is categorical variable.
x= data_set.iloc[:, :-1].values
y= data_set.iloc[:, 4].values
Out[5]:
As we can see in the above output, the last column contains categorical
variables which are not suitable to apply directly for fitting the model. So
we need to encode this variable.
# Country column
ct = ColumnTransformer([("State", OneHotEncoder(), [3])], remainder =
'passthrough')
x = ct.fit_transform(x)
The above code will split our dataset into a training set and test set.
Output: The above code will split the dataset into training set and test
set. You can check the output by clicking on the variable explorer option
given in Spyder IDE. The test set and training set will look like the below
image:
Output:
Now, we have successfully trained our model using the training dataset. In
the next step, we will test the performance of the model using the test
dataset.
n the above output, we have predicted result set and test set. We can
check model performance by comparing these two value index by index.
For example, the first index has a predicted value of 103015$ profit and
test/real value of 103282$ profit. The difference is only of 267$, which is
a good prediction, so, finally, our model is completed here.
o We can also check the score for training dataset and test dataset.
Below is the code for it:
The above score tells that our model is 95% accurate with the
training dataset and 93% accurate with the test dataset.
y = b0+b1x .........(a)
When we compare the above three equations, we can clearly see that all
three equations are Polynomial equations but differ by the degree of
variables. The Simple and Multiple Linear equations are also Polynomial
equations with a single degree, and the Polynomial regression equation is
Linear equation with the nth degree. So if we add a degree to our linear
equations, then it will be converted into Polynomial Linear equations.
o Data Pre-processing
o Build a Linear Regression model and fit it to the dataset
o Build a Polynomial Regression model and fit it to the dataset
o Visualize the result for Linear Regression and Polynomial Regression
model.
o Predicting the output.
Note: Here, we will build the Linear regression model as well as Polynomial Regression
to see the results between the predictions. And Linear regression model is for reference.
# importing libraries
import numpy as nm
import [Link] as mtp
import pandas as pd
#importing datasets
data_set= pd.read_csv('Position_Salaries.csv')
Explanation:
Output:
As we can see in the above output, there are three columns present
(Positions, Levels, and Salaries). But we are only considering two columns
because Positions are equivalent to the levels or may be seen as the
encoded form of Positions.
Here we will predict the output for level 6.5 because the candidate has
4+ years' experience as a regional manager, so he must be somewhere
between levels 7 and 6.
Now, we will build and fit the Linear regression model to the dataset. In
building polynomial regression, we will take the Linear regression model
as reference and compare both the results. The code is given below:
Output:
Now we will build the Polynomial Regression model, but it will be a little
different from the Simple Linear model. Because here we will
use PolynomialFeatures class of preprocessing library. We are using
this class to add some extra features to our dataset.
After executing the code, we will get another matrix x_poly, which can be
seen under the variable explorer option:
Next, we have used another LinearRegression object, namely lin_reg_2,
to fit our x_poly vector to the linear model.
Output:
Now we will visualize the result for Linear regression model as we did in
Simple Linear Regression. Below is the code for it:
Output:
In the above output image, we can clearly see that the regression line is
so far from the datasets. Predictions are in a red straight line, and blue
points are actual values. If we consider this output to predict the value of
CEO, it will give a salary of approx. 600000$, which is far away from the
real value.
So we need a curved model to fit the dataset other than a straight line.
Here we will visualize the result of Polynomial regression model, code for
which is little different from the above model.
Output:
As we can see in the above output image, the predictions are close to the
real values. The above plot will vary as we will change the degree.
For degree= 3:
SO as we can see here in the above output image, the predicted salary for
level 6.5 is near to 170K$-190k$, which seems that future employee is
saying the truth about his salary.
Degree= 4: Let's again change the degree to 4, and now will get the
most accurate plot. Hence we can get more accurate results by increasing
the degree of Polynomial.
Predicting the final result with the Linear Regression model:
Now, we will predict the final output using the Linear regression model to
see whether an employee is saying truth or bluff. So, for this, we will use
the predict() method and will pass the value 6.5. Below is the code for it:
lin_pred = lin_regs.predict([[6.5]])
print(lin_pred)
Output:
[330378.78787879]
Now, we will predict the final output using the Polynomial Regression
model to compare with Linear model. Below is the code for it:
poly_pred = lin_reg_2.predict(poly_regs.fit_transform([[6.5]]))
print(poly_pred)
Output:
[158862.45265153]
Kernel: The function used to map lower-dimensional data into higher dimensional data.
Hyper Plane: The separation line between the data classes. For a Support Vector Regression
problem, a hyperplane is a line that will help us predict the continuous value or target value.
Decision Boundary line: The boundary lines are essentially the decision boundaries of the
hyperplane. The support vectors can be on the Boundary lines or outside it. The best fit line
is determined on the basis of the hyperplane having the maximum number of points inside
its boundary line.
Support Vectors are the data points that are closest to the decision boundary. The distance
of the points is minimum or least.
Implementing SVR in Python
Data preprocessing
Output:
The above dataset contains ten instances. The significant feature in this dataset is
the Level column. The Position column is just a description of the Level column, and
therefore, it adds no value to our analysis. Therefore, we will separate the dataset into a set
of features and study variables.
Variable separation:
It’s seen from the output above that the y_p variable is a vector, i.e., a 1D array.
Therefore, if we implement a model on this data, the study variable will dominate the
feature variable, such that its contribution to the model will be neglected.
Due to this, we will have to scale this study variable to the same range as the scaled study
variable.
Due to this, we have to reshape our y_p variable from 1D to 2D. The code below does this
for us:
y_p = y_p.reshape(-1,1)
Output:
[[ 45000]
[ 50000]
[ 60000]
[ 80000]
[ 110000]
[ 150000]
[ 200000]
[ 300000]
[ 500000]
[1000000]]
From the above output, y_p was successfully reshaped into a 2D array.
Now, import the StandardScalar class and scale up the X_l and y_p variables separately as
shown:
Let’s simultaneously print and check if our two variables were scaled.
print("Scaled X_l:")
print(X_l)
print("Scaled y_p:")
print(y_p)
As we can see from the obtained output, both variables were scaled within the range -
3 and +3.
However, before we can do so, we will first visualize the data to know the nature of the SVR
model that best fits it. So, let us create a scatter plot of our two variables.
Due to this, we cannot use the linear SVR to model this data. Therefore, to capture this
relationship better, we will use the SVR with the kernel functions.
Implementing SVR
To implement our model, first, we need to import it from the scikit-learn and create an
object to itself.
Since we declared our data to be non-linear, we will pass it to a kernel called the Radial
Basis function (RBF) kernel.
After declaring the kernel function, we will fit our data on the object. The following program
performs these rules:
Since the model is now ready, we can use it and make predictions as shown:
A=[Link](StdS_X.transform([[6.5]]))
print(A)
Output:
array([-0.27861589])
As we can see, the model prediction values are for the scaled study variable. But, the
required value for the business is the output of the unscaled data. So, we need to get back
to the real scale of the study variable.
So, for any predicted value to fit within such a new dimension of the study variable, it must
be transformed from 1D to 2D; otherwise, we will get an error.
# Convert A to 2D
A = [Link](-1,1)
print(A)
Output:
array([[-0.27861589]])
It is clear from the output above is a 2D array. Using the inverse_transform() function, we
can convert it to an unscaled value in the original dataset as shown:
Output:
array([[170370.0204065]])
However, if we were to run a polynomial regression on this data and predict the same
values, we would have obtained the predicted values as 158862.45265155, which is only
fixed on the curve. With the Support Vector regression, this is not the case. So there is that
allowance given to the model to make the best prediction.
Code optimization
We can optimize the above operation into a single line of code as below.
B_pred = StdS_y.inverse_transform([Link](StdS_X.transform([[6.5]])).reshape(-
1,1))
print(B_pred)
Output:
array([[170370.0204065]])
Since we now know how to implement and make predictions using the SVR model, the final
thing we will do is to visualize our model.
Output:
Decision Tree Regression
Decision Tree
A decision tree is one of the most frequently used Machine Learning algorithms for
solving regression as well as classification problems. As the name suggests, the algorithm
uses a tree-like model of decisions to either predict the target value (regression) or predict
the target class (classification).
Root Node: This represents the topmost node of the tree that represents the whole
data points.
Decision Node: They are the nodes that are further split into sub-nodes, i.e., this node
that is split is called a decision node.
Leaf / Terminal Node: Nodes that do not split are called Leaf or Terminal nodes. These
nodes are often the final result of the tree.
Parent and Child Node: A node, which is divided into sub-nodes is called a parent node
of sub-nodes whereas sub-nodes are the child of the parent node. In the figure above,
the decision node is the parent of the terminal nodes (child).
Pruning: Removing sub-nodes of a decision node is called pruning. Pruning is often done
in decision trees to prevent overfitting.
dataset =[Link](
[['Asset Flip', 100, 1000],
['Text Based', 500, 3000],
['Visual Novel', 1500, 5000],
['2D Pixel Art', 3500, 8000],
['2D Vector Art', 5000, 6500],
['Strategy', 6000, 7000],
['First Person Shooter', 8000, 15000],
['Simulator', 9500, 20000],
['Racing', 12000, 21000],
['RPG', 14000, 25000],
['Sandbox', 15500, 27000],
['Open-World', 16500, 30000],
['MMOFPS', 25000, 52000],
['MMORPG', 30000, 80000]
])
Step 4: Select all of the rows and column 2 from the dataset to “y”.
# select all rows by : and column 2
y =[Link][:, 2].astype(int)
print(y)
Output:
[ 1000 3000 5000 8000 6500 7000 15000 20000 21000 25000 27000 30000 52000 80000]
Output:
DecisionTreeRegressor(ccp_alpha=0.0, criterion='mse', max_depth=None,
max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort='deprecated',
random_state=0, splitter='best')
Step 8: The tree is finally exported and shown in the TREE STRUCTURE below, visualized