The Wayback Machine - https://web.archive.org/web/20241113051808/https://www.geeksforgeeks.org/ml-one-hot-encoding/
Open In App

One Hot Encoding in Machine Learning

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

While developing Data Science Projects, we may find datasets containing mixed data types consisting of both categorical as well as numerical columns. However, various Machine Learning models do not work with categorical data and to fit this data into the machine learning model it needs to be converted into numerical data. For example, suppose a dataset has a Gender column with categorical elements like Male and  Female. These labels have no specific order of preference and also since the data is string labels, machine learning models misinterpreted that there is some sort of hierarchy in them.

To address this issue, one effective technique is one hot encoding. OHE in machine learning transforms categorical data into a numerical format that machine learning algorithms can process without imposing any ordinal relationships.

What is One Hot Encoding?

One Hot Encoding is a method for converting categorical variables into a binary format. It creates new binary columns (0s and 1s) for each category in the original variable. Each category in the original column is represented as a separate column, where a value of 1 indicates the presence of that category, and 0 indicates its absence.

Why Use One Hot Encoding?

The primary purpose of One Hot Encoding is to ensure that categorical data can be effectively used in machine learning models. Key reasons why this technique is beneficial:

  1. Eliminating Ordinality: Many categorical variables have no inherent order (e.g., “Male” and “Female”). If we were to assign numerical values (e.g., Male = 0, Female = 1), the model might mistakenly interpret this as a ranking, leading to biased predictions. One Hot Encoding eliminates this risk by treating each category independently.
  2. Improving Model Performance: By providing a more detailed representation of categorical variables, One Hot Encoding can help improve the performance of machine learning models. It allows models to capture complex relationships within the data that might be missed if categorical variables were treated as single entities.
  3. Compatibility with Algorithms: Many machine learning algorithms, particularly those based on linear regression and gradient descent, require numerical input. One Hot Encoding ensures that categorical variables are converted into a suitable format.

How One-Hot Encoding Works: An Example

To grasp the concept better, let’s explore a simple example. Imagine we have a dataset with fruits, their categorical values, and corresponding prices. Using one-hot encoding, we can transform these categorical values into numerical form. For instance:

  • Wherever the fruit is “Apple,” the Apple column will have a value of 1, while the other fruit columns (like Mango or Orange) will contain 0.
  • This pattern ensures that each categorical value gets its own column, represented with binary values (1 or 0), making it usable for machine learning models.
FruitCategorical value of fruitPrice
apple15
mango210
apple115
orange320

The output after applying one-hot encoding on the data is given as follows,

Fruit_appleFruit_mangoFruit_orangeprice
1005
01010
10015
00120

Implementing One-Hot Encoding Using Python

To implement one-hot encoding in Python, we can use either the Pandas library or the Scikit-learn library, both of which provide efficient and convenient methods for this task.

1. Using Pandas

Pandas offers the get_dummies function, which is a simple and effective way to perform one-hot encoding. This method converts categorical variables into multiple binary columns.

  • For example, the Gender column with values 'M' and 'F' becomes two binary columns: Gender_F and Gender_M.
  • drop_first=True in pandas drops one redundant column (e.g., keeps only Gender_F to avoid multicollinearity).
Python
import pandas as pd
from sklearn.preprocessing import OneHotEncoder

# Create a dummy employee dataset
data = {
    'Employee id': [10, 20, 15, 25, 30],
    'Gender': ['M', 'F', 'F', 'M', 'F'],
    'Remarks': ['Good', 'Nice', 'Good', 'Great', 'Nice']
}

# Convert the data into a pandas DataFrame
df = pd.DataFrame(data)
print(f"Original Employee Data:\n{df}\n")
# Use pd.get_dummies() to one-hot encode the categorical columns
df_pandas_encoded = pd.get_dummies(df, columns=['Gender', 'Remarks'], drop_first=True)
print(f"One-Hot Encoded Data using Pandas:\n{df_pandas_encoded}\n")

# Initialize OneHotEncoder
encoder = OneHotEncoder(sparse_output=False)

# Fit and transform the categorical columns
one_hot_encoded = encoder.fit_transform(df[categorical_columns])

# Create a DataFrame with the encoded columns
one_hot_df = pd.DataFrame(one_hot_encoded, 
                          columns=encoder.get_feature_names_out(categorical_columns))

