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:
<code class="python">b = np.zeros((a.size, a.max() + 1))</code>
<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!