Home >Backend Development >Python Tutorial >How to Convert Index Arrays to One-Hot Encoded Arrays in NumPy?

How to Convert Index Arrays to One-Hot Encoded Arrays in NumPy?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 03:08:01654browse

How to Convert Index Arrays to One-Hot Encoded Arrays in NumPy?

One-Hot Encoding Index Arrays in NumPy

In NumPy, converting a 1D array of indices to a one-hot encoded 2D array is a common task. For example, given the array a with indices [1, 0, 3], we want to encode it as:

b = [[0,1,0,0], [1,0,0,0], [0,0,0,1]]

To achieve this, there are two key steps:

  1. Create a zeroed array: Create a 2D array b with enough columns (i.e., a.max() 1) to accommodate the one-hot encoded values. The array should be initialized with zeros.
  2. Set appropriate values to 1: For each row i in b, set the a[i]th column to 1. This indicates that the original index a[i] is present at position i in the one-hot encoded array.

Here's a code example to illustrate:

<code class="python">import numpy as np

a = np.array([1, 0, 3])
b = np.zeros((a.size, a.max() + 1))
b[np.arange(a.size), a] = 1

print(b)</code>

Output:

[[0. 1. 0. 0.]
 [1. 0. 0. 0.]
 [0. 0. 0. 1.]]

This method effectively converts the array of indices into a one-hot encoded array, where each row represents a one-hot encoded value of the corresponding index in a.

The above is the detailed content of How to Convert Index Arrays to One-Hot Encoded Arrays 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