The Wayback Machine - https://web.archive.org/web/20241122214824/https://www.geeksforgeeks.org/getting-started-with-classification/
Open In App

Getting started with Classification

Last Updated : 24 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

As the name suggests, Classification is the task of “classifying things” into sub-categories. Classification is part of supervised machine learning in which we put labeled data for training.

The article serves as a comprehensive guide to understanding and applying classification techniques, highlighting their significance and practical implications.

What is Supervised Machine Learning?

Supervised Machine 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.

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.

Machine Learning for classification

Classification is a process of categorizing data or objects into predefined classes or categories based on their features or attributes.

Machine Learning classification is a type of supervised learning technique where an algorithm is trained on a labeled dataset to predict the class or category of new, unseen data.

The main objective of classification machine learning is to build a model that can accurately assign a label or category to a new observation based on its features.

For example, a classification model might be trained on a dataset of images labeled as either dogs or cats and then used to predict the class of new, unseen images of dogs or cats based on their features such as color, texture, and shape.

Classification Types

There are two main classification types in machine learning:

Binary Classification

In binary classification, the goal is to classify the input into one of two classes or categories. Example – On the basis of the given health conditions of a person, we have to determine whether the person has a certain disease or not.

Multiclass Classification

In multi-class classification, the goal is to classify the input into one of several classes or categories. For Example – On the basis of data about different species of flowers, we have to determine which specie our observation belongs to.

Binary vs Multi class classification -Geeksforgeeks

Binary vs Multi class classification

Other categories of classification involves:

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 various types of classifiers algorithms. Some of them are : 

Linear Classifiers

Linear models create a linear decision boundary between classes. They are simple and computationally efficient. Some of the linear classification models are as follows: 

Non-linear Classifiers

Non-linear models create a non-linear decision boundary between classes. They can capture more complex relationships between the input features and the target variable. Some of the non-linear classification models are as follows: 

Learners in Classifications Algorithm

In machine learning, classification learners can also be classified as either “lazy” or “eager” learners.

  • Lazy Learners: Lazy Learners are also known as instance-based learners, lazy learners do not learn a model during the training phase. Instead, they simply store the training data and use it to classify new instances at prediction time. It is very fast at prediction time because it does not require computations during the predictions. it is less effective in high-dimensional spaces or when the number of training instances is large. Examples of lazy learners include k-nearest neighbors and case-based reasoning.
  • Eager Learners: Eager Learners are also known as model-based learners, eager learners learn a model from the training data during the training phase and use this model to classify new instances at prediction time. It is more effective in high-dimensional spaces having large training datasets. Examples of eager learners include decision trees, random forests, and support vector machines.

Classification Models in Machine Learning

Evaluating a classification model is an important step in machine learning, as it helps to assess the performance and generalization ability of the model on new, unseen data. There are several metrics and techniques that can be used to evaluate a classification model, depending on the specific problem and requirements. Here are some commonly used evaluation metrics:

  • Classification Accuracy: The proportion of correctly classified instances over the total number of instances in the test set. It is a simple and intuitive metric but can be misleading in imbalanced datasets where the majority class dominates the accuracy score.
  • Confusion matrix: A table that shows the number of true positives, true negatives, false positives, and false negatives for each class, which can be used to calculate various evaluation metrics.
  • Precision and Recall: Precision measures the proportion of true positives over the total number of predicted positives, while recall measures the proportion of true positives over the total number of actual positives. These metrics are useful in scenarios where one class is more important than the other, or when there is a trade-off between false positives and false negatives.
  • F1-Score: The harmonic mean of precision and recall, calculated as 2 x (precision x recall) / (precision + recall). It is a useful metric for imbalanced datasets where both precision and recall are important.
  • ROC curve and AUC: The Receiver Operating Characteristic (ROC) curve is a plot of the true positive rate (recall) against the false positive rate (1-specificity) for different threshold values of the classifier’s decision function. The Area Under the Curve (AUC) measures the overall performance of the classifier, with values ranging from 0.5 (random guessing) to 1 (perfect classification).
  • Cross-validation: A technique that divides the data into multiple folds and trains the model on each fold while testing on the others, to obtain a more robust estimate of the model’s performance.

