Home > Article > Backend Development > 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:
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!