Data scientists use many different kinds of machine learning algorithms to discover patterns in big data that lead to actionable insights. At a high level, these different algorithms can be classified into two groups based on the way they “learn” about data to make predictions: supervised and unsupervised learning.
What is Supervised Machine Learning?
Supervised Machine Learning: The majority of practical machine learning uses supervised learning.
Supervised learning is where you have input variables (x) and an output variable (Y) and you use an algorithm to learn the mapping function from the input to the output Y = f(X). The goal is to approximate the mapping function so well that when you have new input data (x) you can predict the output variables (Y) for that data.
Techniques of Supervised Machine Learning algorithms include linear and logistic regression, multi-class classification, Decision Trees, and support vector machines.
Supervised learning problems can be further grouped into Regression and Classification problems.
- Regression: Regression algorithms are used to predict a continuous numerical output. For example, a regression algorithm could be used to predict the price of a house based on its size, location, and other features.
- Classification: Classification algorithms are used to predict a categorical output. For example, a classification algorithm could be used to predict whether an email is spam or not.
Both problems have the goal of constructing a succinct model that can predict the value of the dependent attribute from the attribute variables. The difference between the two tasks is the fact that the dependent attribute is numerical for regression and categorical for classification.
Regression
Regression is a statistical approach used to analyze the relationship between a dependent variable (target variable) and one or more independent variables (predictor variables). The objective is to determine the most suitable function that characterizes the connection between these variables. It seeks to find the best-fitting model, which can be utilized to make predictions or draw conclusions.
It is a supervised learning technique, meaning that it requires labeled data to train a model. The model is then used to predict the value of the dependent variable for new, unseen data.
A regression problem is when the output variable is a real or continuous value, such as “salary” or “weight”. Many different models can be used, the simplest is the linear regression. It tries to fit data with the best hyper-plane which goes through the points.
Types of Regression
There are two main types of regression:
- Simple Regression
- Used to predict a continuous dependent variable based on a single independent variable.
- Simple linear regression should be used when there is only a single independent variable.
- Multiple Regression
- Used to predict a continuous dependent variable based on multiple independent variables.
- Multiple linear regression should be used when there are multiple independent variables
Regression Algorithms
There are many different types of regression algorithms, but some of the most common include:
- Linear regression: Linear regression is one of the simplest and most widely used statistical models. This assumes that there is a linear relationship between the independent and dependent variables. This means that the change in the dependent variable is proportional to the change in the independent variables.
- Polynomial regression: Polynomial regression is used to model nonlinear relationships between the dependent variable and the independent variables. It adds polynomial terms to the linear regression model to capture more complex relationships.
- Support vector regression (SVR): Support vector regression (SVR) is a type of regression algorithm that is based on the support vector machine (SVM) algorithm. SVM is a type of algorithm that is used for classification tasks, but it can also be used for regression tasks. SVR works by finding a hyperplane that minimizes the sum of the squared residuals between the predicted and actual values.
- Decision tree regression: Decision tree regression is a type of regression algorithm that builds a decision tree to predict the target value. A decision tree is a tree-like structure that consists of nodes and branches. Each node represents a decision, and each branch represents the outcome of that decision. The goal of decision tree regression is to build a tree that can accurately predict the target value for new data points.
- Ridge Regression: Ridge regression is a type of linear regression that is used to prevent overfitting. Overfitting occurs when the model learns the training data too well and is unable to generalize to new data
- Lasso regression: Lasso regression is another type of linear regression that is used to prevent overfitting. It does this by adding a penalty term to the loss function that forces the model to use some weights and to set others to zero.
- Random forest regression: Random forest regression is an ensemble method that combines multiple decision trees to predict the target value. Ensemble methods are a type of machine learning algorithm that combines multiple models to improve the performance of the overall model. Random forest regression works by building a large number of decision trees, each of which is trained on a different subset of the training data. The final prediction is made by averaging the predictions of all of the trees.
Characteristics of Regression
Here are the characteristics of the regression:
- Continuous Target Variable: Regression deals with predicting continuous target variables that represent numerical values. Examples include predicting house prices, forecasting sales figures, or estimating patient recovery times.
- Error Measurement: Regression models are evaluated based on their ability to minimize the error between the predicted and actual values of the target variable. Common error metrics include mean absolute error (MAE), mean squared error (MSE), and root mean squared error (RMSE).
- Model Complexity: Regression models range from simple linear models to more complex nonlinear models. The choice of model complexity depends on the complexity of the relationship between the input features and the target variable.
- Overfitting and Underfitting: Regression models are susceptible to overfitting and underfitting. Overfitting occurs when the model fits the training data too well and fails to generalize to new data. Underfitting occurs when the model fails to capture the underlying patterns in the data.
- Interpretability: The interpretability of regression models varies depending on the algorithm used. Simple linear models are highly interpretable, while more complex models may be more difficult to interpret.
Examples
Which of the following is a regression task?
- Predicting age of a person
- Predicting nationality of a person
- Predicting whether stock price of a company will increase tomorrow
- Predicting whether a document is related to sighting of UFOs?
Solution : Predicting age of a person (because it is a real value, predicting nationality is categorical, whether stock price will increase is discrete-yes/no answer, predicting whether a document is related to UFO is again discrete- a yes/no answer).
Let’s take an example of linear regression. We have a Housing data set and we want to predict the price of the house. Following is the python code for it.
Python3
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
import pandas as pd
df = pd.read_csv("Housing.csv")
Y = df['price']
X = df['lotsize']
X=X.values.reshape(len(X),1)
Y=Y.values.reshape(len(Y),1)
X_train = X[:-250]
X_test = X[-250:]
Y_train = Y[:-250]
Y_test = Y[-250:]
plt.scatter(X_test, Y_test, color='black')
plt.title('Test Data')
plt.xlabel('Size')
plt.ylabel('Price')
plt.xticks(())
plt.yticks(())
regr = linear_model.LinearRegression()
regr.fit(X_train, Y_train)
plt.plot(X_test, regr.predict(X_test), color='red',linewidth=3)
plt.show()
|
Output:

