0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AI要素③ ワンホットエンコーディング

Posted at

AIの要素技術について記述します。ワンホットエンコーディングは、文字や単語を0と1で表したベクトルに変換し、AIが理解できる形にします。

サンプルプログラム

one_hot_encoding.py

AIに、単語をベクトルとして入力する

例1.
語彙: ['I', 'love', 'Python', 'hate', 'Java']
文: ['I', 'love', 'Python']
ワンホット: [ [1 0 0 0 0], [0 1 0 0 0], [0 0 1 0 0] ]

例2.
顧客データ:
{
"Name": ["Alice", "Bob", "Charlie", "Diana"],
"Gender": ["Female", "Male", "Male", "Female"],
"Region": ["Tokyo", "Osaka", "Nagoya", "Tokyo"]
}

「Female/Male」「Tokyo/Osaka/Nagoya」などのカテゴリを、ワンホットベクトルに変換する
「Gender と Region を連結した5次元ベクトル」になる

項目: Gender_Female Gender_Male Region_Nagoya Region_Osaka Region_Tokyo

Alice [1 0 0 0 1]
Bob [0 1 0 1 0]
Charlie [0 1 1 0 0]
Diana [1 0 0 0 1]

復元時には同じ処理を逆に行うだけなので、カテゴリとインデックスの対応が一貫している限り、どのような割り当てを選んでも問題ない

 

031_one_hot_encoding.py
import numpy as np

# 辞書を作成
vocab = ["I", "love", "Python", "hate", "Java"]
word_to_index = {word: idx for idx, word in enumerate(vocab)}

# 文章を単語リストに
sentence = ["I", "love", "Python"]

# ワンホットエンコード
one_hot = np.zeros((len(sentence), len(vocab)), dtype=int)
for i, word in enumerate(sentence):
    one_hot[i, word_to_index[word]] = 1

print("語彙:", vocab)
print("文:", sentence)
print("ワンホット:\n", one_hot)

結果
語彙: ['I', 'love', 'Python', 'hate', 'Java']
文: ['I', 'love', 'Python']
ワンホット:
 [[1 0 0 0 0]
 [0 1 0 0 0]
 [0 0 1 0 0]]
 

 

032_one_hot_encoding.py
import pandas as pd

# 顧客データ
df = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie", "Diana"],
    "Gender": ["Female", "Male", "Male", "Female"],
    "Region": ["Tokyo", "Osaka", "Nagoya", "Tokyo"]
})

# ワンホット化(ダミー変数化)
df_encoded = pd.get_dummies(df, columns=["Gender", "Region"])

print(df)
print(df_encoded)

結果
      Name  Gender  Region
0    Alice  Female   Tokyo
1      Bob    Male   Osaka
2  Charlie    Male  Nagoya
3    Diana  Female   Tokyo
      Name  Gender_Female  Gender_Male  Region_Nagoya  Region_Osaka  Region_Tokyo
0    Alice           True        False          False         False          True
1      Bob          False         True          False          True         False
2  Charlie          False         True           True         False         False
3    Diana           True        False          False         False          True

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?