# Concatenate the one-hot encoded columns with the original DataFrame
df_sklearn_encoded = pd.concat([df.drop(categorical_columns, axis=1), one_hot_df], axis=1)

print(f"One-Hot Encoded Data using Scikit-Learn:\n{df_sklearn_encoded}\n")

Output:

Original Employee Data:
Employee id Gender Remarks
0 10 M Good
1 20 F Nice
2 15 F Good
3 25 M Great
4 30 F Nice

One-Hot Encoded Data using Pandas:
Employee id Gender_M Remarks_Great Remarks_Nice
0 10 True False False
1 20 False False True
2 15 False False False
3 25 True True False
4 30 False False True

We can observe that we have 3 Remarks and 2 Gender columns in the data. However, you can just use n-1 columns to define parameters if it has n unique labels. For example, if we only keep the Gender_Female column and drop the Gender_Male column, then also we can convey the entire information as when the label is 1, it means female and when the label is 0 it means male. This way we can encode the categorical data and reduce the number of parameters as well.

2. One Hot Encoding using Scikit Learn Library

Scikit-learn(sklearn) is a popular machine-learning library in Python that provide numerous tools for data preprocessing. It provides a OneHotEncoder function that we use for encoding categorical and numerical variables into binary vectors. Using df.select_dtypes(include=['object']) in Scikit Learn Library:

  • This selects only the columns with categorical data (data type object).
  • In this case, ['Gender', 'Remarks'] are identified as categorical columns.
Python
#one hot encoding using OneHotEncoder of Scikit-Learn

import pandas as pd
from sklearn.preprocessing import OneHotEncoder

#Building a dummy employee dataset for example
data = {'Employee id': [10, 20, 15, 25, 30],
        'Gender': ['M', 'F', 'F', 'M', 'F'],
        'Remarks': ['Good', 'Nice', 'Good', 'Great', 'Nice'],
        }
df = pd.DataFrame(data)
print(f"Employee data : \n{df}")

#Extract categorical columns from the dataframe
#Here we extract the columns with object datatype as they are the categorical columns
categorical_columns = df.select_dtypes(include=['object']).columns.tolist()
encoder = OneHotEncoder(sparse_output=False)

# Apply one-hot encoding to the categorical columns
one_hot_encoded = encoder.fit_transform(df[categorical_columns])

#Create a DataFrame with the one-hot encoded columns
#We use get_feature_names_out() to get the column names for the encoded data
one_hot_df = pd.DataFrame(one_hot_encoded, columns=encoder.get_feature_names_out(categorical_columns))

# Concatenate the one-hot encoded dataframe with the original dataframe
df_encoded = pd.concat([df, one_hot_df], axis=1)

# Drop the original categorical columns
df_encoded = df_encoded.drop(categorical_columns, axis=1)
print(f"Encoded Employee data : \n{df_encoded}")

Output:

Employee data : 
Employee id Gender Remarks
0 10 M Good
1 20 F Nice
2 15 F Good
3 25 M Great
4 30 F Nice
Encoded Employee data :
Employee id Gender_F Gender_M Remarks_Good Remarks_Great Remarks_Nice
0 10 0.0 1.0 1.0 0.0 0.0
1 20 1.0 0.0 0.0 0.0 1.0
2 15 1.0 0.0 1.0 0.0 0.0
3 25 0.0 1.0 0.0 1.0 0.0
4 30 1.0 0.0 0.0 0.0 1.0

Both Pandas and Scikit-Learn offer robust solutions for one-hot encoding.

  • Use Pandas get_dummies() when you need quick and simple encoding.
  • Use Scikit-Learn OneHotEncoder when working within a machine learning pipeline, or when you need finer control over encoding behavior.

Advantages and Disadvantages of One Hot Encoding

Advantages of Using One Hot Encoding

  1. It allows the use of categorical variables in models that require numerical input.
  2. It can improve model performance by providing more information to the model about the categorical variable.
  3. It can help to avoid the problem of ordinality, which can occur when a categorical variable has a natural ordering (e.g. “small”, “medium”, “large”).

