LoginSignup
20
13

More than 5 years have passed since last update.

kerasでOne-hotのラベルを作成する

Posted at

はじめに

kerasで分類を行う際,教師ラベルはOne-hotベクトル(1-of-k表現)にしなければならないので,簡単にOne-hotベクトルを作成する方法を備忘録としてまとめます.

One-hot

1つだけHigh(1)で他はLow(0)で表現されるビット列のこと.(Wikipedia)
例) 2を3次元のOne-hotで表現する場合は(0, 0, 1)となる.

作り方

環境

  • Python 3.6.0 :: Anaconda custom (64-bit)
  • keras 2.0.4 (backend: Tensorflow)
  • Tensorflow 1.1.0

コード

import numpy as np
from keras.utils import np_utils
# Using TensorFlow backend.

y = np.array([0, 1, 0, 2, 0, 1, 0, 2])  # 元のラベル
# array([0, 1, 0, 2, 0, 1, 0, 2])

one_hot_y = np_utils.to_categorical(y)  # One-hotにしたラベル
# array([[ 1.,  0.,  0.],
#        [ 0.,  1.,  0.],
#        [ 1.,  0.,  0.],
#        [ 0.,  0.,  1.],
#        [ 1.,  0.,  0.],
#        [ 0.,  1.,  0.],
#        [ 1.,  0.,  0.],
#        [ 0.,  0.,  1.]])

以上です.
最大値に合わせてその次元数のOne-hotを作成してくれるのがいいですね.

おわりに

  • 一行で済むので楽ですね.
  • 今後も自分の備忘録的なものになっていきそうな予感….
20
13
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
20
13