Sunday, 2 March 2025

How to use one-hot encoding in machine learning?

One hot encoding is a technique, that converts categorical data into a binary matrix representation. This is one of the popular data pre-processing technique.

Example 1:  if you have a categorical variable called "gender" with the values "male", "female", then one-hot encoding will create two binary features "gender_male", "gender_female". Each feature will be 0 or 1 depending on whether the corresponding category is present in the data.

 

gender

gender_male

gender_female

male

1

0

female

0

1

female

0

1

male

1

0

 

Example 2:  if you have a categorical variable called "color" with the values "red", "green", and "blue", then one-hot encoding will create three binary features: color_red, color_green, and color_blue. Each feature will be 0 or 1, depending on whether the corresponding category is present in the data.

 

color

color_red

color_green

color_blue

red

1

0

0

green

0

1

0

blue

0

0

1

green

0

1

0

 

one_hot_encoding.py 

import pandas as pd
from sklearn.preprocessing import OneHotEncoder

# Create a DataFrame with a categorical column
df = pd.DataFrame(
    {'color': ['red', 'green', 'blue', 'red']}
)

# Create a OneHotEncoder object
encoder = OneHotEncoder()

# Transform the DataFrame
encoded_sparse_matrix = encoder.fit_transform(df)

# The result is a sparse matrix, you can convert it to a dense array
one_hot_encoded_array = encoded_sparse_matrix.toarray()

print("Original categorical data:")
print(df)

print("\nencoded sparse matrix:")
print(type(encoded_sparse_matrix))

print("\nOne-hot encoded data:")
print(one_hot_encoded_array)

Output

Original categorical data:
   color
0    red
1  green
2   blue
3    red

encoded sparse matrix:
<class 'scipy.sparse._csr.csr_matrix'>

One-hot encoded data:
[[0. 0. 1.]
 [0. 1. 0.]
 [1. 0. 0.]
 [0. 0. 1.]]

df = pd.DataFrame(

    {'color': ['red', 'green', 'blue', 'red']}

)

This code will first create a DataFrame with a categorical column called color. The color column has three unique values red, green, and blue.

 

encoder = OneHotEncoder()

it will create a OneHotEncoder object. This object is used to encode the categorical data in the color column.

 

encoded_sparse_matrix = encoder.fit_transform(df)

This will convert the categorical data in the color column to one-hot encoded data.

 

one_hot_encoded_array = encoded_sparse_matrix.toarray()

The output of the code is a DataFrame with three new columns: color_red, color_green, and color_blue. The color_red column will be 1 if the color column is equal to red and 0 otherwise. The color_green column will be 1 if the color column is equal to green and 0 otherwise. The color_blue column will be 1 if the color column is equal to blue and 0 otherwise.

 

In the above output, encoding sequence is in the order of blue, green and red.

 

But what if I want the order as red, greed, and blue.

 

Customize the encoding sequence

By passing the custom order as an argument to ‘OneHotEncoder’ constructor we can customize the encoding sequence.

# Define the desired order of categories
desired_order = ['red', 'green', 'blue']

# Create a OneHotEncoder object
encoder = OneHotEncoder(categories=[desired_order])

 

Find the below working application.

 

one_hot_encoding_maintain_order.py

 

import pandas as pd
from sklearn.preprocessing import OneHotEncoder

# Create a DataFrame with a categorical column
df = pd.DataFrame(
    {'color': ['red', 'green', 'blue', 'red']}
)

# Define the desired order of categories
desired_order = ['red', 'green', 'blue']

# Create a OneHotEncoder object
encoder = OneHotEncoder(categories=[desired_order])

# Transform the DataFrame
encoded_sparse_matrix = encoder.fit_transform(df)

# The result is a sparse matrix, you can convert it to a dense array
one_hot_encoded_array = encoded_sparse_matrix.toarray()

print("Original categorical data:")
print(df)

print("\nencoded sparse matrix:")
print(type(encoded_sparse_matrix))

print("\nOne-hot encoded data:")
print(one_hot_encoded_array)

 Output

Original categorical data:
   color
0    red
1  green
2   blue
3    red

encoded sparse matrix:
<class 'scipy.sparse._csr.csr_matrix'>

One-hot encoded data:
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [1. 0. 0.]]

 


Previous                                                    Next                                                    Home

Label Encoding: A Simple Way to Convert Categorical Data for Machine Learning

Label encoding is a process to convert the categorical data into numbers. Each categorical data is assigned with an unique number. This is required in multiple occasions, where machine learning algorithms require  numerical data to perform Mathematical computations, for example Linear regression, decision trees, support vector machines work with numerical data.


Examples of Categorical data

  1. favorite_color: red, green, yellow etc.,
  2. gender : male, female
  3. Marital status: single, married, divorced
  4. vehical_type: car, bike, bus
  5. rating: poor, average, good, excellent
  6. occupation: doctor, teacher, software engineer
  7. Religion: Christian, Muslim, Hindu, Buddhist
  8. education: high school, degree, masters, PhD

 

Let’s write an example using Scikit learn library.

 

label_encoding.py 