It is important to choose the appropriate evaluation metric(s) based on the specific problem and requirements, and to avoid overfitting by evaluating the model on independent test data.

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.

How does Classification Machine Learning Work?

The basic idea behind classification is to train a model on a labeled dataset, where the input data is associated with their corresponding output labels, to learn the patterns and relationships between the input data and output labels. Once the model is trained, it can be used to predict the output labels for new unseen data.

classification-task

Classification Machine Learning

The classification process typically involves the following steps:

Understanding the problem

Before getting started with classification, it is important to understand the problem you are trying to solve. What are the class labels you are trying to predict? What is the relationship between the input data and the class labels?

Suppose we have to predict whether a patient has a certain disease or not, on the basis of 7 independent variables, called features. This means, there can be only two possible outcomes: 

  • The patient has the disease, which means “True”.
  • The patient has no disease. which means “False”.

This is a binary classification problem.

Data preparation

Once you have a good understanding of the problem, the next step is to prepare your data. This includes collecting and preprocessing the data and splitting it into training, validation, and test sets. In this step, the data is cleaned, preprocessed, and transformed into a format that can be used by the classification algorithm.

  • X: It is the independent feature, in the form of an N*M matrix. N is the no. of observations and M is the number of features.
  • y: An N vector corresponding to predicted classes for each of the N observations.

Feature Extraction

The relevant features or attributes are extracted from the data that can be used to differentiate between the different classes.

Suppose our input X has 7 independent features, having only 5 features influencing the label or target values remaining 2 are negligibly or not correlated, then we will use only these 5 features only for the model training. 

Model Selection

There are many different models that can be used for classification, including logistic regression, decision trees, support vector machines (SVM), or neural networks. It is important to select a model that is appropriate for your problem, taking into account the size and complexity of your data, and the computational resources you have available.

Model Training

Once you have selected a model, the next step is to train it on your training data. This involves adjusting the parameters of the model to minimize the error between the predicted class labels and the actual class labels for the training data.

Model Evaluation

Evaluating the model: After training the model, it is important to evaluate its performance on a validation set. This will give you a good idea of how well the model is likely to perform on new, unseen data. 

Log Loss or Cross-Entropy Loss, Confusion Matrix,  Precision, Recall, and AUC-ROC curve are the quality metrics used for measuring the performance of the model.

Fine-tuning the model

If the model’s performance is not satisfactory, you can fine-tune it by adjusting the parameters, or trying a different model.

Deploying the model

Finally, once we are satisfied with the performance of the model, we can deploy it to make predictions on new data.  it can be used for real world problem.

Examples of Machine Learning Classification in Real Life

Classification algorithms are widely used in many real-world applications across various domains, including:

  • Email spam filtering
  • Credit risk assessment
  • Medical diagnosis
  • Image classification
  • Sentiment analysis.
  • Fraud detection
  • Quality control
  • Recommendation systems

Implementation of Classification Model in Machine Learning

Let’s get a hands-on experience with how Classification works. We are going to study various Classifiers and see a rather simple analytical comparison of their performance on a well-known, standard data set, the Iris data set.  

Requirements for running the given script:

Python




# Importing the required libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn import datasets
from sklearn import svm
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
 
# import the iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
 
# splitting X and y into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=1)
 
# GAUSSIAN NAIVE BAYES
gnb = GaussianNB()
# train the model
gnb.fit(X_train, y_train)
# make predictions
gnb_pred = gnb.predict(X_test)
# print the accuracy
print("Accuracy of Gaussian Naive Bayes: ",
      accuracy_score(y_test, gnb_pred))
# print other performance metrics
print("Precision of Gaussian Naive Bayes: ",
      precision_score(y_test, gnb_pred, average='weighted'))
print("Recall of Gaussian Naive Bayes: ",
      recall_score(y_test, gnb_pred, average='weighted'))
print("F1-Score of Gaussian Naive Bayes: ",
      f1_score(y_test, gnb_pred, average='weighted'))
 
# DECISION TREE CLASSIFIER
dt = DecisionTreeClassifier(random_state=0)
# train the model
dt.fit(X_train, y_train)
# make predictions
dt_pred = dt.predict(X_test)
# print the accuracy
print("Accuracy of Decision Tree Classifier: ",
      accuracy_score(y_test, dt_pred))