Disadvantages of Using One Hot Encoding

  1. It can lead to increased dimensionality, as a separate column is created for each category in the variable. This can make the model more complex and slow to train.
  2. It can lead to sparse data, as most observations will have a value of 0 in most of the one-hot encoded columns.
  3. It can lead to overfitting, especially if there are many categories in the variable and the sample size is relatively small.
  4.  One-hot-encoding is a powerful technique to treat categorical data, but it can lead to increased dimensionality, sparsity, and overfitting. It is important to use it cautiously and consider other methods such as ordinal encoding or binary encoding.

Best Practices for One Hot Encoding

To make the most of One Hot Encoding and mitigate its drawbacks, consider the following best practices:

  1. Limit the Number of Categories: If you have high cardinality categorical variables, consider limiting the number of categories through grouping or feature engineering.
  2. Use Feature Selection: Implement feature selection techniques to identify and retain only the most relevant features after One Hot Encoding. This can help reduce dimensionality and improve model performance.
  3. Monitor Model Performance: Regularly evaluate your model’s performance after applying One Hot Encoding. If you notice signs of overfitting or other issues, consider alternative encoding methods.
  4. Understand Your Data: Before applying One Hot Encoding, take the time to understand the nature of your categorical variables. Determine whether they have a natural order and whether One Hot Encoding is appropriate.

Alternatives to One Hot Encoding

While One Hot Encoding is a popular choice for handling categorical data, there are several alternatives that may be more suitable depending on the context:

  1. Label Encoding: In cases where categorical variables have a natural order (e.g., “Low,” “Medium,” “High”), label encoding can be a better option. This method assigns a unique integer to each category without introducing the same risks of hierarchy misinterpretation as with nominal data.
  2. Binary Encoding: This technique combines the benefits of One Hot Encoding and label encoding. It converts categories into binary numbers and then creates binary columns. This method can reduce dimensionality while preserving information.
  3. Target Encoding: In target encoding, we replace each category with the mean of the target variable for that category. This method can be particularly useful for categorical variables with a high number of unique values, but it also carries a risk of leakage if not handled properly.

One Hot Encoding in Machine Learning – FAQs

Why is it called one-hot encoding?

It is called one-hot encoding because only one column (or feature) corresponding to a particular category has the value 1, while all others are set to 0. For example, if the categories are Male and Female, the Male row will have [1, 0] and Female will have [0, 1]. This way, only one “hot” bit (1) is activated for each entry.

What is the one-hot encoding strategy?

The strategy involves:

  1. Identifying categorical columns in the dataset.
  2. Creating new binary columns—one for each unique category.
  3. Assigning 1 to the column corresponding to the category present for that row, and 0 to all other columns.

What is the result of one-hot encoding?

The result of one-hot encoding is a binary matrix representation of categorical data. This matrix replaces the original categorical column with multiple binary columns, each representing a category.

What is another name for one-hot encoding?

Dummy encoding is often used as an alternative term. However, dummy encoding typically drops one of the binary columns to prevent multicollinearity (unlike standard one-hot encoding).

What is one-hot encoding for word?

In Natural Language Processing (NLP), one-hot encoding is used to represent words as binary vectors. Each word is assigned a unique position in the vector, with 1 indicating the presence of the word and 0s elsewhere. However, one-hot encoding is less commonly used for large vocabularies because it can result in high-dimensional vectors.

What is the difference between encoding and one-hot encoding?

Encoding refers to converting categorical values into numerical representations in general. There are multiple encoding techniques:

  • Label Encoding: Assigns an integer to each category (e.g., Male = 0, Female = 1).
  • One-Hot Encoding: Converts categories into multiple binary columns where only one bit is active (1) per entry.

One-hot encoding is particularly useful when categories do not have a natural order, whereas label encoding is used for ordinal data.

When not to use one-hot encoding?

  • High Cardinality: If a categorical feature has too many unique values, one-hot encoding can lead to extremely high-dimensional data, which may slow down the model training and increase memory usage. Example: Encoding Country with 200+ unique values will create 200+ binary columns.
  • Tree-Based Models: Algorithms like decision trees, random forests, or gradient boosting do not benefit significantly from one-hot encoding. These models can handle categorical features natively or with label encoding.
  • When Sparsity is an Issue: If your model struggles with sparse data (many 0s), one-hot encoding may not be a good choice.


Similar Reads