Here in this graph, we plot the test data. The red line indicates the best fit line for predicting the price.
To make an individual prediction using the linear regression model:
print( str(round(regr.predict(5000))) )
Regession Evaluation Metrics
Here are some most popular evaluation metrics for regression:
- Mean Absolute Error (MAE): The average absolute difference between the predicted and actual values of the target variable.
- Mean Squared Error (MSE): The average squared difference between the predicted and actual values of the target variable.
- Root Mean Squared Error (RMSE): The square root of the mean squared error.
- Huber Loss: A hybrid loss function that transitions from MAE to MSE for larger errors, providing balance between robustness and MSE’s sensitivity to outliers.
- Root Mean Square Logarithmic Error
- R2 – Score
Applications of Regression
- Predicting prices: For example, a regression model could be used to predict the price of a house based on its size, location, and other features.
- Forecasting trends: For example, a regression model could be used to forecast the sales of a product based on historical sales data and economic indicators.
- Identifying risk factors: For example, a regression model could be used to identify risk factors for heart disease based on patient data.
- Making decisions: For example, a regression model could be used to recommend which investment to buy based on market data.
Advantages of Regression
- Easy to understand and interpret
- Robust to outliers
- Can handle both linear and nonlinear relationships
Disadvantages of Regression
- Assumes linearity
- Sensitive to multicollinearity
- May not be suitable for highly complex relationships
Classification
Classification is a type of supervised machine learning algorithm that trains a model to predict a categorical class label for new data points. In other words, classification algorithms are used to assign new data points to one of a predefined set of categories.
Classification problem is when the output variable is a category, such as “red” or “blue” or “disease” and “no disease”. A classification model attempts to draw some conclusion from observed values. Given one or more inputs a classification model will try to predict the value of one or more outcomes.
For example, when filtering emails “spam” or “not spam”, when looking at transaction data, “fraudulent”, or “authorized”. In short Classification either predicts categorical class labels or classifies data (construct a model) based on the training set and the values (class labels) in classifying attributes and uses it in classifying new data. There are a number of classification models. Classification models include logistic regression, decision tree, random forest, gradient-boosted tree, multilayer perceptron, one-vs-rest, and Naive Bayes.
Types of Classification
There are several different types of classification in supervised machine learning :
- Binary Classification– In binary classification, the goal is to predict whether a new data point belongs to one of two classes. For example, a binary classification algorithm could be used to classify emails as spam or not spam, or to classify images of handwritten digits as belonging to either the digit 0 or the digit.
- Multiclass Classification– In multiclass classification, the goal is to predict which of several classes a new data point belongs to. For example, a multiclass classification algorithm could be used to classify images of handwritten digits as belonging to one of the digits 0-9, or to classify text documents as belonging to one of several different categories, such as news, entertainment, or sports.
- Multi-label Classification– In multi-label classification, the goal is to predict which of several labels a new data point belongs to. This is different from multiclass classification, where each data point can only belong to one class. For example, a multi-label classification algorithm could be used to classify images of animals as belonging to one or more of the categories cat, dog, bird, or fish.
- Imbalanced Classification– In imbalanced classification, the goal is to predict whether a new data point belongs to a minority class, even though there are many more examples of the majority class. For example, a medical diagnosis algorithm could be used to predict whether a patient has a rare disease, even though there are many more patients with common diseases.
Classification Algorithms
There are many different types of regression algorithms, but some of the most common include:
- Logistic regression: Logistic regression is a type of linear classification algorithm that uses a logistic function to predict the probability that a data point belongs to a particular category.
- Naive Bayes: Naive Bayes is a type of probabilistic classification algorithm that assumes that the features of a data point are independent of each other. This assumption is often violated in practice, but naive Bayes can still be a useful algorithm for many tasks.
- K-nearest neighbors (KNN): KNN is a type of non-parametric classification algorithm that classifies a new data point based on the majority class of its k nearest neighbors in the training data.
- Decision trees: Decision trees are a type of tree-structured classification algorithm that builds a decision tree to classify data points. Decision trees are easy to interpret and can be used to handle both categorical and numerical data.
- Support vector machines (SVMs): SVMs are a type of classification algorithm that finds a hyperplane that maximizes the margin between the two classes in the training data. SVMs are well-suited for tasks where the data is high-dimensional.
Characteristics of Classification
Here are the characteristics of the classification:
- Categorical Target Variable: Classification deals with predicting categorical target variables that represent discrete classes or labels. Examples include classifying emails as spam or not spam, predicting whether a patient has a high risk of heart disease, or identifying image objects.
- Accuracy and Error Rates: Classification models are evaluated based on their ability to correctly classify data points. Common metrics include accuracy, precision, recall, and F1-score.
- Model Complexity: Classification models range from simple linear classifiers to more complex nonlinear models. The choice of model complexity depends on the complexity of the relationship between the input features and the target variable.
- Overfitting and Underfitting: Classification models are susceptible to overfitting and underfitting. Overfitting occurs when the model learns the training data too well and fails to generalize to new data.
Examples
Which of the following is/are classification problem(s)?
- Predicting the gender of a person by his/her handwriting style
- Predicting house price based on area
- Predicting whether monsoon will be normal next year
- Predict the number of copies a music album will be sold next month
Solution : Predicting the gender of a person Predicting whether monsoon will be normal next year. The other two are regression.
As we discussed classification with some examples. Now there is an example of classification in which we are performing classification on the iris dataset using RandomForestClassifier in python. You can download the dataset from Here
Dataset Description
Title: Iris Plants Database
Attribute Information:
1. sepal length in cm
2. sepal width in cm
3. petal length in cm
4. petal width in cm
5. class:
-- Iris Setosa
-- Iris Versicolour
-- Iris Virginica
Missing Attribute Values: None
Class Distribution: 33.3% for each of 3 classes
Code:
Python3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
dataset = pd.read_csv(
'databases/iris/iris.data',sep= ',', header= None)
data = dataset.iloc[:, :]
print("Sum of NULL values in each column. ")
print(data.isnull().sum())
X = data.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size = 0.3, random_state = 0)
classifier=RandomForestClassifier()
classifier=classifier.fit(X_train,y_train)
predicted=classifier.predict(X_test)
print ('Confusion Matrix :')
print(confusion_matrix(y_test, predicted))
print ('Accuracy Score :',accuracy_score(y_test, predicted))
print ('Report : ')
print (classification_report(y_test, predicted))
|
Output:
Sum of NULL values in each column.
0 0
1 0
2 0
3 0
4 0
Confusion Matrix :
[[16 0 0]
[ 0 17 1]
[ 0 0 11]]
Accuracy Score : 97.7
Report :
precision recall f1-score support
0 1.00 1.00 1.00 16
1 1.00 0.94 0.97 18
2 0.92 1.00 0.96 11
avg/total 0.98 0.98 0.98 45
Classification Evaluation Metrics
Here are some popular evaluation metrics for classifications:
- Accuracy: The proportion of correctly classified data points.
- Precision: The proportion of positive predictions that are actually correct.
- Hinge Loss: A loss function used in support vector machines, measuring the distance between data points and the decision boundary.
- Log Loss: Another loss function for binary classification, similar to binary cross-entropy loss but with a logarithmic transformation.
- F1 score – The harmonic mean of precision and recall, balancing both measures.
- Logarithmic loss
- Area under Curve
- Confusion Matrix
Application of Classification
- Spam filtering: Identifying spam emails in an inbox
- Fraud detection: Detecting fraudulent transactions in financial data
- Medical diagnosis: Diagnosing diseases based on patient data
- Image recognition: Recognizing objects or scenes in images
- Recommender systems: Recommending products or services to users based on their past behavior
Advantages of Classification
- Easy to understand and interpret
- Can handle a wide variety of data types
- Can be used for both binary and multiclass classification tasks
Disadvantages of Classification
- Can be sensitive to outliers
- Requires a large amount of labeled data to train
- May not be suitable for very complex relationships between features and classes
Regression vs Classification
Here is a table summarizing the key differences between regression and classification:
|
Find the best-fitting function
|
Learn a decision boundary
|
|
Continuous
|
Discrete
|
|
Mean absolute error (MAE), root mean squared error (RMSE), mean squared error (MSE)
|
Accuracy, precision, recall, F1-score
|
|
Predicting numerical values
|
Classifying data into categories
|
|
Predicting house prices, forecasting sales trends, identifying risk factors for diseases, making financial decisions
|
Spam filtering, fraud detection, medical diagnosis, image recognition, recommender systems
|
|
Multicollinearity, outliers, high-dimensional data
|
Class imbalance, overfitting, underfitting
|
Conclusion
Regression and classification are two fundamental tasks in supervised machine learning. Regression is used to predict a continuous numerical value, while classification is used to predict a discrete categorical value. Both regression and classification can be used for a variety of tasks, but the choice of which one to use depends on the nature of the problem being solved.
Frequently Asked Question(FAQ’s)
1. What is regression and classification in machine learning?
Regression and classification are both supervised machine learning tasks that involve predicting a target variable based on a set of input features. However, they differ in the nature of the target variable:
- Regression: Predicts continuous target variables, representing numerical values.
- Classification: Predicts categorical target variables, representing discrete classes or labels.
2. What is the difference between decision tree and random forest?
Decision trees and random forests are both tree-based machine learning algorithms, but they differ in their construction and approach:
- Decision Tree: A single tree structure that recursively partitions the data based on input features until reaching terminal nodes representing predictions.
- Random Forest: An ensemble method that combines multiple decision trees, each trained on a random subset of the data, to improve overall performance and reduce overfitting.
3. What is the difference between classification and prediction?
Classification and prediction are often used interchangeably, but they have distinct meanings:
- Classification: A specific prediction task where the target variable is categorical, assigning data points to predefined classes.
- Prediction: A broader term encompassing various machine learning tasks, including classification and regression, where the goal is to predict an output variable based on input data.
4. Is Random Forest A classification or regression?
Random Forest can be used for both classification and regression tasks. The algorithm’s versatility allows it to handle both categorical and numerical target variables.
5. What is the difference between clustering and classification and regression?
Clustering and classification and regression are all machine learning tasks that involve analyzing data, but they differ in their objectives:
- Clustering: Unsupervised learning task that groups data points into clusters based on their similarities, without predefined classes.
- Classification: Supervised learning task that assigns data points to predefined classes based on labeled training data.
- Regression: Supervised learning task that predicts continuous target variables based on labeled training data.
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
04 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...