from sklearn.preprocessing import LabelEncoder

# Sample categorical labels
categorical_labels = ['poor', 'average', 'good', 'average', 'good', 'excellent']

# Creating an instance of LabelEncoder
label_encoder = LabelEncoder()

# Fitting the encoder on the categorical labels and transforming them
encoded_labels = label_encoder.fit_transform(categorical_labels)

print(encoded_labels)

 

Output

[3 0 2 0 2 1]

 

In this example, the LabelEncoder maps each unique label to a corresponding integer. In this case,

  1. 'poor' is mapped to 3,
  2. 'average' is mapped to 0,
  3. 'good' is mapped to 2, and
  4.  'excellent' is mapped to 1

 

Advantages of Label encoding

  1. Easy to implement
  2. It is a lossless transformation, original data is converted back from encoded data.

 

Limitation on Label encoding

Label encoding technique is ineffective in machine learning algorithms, when you have many unique categories. In these cases,  use other encoding techniques like one-hot encoding.

 

 

Previous                                                    Next                                                    Home

Mastering CSS Grid: A Deep Dive into the grid-area Property

The grid-area property in CSS is a powerful feature used in CSS Grid Layout. It allows you to define how an element is positioned within a grid container, specifying its location and the space it occupies. grid-area can be used in two different contexts:

It combines grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties to define the item's position.

 

Syntax

grid-area: row-start / column-start / row-end / column-end;

 

1.   row-start: Specifies the line where the grid item starts on the row axis.

2.   column-start: Specifies the line where the grid item starts on the column axis.

3.   row-end: Specifies the line where the grid item ends on the row axis.

4.   column-end: Specifies the line where the grid item ends on the column axis.

 

Example

grid-area: 1 / 1 / 3 / 2;

 

The line grid-area: 1 / 1 / 3 / 2; is using the shorthand syntax for placing a grid item within a grid container. It defines the start and end lines for both rows and columns, effectively specifying where the item will be positioned within the grid.

 

·      1 (row-start): This specifies the grid line where the item starts on the row axis. In this case, it starts at the first row line.

 

·      1 (column-start): This specifies the grid line where the item starts on the column axis. Here, it starts at the first column line.

 

·      3 (row-end): This specifies the grid line where the item ends on the row axis. It means the item will span up to the third row line. Therefore, the item will occupy rows 1 and 2 (it spans two rows).

 

·      2 (column-end): This specifies the grid line where the item ends on the column axis. It means the item will span up to the second column line. Thus, the item will occupy only the first column.

 

grid-area.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Grid Example</title>
    <style>
        .grid-container {
          display: grid;
          grid-template-columns: 1fr 1fr 1fr; /* Three equal columns */
          gap: 10px; /* Spacing between items */
          height: 200px;
          border: 1px solid black;
        }

        .style-text{
            text-align: center;
            padding-top: 30px;
            margin: 10px;
            font-size: 1.2em;
            font-weight: bold;
        }

        .item1 {
          background-color: lightcoral;
          grid-area: 1 / 1 / 3 / 2; 
        }

        .item2 {
          background-color: lightblue;
          grid-column: 3 / 4; /* Starts at line 3 and ends at line 4 */
        }

        .item3 {
          background-color: lightgreen;
          grid-column: 1 / 2; /* Starts at line 1 and ends at line 2 */
        }

        .item4 {
          background-color: lightsalmon;
          grid-column: 2 / 4; /* Starts at line 1 and ends at line 2 */
        }

    </style>
</head>
<body>

<div class="grid-container">
  <div class="item1 style-text">Item 1</div>
  <div class="item2 style-text">Item 2</div>
  <div class="item3 style-text">Item 3</div>
  <div class="item4 style-text">Item 4</div>
</div>

</body>
</html>

 


 

Previous                                                    Next                                                    Home

How to Control the Grid Layout with the grid-rows Property?

grid-row property is a part of CSS Grid Layout, a powerful tool for creating complex web layouts. CSS Grid allows you to divide a web page into rows and columns, making it easier to place and align elements. The grid-row property is specifically used to control the vertical placement of grid items by specifying which row(s) an item should occupy.

 

Understanding grid-row

The grid-row property is shorthand for two properties:

 

1.   grid-row-start: Specifies the starting row line for a grid item.

2.   grid-row-end: Specifies the ending row line for a grid item.

 

Syntax

grid-row: <start-line> / <end-line>;

 

1.   <start-line>: This defines on which grid row line the item should start.

2.   <end-line>: This defines on which grid row line the item should end.

 

Imagine you have a grid with multiple rows, and you want a particular item to span across certain rows. You can use the grid-row property to control this. The rows are defined by grid lines, which are essentially imaginary lines that separate each row.

 

hello-world.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grid Row Example</title>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(4, 100px);
            gap: 10px;
            border: 2px solid #000;
            padding: 10px;
        }

        .grid-item {
            background-color: lightcoral;
            text-align: center;
            padding-top: 40px;
            font-size: 1.5em;
            font-weight: bold;
        }

        .grid-item:nth-child(1) {
            grid-row: 1 / 3; /* Starts on row line 1, ends on row line 3 */
        }
    </style>
</head>
<body>

    <div class="grid-container">
        <div class="grid-item">Item 1 (Spans rows 1-2)</div>
        <div class="grid-item">Item 2</div>
        <div class="grid-item">Item 3</div>
        <div class="grid-item">Item 4</div>
        <div class="grid-item">Item 5</div>
        <div class="grid-item">Item 6</div>
    </div>

</body>
</html>

 

 


Using the span keyword

The span keyword is another powerful feature of the CSS Grid Layout that simplifies specifying the number of rows (or columns) an item should span. Instead of manually calculating the start and end lines, you can use span to indicate how many rows a grid item should occupy from its starting point.

 

grid-row: <start-line> / span <number-of-rows>;

 

1.   <start-line>: This defines the starting grid row line for the item.

2.   span <number-of-rows>: This defines how many rows the item should span starting from the <start-line>.

 

hello-world-span.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grid Row Example</title>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(4, 100px);
            gap: 10px;
            border: 2px solid #000;
            padding: 10px;
        }

        .grid-item {
            background-color: lightcoral;
            text-align: center;
            padding-top: 40px;
            font-size: 1.5em;
            font-weight: bold;
        }

        .grid-item:nth-child(1) {
            grid-row: 1 / span 2; /* Starts on row line 1, span two lines */
        }
    </style>
</head>
<body>

    <div class="grid-container">
        <div class="grid-item">Item 1 (Spans rows 1-2)</div>
        <div class="grid-item">Item 2</div>
        <div class="grid-item">Item 3</div>
        <div class="grid-item">Item 4</div>
        <div class="grid-item">Item 5</div>
        <div class="grid-item">Item 6</div>
    </div>

</body>
</html>

 

 


Previous                                                    Next                                                    Home

Quick Introduction to Closures in JavaScript: A Step-by-Step Guide

In JavaScript, a closure is a feature where an inner function has access to the variables of its outer (enclosing) function, even after that outer function has finished executing. Essentially, a closure allows a function to "remember" the environment (or scope) in which it was created.

hello-world.js 

function outerFunction() {
  let outerVariable = "I am defined at Outer Layer Scope";

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

const myClosure = outerFunction();
myClosure(); // Output: "I am defined at Outer Layer Scope"

 Output

I am defined at Outer Layer Scope

 

When outerFunction is called and returns innerFunction, we assign that returned function to myClosure. Even though outerFunction has finished executing, myClosure (which is innerFunction) still remembers the environment it was created in, which includes the outerVariable.

 

How Do Closures Retain Access to the Outer Scope?

This behaviour is possible because of JavaScript's lexical scoping. JavaScript functions are lexically scoped, meaning they remember the scope in which they were created. When innerFunction is created, it has access to outerFunction's scope, including variables declared within outerFunction.

 

When you call a function that creates and returns a closure, a new function instance is created each time, even if the code inside is the same. This is because each call to the outer function creates a new scope with its own set of variables, and the inner function (the closure) captures and retains access to that specific scope.

 

diff-inner-function-on-each-call.js

function outerFunction(name) {
  let count = 0;

  function innerFunction(name) {
    count++;
    console.log(`Closure : ${name}, Count is ${count}`);
  }

  return () => innerFunction(name);
}

const myClosure1 = outerFunction("Closure1");
const myClosure2 = outerFunction("Closure2");

myClosure1();
myClosure2();

myClosure1();
myClosure2();

myClosure1();
myClosure2();

 

Output

Closure : Closure1, Count is 1
Closure : Closure2, Count is 1
Closure : Closure1, Count is 2
Closure : Closure2, Count is 2
Closure : Closure1, Count is 3
Closure : Closure2, Count is 3

 Each Call to outerFunction Creates a New Execution Context, When you call outerFunction, it creates a new execution context (a new scope) with its own local variables. This includes the count variable, which is initialized to 0 each time.

 


Previous                                                    Next                                                    Home

How export default Simplifies JavaScript Modules?

In JavaScript, export default is used to export a single value, function, or class from a module. It allows the module to export one primary item that can be imported without specifying a name.

Syntax 

export default value;

circle-util.js

export default function areaOfCircle(radius){
    if (typeof radius !== 'number'){
        throw new Error("radius is not a number");
    }
    return 3.14 * radius * radius;
}

default-export.js

import circleArea from "./circle-util.js"

console.log(`Area of Circle for the radius 5 is ${circleArea(5)}`);

Output

Area of Circle for the radius 5 is 78.5

How to rersolve the error “Cannot use import statement outside a module”?

The error Cannot use import statement outside a module occurs in Node.js because Node.js uses CommonJS module system by default, whereas import and export syntax is part of ECMAScript (ES) modules.

 

To resolve this error, set "type": "module" in package.json.

 

package.json

{
  "name": "your-app",
  "version": "1.0.0",
  "type": "module"
}

 

"type": "module" in your package.json file indicates that all .js files in your project are treated as ES modules.

 

Previous                                                    Next                                                    Home