What is difference between one hot encoding and leave one out encoding?
Answer: One-hot encoding represents each category with a binary vector, while leave-one-out encoding replaces a category with the mean of the target variable excluding the current observation.One-hot encoding and leave-one-out encoding are two different methods used in categorical variable encoding. Let's compare them in detail in tabular form: Cri
2 min read
CatBoost's Categorical Encoding: One-Hot vs. Target Encoding
CatBoost is a powerful gradient boosting algorithm that excels in handling categorical data. It incorporates unique methods for encoding categorical features, including one-hot encoding and target encoding. Understanding these encoding techniques is crucial for effectively utilizing CatBoost in machine learning tasks. In real-world datasets, we qui
6 min read
Why One-Hot Encoding Improves Machine Learning Performance?
One-hot encoding is a crucial step in data preparation for machine learning algorithms. It involves converting categorical data into a numerical format that can be effectively processed by these algorithms. This technique has been widely adopted due to its ability to significantly improve the performance of machine learning models. In this article,
8 min read
One Hot Encoding using Tensorflow
In this post, we will be seeing how to initialize a vector in TensorFlow with all zeros or ones. The function you will be calling is tf.ones(). To initialize with zeros you could use tf.zeros() instead. These functions take in a shape and return an array full of zeros and ones accordingly. Code: import tensorflow as tf ones_matrix = tf.ones([2, 3])
2 min read
One-Hot Encoding in NLP
Natural Language Processing (NLP) is a quickly expanding discipline that works with computer-human language exchanges. One of the most basic jobs in NLP is to represent text data numerically so that machine learning algorithms can comprehend it. One common method for accomplishing this is one-hot encoding, which converts category variables to binar
9 min read
Why Tree Ensembles Don't Require One-Hot-Encoding
Answer: Tree ensembles, unlike linear models, inherently handle categorical data without requiring one-hot encoding due to their split-based nature.Tree ensembles, such as Random Forests and Gradient Boosting Machines (GBMs), have a unique capability to handle categorical data without the need for one-hot encoding. This ability stems from the funda
2 min read
Is It Effective to Use One-Hot Encoding When Its Dimension Is as Large as Thousands?
Answer: It lead to high memory usage and model complexity, often making it less effective without dimensionality reduction techniques.One-hot encoding transforms categorical variables into a form that algorithms can work with more effectively. However, when the dimensionality reaches the thousands, it introduces challenges that can affect the effic
2 min read
One-Hot-Encoding from a Pandas Column Containing a List
One-hot encoding is a crucial preprocessing step in data science, especially when dealing with categorical data. It converts categorical variables into a binary matrix representation, where each category is represented by a separate column. This article will guide you through the process of one-hot encoding a Pandas column containing a list of elem
6 min read
Mean Encoding - Machine Learning
During Feature Engineering the task of converting categorical features into numerical is called Encoding. There are various ways to handle categorical features like OneHotEncoding and LabelEncoding, FrequencyEncoding or replacing by categorical features by their count. In similar way we can uses MeanEncoding. Created a DataFrame having two features
2 min read
Feature Encoding Techniques - Machine Learning
As we all know that better encoding leads to a better model and most algorithms cannot handle the categorical variables unless they are converted into a numerical value. Categorical features are generally divided into 3 types: A. Binary: Either/or Examples: Yes, NoTrue, False B. Ordinal: Specific ordered Groups. Examples: low, medium, highcold, hot
5 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
One Shot Learning in Machine Learning
One-shot learning is a machine learning paradigm aiming to recognize objects or patterns from a limited number of training examples, often just a single instance. Traditional machine learning models typically require large amounts of labeled data for high performance. Still, one-shot learning seeks to overcome this limitation by enabling models to
7 min read
TensorFlow - How to create one hot tensor
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. One hot tensor is a Tensor in which all the values at indices where i =j and i!=j is same. Method Used: one_hot: This method accepts a Tensor of indices, a scalar defining depth of the one hot dimension and returns a one
2 min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Azure Virtual Machine for Machine Learning
Prerequisites: About Microsoft Azure, Cloud Based Services Some of the Machine Learning and Deep Learning algorithms may require high computation power which may not be supported by your local machine or laptop. In that case, creating a Virtual Machine on a cloud platform can provide you the expected computation power. We can have a system with hig
4 min read
Machine Learning Model with Teachable Machine
Teachable Machine is a web-based tool developed by Google that allows users to train their own machine learning models without any coding experience. It uses a web camera to gather images or videos, and then uses those images to train a machine learning model. The user can then use the model to classify new images or videos. The process of creating
7 min read
Artificial intelligence vs Machine Learning vs Deep Learning
Nowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are related to each other but not the same. Let's see
4 min read
Need of Data Structures and Algorithms for Deep Learning and Machine Learning
Deep Learning is a field that is heavily based on Mathematics and you need to have a good understanding of Data Structures and Algorithms to solve the mathematical problems optimally. Data Structures and Algorithms can be used to determine how a problem is represented internally or how the actual storage pattern works & what is happening under
6 min read
Machine Learning - Learning VS Designing
In this article, we will learn about Learning and Designing and what are the main differences between them. In Machine learning, the term learning refers to any process by which a system improves performance by using experience and past data. It is kind of an iterative process and every time the system gets improved though one may not see a drastic
3 min read
Passive and Active learning in Machine Learning
Machine learning is a subfield of artificial intelligence that deals with the creation of algorithms that can learn and improve themselves without explicit programming. One of the most critical factors that contribute to the success of a machine learning model is the quality and quantity of data used to train it. Passive learning and active learnin
3 min read
Automated Machine Learning for Supervised Learning using R
Automated Machine Learning (AutoML) is an approach that aims to automate various stages of the machine learning process, making it easier for users with limited machine learning expertise to build high-performing models. AutoML is particularly useful in supervised learning, where you have labeled data and want to create models that can make predict
8 min read
Meta-Learning in Machine Learning
Traditional machine learning requires a huge dataset that is specific to a particular task and wishes to train a model for regression or classification purposes using these datasets. That’s radically far from how humans take advantage of their past experiences to learn quickly a new task from only a handset of examples. What is Meta Learning?Meta-l
13 min read
Continual Learning in Machine Learning
As we know Machine Learning (ML) is a subfield of artificial intelligence that specializes in growing algorithms that learn from statistics and make predictions or choices without being explicitly programmed. It has revolutionized many industries by permitting computer systems to understand styles, make tips, and perform tasks that were soon consid
10 min read
Few-shot learning in Machine Learning
What is a Few-shot learning?Few-shot learning is a type of meta-learning process. It is a process in which a model possesses the capability to autonomously acquire knowledge and improve its performance through self-learning. It is a process like teaching the model to recognize things or do tasks, but instead of overwhelming it with a lot of example
8 min read
What Is Meta-Learning in Machine Learning in R
In traditional machine learning, models are typically trained on a specific dataset for a specific task, and their performance is optimized for that particular task. However, in R Programming Language the focus is on building models that can leverage prior knowledge or experience to quickly adapt to new tasks with minimal additional training data.
7 min read
Types of Federated Learning in Machine Learning
Federated Learning is a powerful technique that allow a single machine to learn from many different source and converting the data into small pieces sending them to different Federated Learning (FL) is a decentralized of the machine learning paradigm that can enables to model training across various devices while preserving your data the data priva
5 min read
Machine Learning-based Recommendation Systems for E-learning
In today's digital age, e-learning platforms are transforming education by giving students unprecedented access to a wide range of courses and resources. Machine learning-based recommendation systems have emerged as critical tools for effectively navigating this vast amount of content. The article delves into the role of recommendation systems in e
9 min read
Understanding PAC Learning: Theoretical Foundations and Practical Applications in Machine Learning
In the vast landscape of machine learning, understanding how algorithms learn from data is crucial. Probably Approximately Correct (PAC) learning stands as a cornerstone theory, offering insights into the fundamental question of how much data is needed for learning algorithms to reliably generalize to unseen instances. PAC learning provides a theor
8 min read
Difference Between Artificial Intelligence vs Machine Learning vs Deep Learning
Artificial Intelligence is basically the mechanism to incorporate human intelligence into machines through a set of rules(algorithm). AI is a combination of two words: "Artificial" meaning something made by humans or non-natural things and "Intelligence" meaning the ability to understand or think accordingly. Another definition could be that "AI is
14 min read
Difference Between Machine Learning and Deep Learning
If you are interested in building your career in the IT industry then you must have come across the term Data Science which is a booming field in terms of technologies and job availability as well. In this article, we will explore the Difference between Machine Learning and Deep Learning, two major fields within Data Science. Understanding these di
8 min read
three90RightbarBannerImg