72
62

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

scikit-learnのLabelEncoderの使い方

Posted at

はじめに

分類器にかける前に文字データを離散の数値に変換するときに使われる。細かい処理などはできないが、とりあいず離散数値にして分類器にかけたいときによく使います。

使い方

>>> le = preprocessing.LabelEncoder()
>>> le.fit(["paris", "paris", "tokyo", "amsterdam"])
LabelEncoder()
>>> list(le.classes_)
['amsterdam', 'paris', 'tokyo']
>>> le.transform(["tokyo", "tokyo", "paris"]) 
array([2, 2, 1]...)
>>> list(le.inverse_transform([2, 2, 1]))
['tokyo', 'tokyo', 'paris']

le.fit()の部分で変換したいデータを選択します。そしてle.transform()で数値へ変換します。

実際にタイタニックのデータを変換してみたいと思います。タイタニックのデータはseabornの中にあるのでそれを使います。

import seaborn as sns
import pandas as pd
from sklearn import preprocessing

titanic = sns.load_dataset("titanic")

for column in ['sex','class']:
#     print(titanic[column].shape)
    le = preprocessing.LabelEncoder()
    le.fit(titanic[column])
    titanic[column] = le.transform(titanic[column])

titanic

今回はsex,classを変換してみました。便利なので皆さんもぜひ使ってみてください。

参照

72
62
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
72
62

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?