作用: 将非数值标签转换为数值标签
先看下官方是怎么说的: 官方地址
- Encode target labels with value between 0 and n_classes-1.
- 将 目标标签的值 编码为 1 到 n-1, (一共n个分类)
- This transformer should be used to encode target values, i.e. y, and not the input X.
- 这个转换 应该被适用于 编码 标签的值,比如 y, 而不是用于编码输入值,比如 x
举例
import numpy as np import pandas as pd import sklearn.preprocessing as preprocessing city = pd.Series(["paris", "paris", "tokyo", "amsterdam"]) le = preprocessing.LabelEncoder() le.fit(city) list(le.classes_) # 查看标签去重后的类别 # ['amsterdam', 'paris', 'tokyo'] # 标签值转化,可以理解为,将非数字标签映射到数字标签 le.transform(city) # 输出为: array([1, 1, 2, 0]) # 反转化,将数字标签还原为非数字标签 list(le.inverse_transform([1, 1, 2, 0])) # ['tokyo', 'tokyo', 'paris']
以上涉及到的3个方法:
- le.fit(df) : 将标签去重,生成类别,并编码为数字化的标签
- le.transform(df) :将原数据标签全部映射到 数字标签上
- le.inverse_transform(list) : 将数字标签 反转换为 非数字标签