# print other performance metrics
print("Precision of Decision Tree Classifier: ",
      precision_score(y_test, dt_pred, average='weighted'))
print("Recall of Decision Tree Classifier: ",
      recall_score(y_test, dt_pred, average='weighted'))
print("F1-Score of Decision Tree Classifier: ",
      f1_score(y_test, dt_pred, average='weighted'))
 
# SUPPORT VECTOR MACHINE
svm_clf = svm.SVC(kernel='linear')  # Linear Kernel
# train the model
svm_clf.fit(X_train, y_train)
# make predictions
svm_clf_pred = svm_clf.predict(X_test)
# print the accuracy
print("Accuracy of Support Vector Machine: ",
      accuracy_score(y_test, svm_clf_pred))
# print other performance metrics
print("Precision of Support Vector Machine: ",
      precision_score(y_test, svm_clf_pred, average='weighted'))
print("Recall of Support Vector Machine: ",
      recall_score(y_test, svm_clf_pred, average='weighted'))
print("F1-Score of Support Vector Machine: ",
      f1_score(y_test, svm_clf_pred, average='weighted'))


Output:

Accuracy of Gaussian Naive Bayes:  0.9333333333333333
Precision of Gaussian Naive Bayes: 0.9352007469654529
Recall of Gaussian Naive Bayes: 0.9333333333333333
F1-Score of Gaussian Naive Bayes: 0.933615520282187
Accuracy of Decision Tree Classifier: 0.9555555555555556
Precision of Decision Tree Classifier: 0.9555555555555556
Recall of Decision Tree Classifier: 0.9555555555555556
F1-Score of Decision Tree Classifier: 0.9555555555555556
Accuracy of Support Vector Machine: 1.0
Precision of Support Vector Machine: 1.0
Recall of Support Vector Machine: 1.0
F1-Score of Support Vector Machine: 1.0

Conclusion

In conclusion, classification is a fundamental task in machine learning, involving the categorization of data into predefined classes or categories based on their features.

Frequently Asked Questions (FAQs)

What is classification rule in machine learning?

A decision guideline in machine learning determining the class or category of input based on features.

What are the classification of algorithms?

Methods like decision trees, SVM, and k-NN categorizing data into predefined classes for predictions.

What is learning classification?

Acquiring knowledge to assign labels to input data, distinguishing classes in supervised machine learning.

What is difference between classification and clustering?

  • Classification: Predicts predefined classes.
  • Clustering: Groups data based on inherent similarities without predefined classes.

What is the difference between classification and regression methods?

  • Classification: Assigns labels to data classes.
  • Regression: Predicts continuous values for quantitative analysis.


Previous Article
Next Article

Similar Reads

