One-hot Encoding ๊ตฌํ
๐ ๋ฌธ์ : One-Hot Encoding of Nominal Values
์ค๋ช
๋ช ๋ชฉํ(Nominal) ๊ฐ์ด ํฌํจ๋ 1์ฐจ์ numpy ๋ฐฐ์ด์ ์ ๋ ฅ๋ฐ์ One-Hot Encoding์ ์ํํ๋ ํจ์๋ฅผ ์์ฑํ์ธ์.
ํจ์๋ np.ndarray ํ์ ์ 1D ์ ์ ๋ฐฐ์ด x๋ฅผ ์ ๋ ฅ์ผ๋ก ๋ฐ๊ณ ,
์ ํ์ ์ผ๋ก n_col (์ถ๋ ฅ ํ๋ ฌ์ ์ด ๊ฐ์)์ ์ง์ ํ ์ ์์ต๋๋ค.
๋ง์ฝ n_col์ด ์ ๊ณต๋์ง ์์ผ๋ฉด, ์๋์ผ๋ก x์ ์ต๋๊ฐ์ ๊ธฐ์ค์ผ๋ก ์ค์ ํด์ผ ํฉ๋๋ค.์กฐ๊ฑด
- x์ ๊ฐ ๊ฐ์ 0 ์ด์์ด๋ฉฐ, x์ ์์ ๊ฐ์๋งํผ ํ(row) ์ ๋ง๋ค๊ณ ,
- x์ ๊ณ ์ ๊ฐ ๊ฐ์๋งํผ ์ด(column) ์ ์์ฑํ์ฌ ํด๋น ํด๋์ค ์์น์ 1์ ํ ๋นํ์ธ์.
- ๋ฐ๋ณต๋ฌธ ์์ด numpy์ ๋ฒกํฐ ์ฐ์ฐ์ ์ฌ์ฉํ์ฌ ๊ตฌํํ์ธ์.
์์
x = np.array([0, 1, 2, 1, 0]) output = to_categorical(x) print(output)
์ถ๋ ฅ:
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.] [0. 1. 0.] [1. 0. 0.]]
โ ์ ๋ต ์ฝ๋
import numpy as np
def to_categorical(x, n_col=None):
if n_col is None:
n_col = np.max(x) + 1 # ํด๋์ค ๊ฐ์ ๊ฒฐ์
one_hot = np.zeros((x.shape[0], n_col)) # (์ํ ์, ํด๋์ค ๊ฐ์) ํฌ๊ธฐ์ 0 ํ๋ ฌ ์์ฑ
one_hot[np.arange(x.shape[0]), x] = 1 # ํ ์ธ๋ฑ์ค์ ์ด ์ธ๋ฑ์ค๋ฅผ ํ์ฉํ์ฌ 1 ํ ๋น
return one_hot
# ์์ ์คํ
x = np.array([0, 1, 2, 1, 0])
output = to_categorical(x)
print(output)
๐ ์ฝ๋ ์ค๋ช
1๏ธโฃ n_col ๊ฒฐ์ (์ด ๊ฐ์)
if n_col is None:
n_col = np.max(x) + 1
- n_col์ด ์ง์ ๋์ง ์์๋ค๋ฉด, x์์ ๊ฐ์ฅ ํฐ ๊ฐ(np.max(x))์ ๊ธฐ์ค์ผ๋ก +1์ ํ์ฌ ํด๋์ค ๊ฐ์๋ฅผ ๊ฒฐ์ ํฉ๋๋ค.
- ์๋ฅผ ๋ค์ด x = [0, 1, 2, 1, 0] ์ด๋ฉด, ํด๋์ค 0, 1, 2๊ฐ ์กด์ฌํ๋ฏ๋ก n_col = 3์ด ๋ฉ๋๋ค.
2๏ธโฃ One-Hot ํ๋ ฌ ์ด๊ธฐํ
one_hot = np.zeros((x.shape[0], n_col))
- (์ํ ๊ฐ์, ํด๋์ค ๊ฐ์) ํฌ๊ธฐ์ 0 ํ๋ ฌ์ ์์ฑํฉ๋๋ค.
- ์์ ์์ x.shape[0] = 5, n_col = 3 ์ด๋ฏ๋ก one_hot์ ํฌ๊ธฐ๋ (5, 3)์ด ๋ฉ๋๋ค.
3๏ธโฃ ํต์ฌ ์ฝ๋: One-Hot Encoding ์ ์ฉ
one_hot[np.arange(x.shape[0]), x] = 1
์ด ์ฝ๋์ ์๋ฏธ๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:
- np.arange(x.shape[0]) → [0, 1, 2, 3, 4] (ํ ์ธ๋ฑ์ค)
- x ์์ฒด๊ฐ ์ด ์ธ๋ฑ์ค → [0, 1, 2, 1, 0]
- ๋ฐ๋ผ์:
๊ฒฐ๊ณผ์ ์ผ๋ก ๋ค์๊ณผ ๊ฐ์ one_hot ํ๋ ฌ์ด ์์ฑ๋ฉ๋๋ค:one_hot[0, 0] = 1 # ์ฒซ ๋ฒ์งธ ์ํ → 0๋ฒ ํด๋์ค one_hot[1, 1] = 1 # ๋ ๋ฒ์งธ ์ํ → 1๋ฒ ํด๋์ค one_hot[2, 2] = 1 # ์ธ ๋ฒ์งธ ์ํ → 2๋ฒ ํด๋์ค one_hot[3, 1] = 1 # ๋ค ๋ฒ์งธ ์ํ → 1๋ฒ ํด๋์ค one_hot[4, 0] = 1 # ๋ค์ฏ ๋ฒ์งธ ์ํ → 0๋ฒ ํด๋์ค
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.] [0. 1. 0.] [1. 0. 0.]]
๐ฏ ์ถ๊ฐ ์ค๋ช : one_hot[np.arange(x.shape[0]), x] = 1 ์๋ ์๋ฆฌ
one_hot[row_indices, col_indices] = 1
- row_indices = np.arange(x.shape[0]) → [0, 1, 2, 3, 4] (ํ ๋ฒํธ)
- col_indices = x → [0, 1, 2, 1, 0] (๊ฐ ํ์ด ์ํ ์ด ๋ฒํธ)
- ๋ฐ๋ผ์ ๊ฐ (ํ, ์ด) ์์น์ 1์ ๋ฃ๋ ํจ๊ณผ๋ฅผ ๊ฐ์ง๋๋ค.
โ ๋ฐ๋ณต๋ฌธ ์์ด ๋ฒกํฐ ์ฐ์ฐ์ ์ฌ์ฉํ๋ฏ๋ก ๋น ๋ฅด๊ณ ํจ์จ์ ์ ๋๋ค! ๐
์ด๊ฒ์ด ํฌ์ ์ธ๋ฑ์ฑ!
๐ฅ ๋ฐ๋ณต๋ฌธ์ ์ฌ์ฉํ๋ฉด ์ด๋ป๊ฒ ๋ ๊น?
for i in range(x.shape[0]):
one_hot[i, x[i]] = 1
ํ์ง๋ง numpy์ ๋ฒกํฐ ์ฐ์ฐ์ ์ฌ์ฉํ๋ฉด ๋ฐ๋ณต๋ฌธ ์์ด ๋ ๋น ๋ฅด๊ฒ ์ํํ ์ ์์ต๋๋ค!
์ฆ, one_hot[np.arange(x.shape[0]), x] = 1์ ์ ๋ฐ๋ณต๋ฌธ์ ์ต์ ํ๋ ๋ฒ์ ์
๋๋ค. โ
๐ฏ ์ต์ข ์ ๋ฆฌ
โ One-Hot Encoding์ ์ํํ๋ to_categorical() ํจ์ ๊ตฌํ
โ ๋ฒกํฐ ์ฐ์ฐ(np.arange)์ ํ์ฉํ์ฌ ๋ฐ๋ณต๋ฌธ ์์ด ๋น ๋ฅด๊ฒ ์คํ
โ (ํ, ์ด) ์ธ๋ฑ์ค๋ฅผ ํ์ฉํด ํ ๋ฒ์ ์ํ๋ ์์น์ 1์ ํ ๋น
โ ์ต์ ํ๋ One-Hot Encoding์ ์ดํดํ๊ณ ํ์ฉํ ์ ์์