LabelBinarizer进行单分类和多分类one-hot编码

LabelBinarizer进行单分类和多分类one-hot编码

此种场景适用的字符串, 之间没有天然内在顺序

5.1 Encoding Nominal Categorical Feature¶
feature
# 加载库   使用LabelBinarizer  进行one-hot编码
import numpy as np
from sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer
​
feature = np.array([
    ["Texas"],
    ["California"],
    ["Texas"],
    ["Delaware"],
    ["Texas"]
])
​
array([[0, 0, 1],
       [1, 0, 0],
       [0, 0, 1],
       [0, 1, 0],
       [0, 0, 1]])
feature
array([['Texas'],
       ['California'],
       ['Texas'],
       ['Delaware'],
       ['Texas']], dtype='<U10')
# feature
# create one-hot encoder   创建 one-hot编码
one_hot = LabelBinarizer()# one-hot encode feature 进行编码
one_hot.fit_transform(feature)
array([[0, 0, 1],
       [1, 0, 0],
       [0, 0, 1],
       [0, 1, 0],
       [0, 0, 1]])
  查看特征分类
# view feature classes  查看特征分类
one_hot.classes_
array(['California', 'Delaware', 'Texas'], dtype='<U10')
逆转换
# reverse one-hot encoding  逆转换
one_hot.inverse_transform(one_hot.transform(feature))
array(['Texas', 'California', 'Texas', 'Delaware', 'Texas'], dtype='<U10')
变量
import pandas as pd
​
# 加载库   创建虚拟变量
pd.get_dummies(feature[:, 0])
California	Delaware	Texas
0	0	0	1
1	1	0	0
2	0	0	1
3	0	1	0
4	0	0	1
# create multiclass feature  处理多个分类特征
multiclass_feature = [
    ("Texas", "Florida"),
    ("California", "Alabama"),
    ("Texas", "Florida"),
    ("Delaware", "Florida"),
    ("Texas", "Alabama")
]
​
​
multiclass_feature
​
# create multiclass one-hot encoder
one_hot_multiclass = MultiLabelBinarizer()# one-hot encode multiclass feature
one_hot_multiclass.fit_transform(multiclass_feature)
array([[0, 0, 0, 1, 1],
       [1, 1, 0, 0, 0],
       [0, 0, 0, 1, 1],
       [0, 0, 1, 1, 0],
       [1, 0, 0, 0, 1]])
# view classes  查看分类
one_hot_multiclass.classes_
array(['Alabama', 'California', 'Delaware', 'Florida', 'Texas'],
      dtype=object)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值