Multiclass Classification vs Multi-label Classification
Multiclass classification is a machine learning task where the goal is to assign instances to one of multiple predefined classes or categories, where each instance belongs to exactly one class. Whereas multilabel classification is a machine learning task where each instance can be associated with multiple labels simultaneously, allowing for the ass
7 min read
ML | Getting Started With AlexNet
This article is focused on providing an introduction to the AlexNet architecture. Its name comes from one of the leading authors of the AlexNet paper- Alex Krizhevsky. It won the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) 2012 with a top-5 error rate of 15.3% (beating the runner up which had a top-5 error rate of 26.2%). The most im
3 min read
Getting started with Dialogflow
Dialogflow (formerly known as Api.ai), is the platform owned by Google to build conversational agents. Instead of building a chatbot from scratch, Dialogflow makes it easier to build it in considerably less time and with bunch of Google features, including pre-build ML Models that can help you get started right away. Dialogflow also allows you to i
4 min read
Getting Started with Google Actions
Actions on Google is the developer platform for the Google Assistant. By creating actions, brands are able to bring their services to the Google Assistant. Some important terms related to Actions on Google: Actions An interaction with the to start a conversation, the user needs to invoke your Action through the Assistant. Users say or type a phrase
4 min read
Getting Started With ChatGPT: A Complete Guide With Examples
Artificial Intelligence (AI) has brought about a significant transformation in the software industry and its technologies, revolutionizing the business landscape. Chatbots are one of the types of AI-powered platforms that mimic human-like conversation. Among these platforms, ChatGPT is a powerful tool that has quickly gained popularity on the inter
15+ min read
Getting Started With Google Colab
Google Colab is the short form for "Google Colabortory". It is an executable document that lets you write, run, and share code or you can think as an improved version of "Jupyter Notebook" stored in Google Drive. You might be wondering about the word "Notebook", in simple words it is just a document that includes executable lines of code along with
6 min read
Getting Started with Plotly in R
creationPlotly in R Programming Language allows the creation of interactive web graphics from 'ggplot2' graphs and a custom interface to the JavaScript library 'plotly.js' inspired by the grammar of graphics. InstallationTo use a package in R programming one must have to install the package first. This task can be done using the command install.pac
5 min read
Getting Started With Object Tracking Using OpenCV
OpenCV, developed by Intel in the early 2000s, is a popular open-source computer vision library used for real-time tasks. It offers various features like image processing, face detection, object detection, and more. In this article, we explore object-tracking algorithms and how to implement them using OpenCV and Python to track objects in videos. G
4 min read
Getting started with Kaggle : A quick guide for beginners
Kaggle is an online community of Data Scientists and Machine Learning Engineers which is owned by Google. A general feeling of beginners in the field of Machine Learning and Data Science towards the website is of hesitance. This feeling mainly arises because of the misconceptions that the outside people have about the website. Here are some of them
3 min read
Getting started with Data Visualization in R
Data visualization is the technique used to deliver insights in data using visual cues such as graphs, charts, maps, and many others. This is useful as it helps in intuitive and easy understanding of the large quantities of data and thereby make better decisions regarding it. Data Visualization in R Programming LanguageThe popular data visualizatio
6 min read
Getting Started with Google Gemini with Python: API Integration and Model Capabilities
Google released Gemini, their first truly multimodal device, in three sizes: Ultra, Pro, and Nano, in December. Since each Gemini model is designed for a specific set of use cases, the family of models is adaptable and functions well on a variety of platforms, including devices and data centers. Gemini models combine and comprehend text, code, grap
6 min read
Getting started with Machine Learning || Machine Learning Roadmap
Machine Learning (ML) represents a branch of artificial intelligence (AI) focused on enabling systems to learn from data, uncover patterns, and autonomously make decisions. In today's era dominated by data, ML is transforming industries ranging from healthcare to finance, offering robust tools for predictive analytics, automation, and informed deci
11 min read
Getting Started with KNIME Analytics: Running the Platform
Data Analytics is a process in which tools convert the raw data into meaningful format. For Structured Data, tools are required to handle the missing values, gain insights, convert to appropriate data formats, and generate charts so we can later use the data for further purposes. Many Data Analytics tools are available out of which KNIME is most po
6 min read
Essential OpenCV Functions to Get Started into Computer Vision
Computer vision is a process by which we can understand the images and videos how they are stored and how we can manipulate and retrieve data from them. Computer Vision is the base or mostly used for Artificial Intelligence. Computer-Vision is playing a major role in self-driving cars, robotics as well as in photo correction apps. OpenCV is the hug
7 min read
How Should a Machine Learning Beginner Get Started on Kaggle?
Are you fascinated by Data Science? Do you think Machine Learning is fun? Do you want to learn more about these fields but aren’t sure where to start? Well, start with Kaggle! Kaggle is an online community devoted to Data Scientist and Machine Learning founded by Google in 2010. It is the largest data community in the world with members ranging fro
8 min read
How To Use Classification Machine Learning Algorithms in Weka ?
Weka tool is an open-source tool developed by students of Waikato university which stands for Waikato Environment for Knowledge Analysis having all inbuilt machine learning algorithms. It is used for solving real-life problems using data mining techniques. The tool was developed using the Java programming language so that it is platform-independent
3 min read
Basic Concept of Classification (Data Mining)
Data Mining: Data mining in general terms means mining or digging deep into data that is in different forms to gain patterns, and to gain knowledge on that pattern. In the process of data mining, large data sets are first sorted, then patterns are identified and relationships are established to perform data analysis and solve problems. Classificati
10 min read
Python | Image Classification using Keras
Image classification is a method to classify way images into their respective category classes using some methods like : Training a small network from scratchFine-tuning the top layers of the model using VGG16 Let's discuss how to train the model from scratch and classify the data containing cars and planes. Train Data: Train data contains the 200
4 min read
ML | Using SVM to perform classification on a non-linear dataset
Prerequisite: Support Vector Machines Definition of a hyperplane and SVM classifier: For a linearly separable dataset having n features (thereby needing n dimensions for representation), a hyperplane is basically an (n - 1) dimensional subspace used for separating the dataset into two sets, each set containing data points belonging to a different c
4 min read
Omniglot Classification Task
Let us first define the meaning of Omniglot before getting in-depth into the classification task. Omniglot Dataset: It is a dataset containing 1623 characters from 50 different alphabets, each one hand-drawn by a group of 20 different people. This dataset was created for the study of how humans and machines adapt to one-shot learning, i.e. learning
4 min read
ML | Why Logistic Regression in Classification ?
Using Linear Regression, all predictions >= 0.5 can be considered as 1 and rest all < 0.5 can be considered as 0. But then the question arises why classification can't be performed using it? Problem - Suppose we are classifying a mail as spam or not spam and our output is y, it can be 0(spam) or 1(not spam). In case of Linear Regression, hÎļ(x
3 min read
ML | Logistic Regression v/s Decision Tree Classification
Logistic Regression and Decision Tree classification are two of the most popular and basic classification algorithms being used today. None of the algorithms is better than the other and one's superior performance is often credited to the nature of the data being worked upon. We can compare the two algorithms on different categories - CriteriaLogis
2 min read
Probability Calibration for 3-class Classification in Scikit Learn
Probability calibration is a technique to map the predicted probabilities of a model to their true probabilities. The probabilities predicted by some classification algorithms like Logistic Regression, SVM, or Random Forest may not be well calibrated, meaning they may not accurately reflect the true probabilities of the target classes. This can lea
4 min read
ML | Classification vs Clustering
Prerequisite: Classification and Clustering As you have read the articles about classification and clustering, here is the difference between them. Both Classification and Clustering is used for the categorization of objects into one or more classes based on the features. They appear to be a similar process as the basic difference is minute. In the
2 min read
OpenCV and Keras | Traffic Sign Classification for Self-Driving Car
Introduction In this article, we will learn how to classify some common traffic signs that we occasionally encounter in our daily lives on the road. While building a self-driving car, it is necessary to make sure it identifies the traffic signs with a high degree of accuracy, unless the results might be catastrophic. While travelling, you may have
7 min read
Classification of Data Mining Systems
Data Mining is considered as an interdisciplinary field. It includes a set of various disciplines such as statistics, database systems, machine learning, visualization and information sciences.Classification of the data mining system helps users to understand the system and match their requirements with such systems. Data mining systems can be cate
1 min read
An introduction to MultiLabel classification
One of the most used capabilities of supervised machine learning techniques is for classifying content, employed in many contexts like telling if a given restaurant review is positive or negative or inferring if there is a cat or a dog on an image. This task may be divided into three domains, binary classification, multiclass classification, and mu
7 min read
Multi-Label Image Classification - Prediction of image labels
There are so many things we can do using computer vision algorithms: Object detectionImage segmentationImage translationObject tracking (in real-time), and a whole lot more. What is Multi-Label Image Classification? Let’s understand the concept of multi-label image classification with an intuitive example. If I show you an image of a ball, you'll e
8 min read
One-vs-Rest strategy for Multi-Class Classification
Prerequisite: Getting Started with Classification/ Classification is perhaps the most common Machine Learning task. Before we jump into what One-vs-Rest (OVR) classifiers are and how they work, you may follow the link below and get a brief overview of what classification is and how it is useful. In general, there are two types of classification alg
4 min read
Tumor Detection using classification - Machine Learning and Python
In this article, we will be making a project through Python language which will be using some Machine Learning Algorithms too. It will be an exciting one as after this project you will understand the concepts of using AI & ML with a scripting language. The following libraries/packages will be used in this project: numpy: It's a Python library t
9 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg