Home  >  Article  >  Backend Development  >  How to Convert an Array of Indices to a One-Hot Encoded Array in NumPy?

How to Convert an Array of Indices to a One-Hot Encoded Array in NumPy?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 00:09:28521browse

How to Convert an Array of Indices to a One-Hot Encoded Array in NumPy?

Converting an Array of Indices to a One-Hot Encoded Array in NumPy

Often, it becomes necessary to transform a 1D array of indices into a 2D array where each row represents a one-hot encoding of the corresponding index in the original array.

Example:

Let's have a 1D array of indices 'a':

<code class="python">a = np.array([1, 0, 3])</code>

We aim to create a 2D array 'b' where each row is a one-hot encoding of the corresponding index in 'a':

<code class="python">b = np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])</code>

Solution:

To achieve this transformation, we can utilize the following steps:

  1. Zeroed Array Creation:
    Create a zeroed array 'b' with enough columns to accommodate the maximum index value in 'a', plus one ('a.max() 1').
<code class="python">b = np.zeros((a.size, a.max() + 1))</code>
  1. One-Hot Encoding:
    For each row 'i' in the array, set the 'a[i]'th column to 1. This step transforms each index in 'a' into a one-hot encoded row in 'b'.
<code class="python">b[np.arange(a.size), a] = 1</code>

Output:

Executing this code produces the desired one-hot encoded array 'b':

<code class="python">[[ 0.  1.  0.  0.]
 [ 1.  0.  0.  0.]
 [ 0.  0.  0.  1.]]</code>

The above is the detailed content of How to Convert an Array of Indices to a One-Hot Encoded Array in NumPy?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn