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

Barbara Streisand
Release: 2024-11-01 00:09:28
Original
536 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login
  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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!