LoginSignup
42
34

More than 5 years have passed since last update.

整数値のベクトルをone hot表現に変換

Last updated at Posted at 2017-05-22

クラス分類問題などで、整数値のベクトルをone hot表現に変換する場合、
pythonではnumpyを使って以下のように変換できる。

python
import numpy as np

target_vector = [0,2,1,3,4]               # クラス分類を整数値のベクトルで表現したもの
n_labels = len(np.unique(target_vector))  # 分類クラスの数 = 5
np.eye(n_labels)[target_vector]           # one hot表現に変換
実行して得られるone-hot表現
array([[ 1.,  0.,  0.,  0.,  0.],   # 0
       [ 0.,  0.,  1.,  0.,  0.],   # 2
       [ 0.,  1.,  0.,  0.,  0.],   # 1
       [ 0.,  0.,  0.,  1.,  0.],   # 3
       [ 0.,  0.,  0.,  0.,  1.]])  # 4

参考

42
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
34