Note

Numpy (51) 본문

Numpy

Numpy (51)

알 수 없는 사용자 2022. 9. 17. 00:00
728x90

How to generate one-hot encodings for an array in numpy?

# Input:
np.random.seed(101) 
arr = np.random.randint(1,4, size=6)
arr

# output
array([2, 3, 2, 2, 2, 1])

# Solution:
def one_hot_encodings(arr):
    uniqs = np.unique(arr)
    out = np.zeros((arr.shape[0], uniqs.shape[0]))
    for i, k in enumerate(arr):
        out[i, k-1] = 1
    return out

one_hot_encodings(arr)

# output
 array([[ 0.,  1.,  0.],
        [ 0.,  0.,  1.],
        [ 0.,  1.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  1.,  0.],
        [ 1.,  0.,  0.]])

# Method 2:
(arr[:, None] == np.unique(arr)).view(np.int8)

'Numpy' 카테고리의 다른 글

Numpy (53)  (0) 2022.09.21
Numpy (52)  (0) 2022.09.20
Numpy (50)  (0) 2022.09.16
Numpy (49)  (0) 2022.09.15
Numpy (48)  (0) 2022.09.14
Comments