one_hot: 用于类标签数组的独热编码函数
一个用于对类标签执行独热编码的函数。
从 mlxtend.preprocessing 导入 one_hot
概述
典型的用于分类的监督机器学习算法假设类标签是名义的(类别的一种特殊情况,不暗示顺序)。名义特征的一个典型例子是“颜色”,因为我们不能说(在大多数应用中)“橙色 > 蓝色 > 红色”。
one_hot
函数提供了一个简单的接口,用于将类标签整数转换为所谓的独热数组,其中每个唯一标签在新数组中表示为一个列。
例如,假设我们有来自 3 个不同类别:0、1 和 2 的 5 个数据点。
y = [0, # sample 1, class 0
1, # sample 2, class 1
0, # sample 3, class 0
2, # sample 4, class 2
2] # sample 5, class 2
独热编码后,我们得到以下数组(请注意,每行中“1”的索引位置表示该样本的类标签)
y = [[1, 0, 0], # sample 1, class 0
[0, 1, 0], # sample 2, class 1
[1, 0, 0], # sample 3, class 0
[0, 0, 1], # sample 4, class 2
[0, 0, 1] # sample 5, class 2
])
示例 1 - 默认
from mlxtend.preprocessing import one_hot
import numpy as np
y = np.array([0, 1, 2, 1, 2])
one_hot(y)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
示例 2 - Python 列表
from mlxtend.preprocessing import one_hot
y = [0, 1, 2, 1, 2]
one_hot(y)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
示例 3 - 整数数组
from mlxtend.preprocessing import one_hot
y = [0, 1, 2, 1, 2]
one_hot(y, dtype='int')
array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[0, 1, 0],
[0, 0, 1]])
示例 4 - 任意数量的类标签
from mlxtend.preprocessing import one_hot
y = [0, 1, 2, 1, 2]
one_hot(y, num_labels=10)
array([[ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.]])
API
one_hot(y, num_labels='auto', dtype='float')
类标签的独热编码
参数
-
y
: 类似数组,形状 = [n_classlabels]由类标签组成的 Python 列表或 numpy 数组。
-
num_labels
: int 或 'auto'类标签数组中唯一标签的数量。如果设置为 'auto',则从输入数组推断唯一标签的数量。
-
dtype
: str输出数组的 NumPy 数组类型(float, float32, float64)。
返回
-
ary
: numpy.ndarray, 形状 = [n_classlabels]独热编码数组,其中每个样本在返回数组中表示为一个行向量。
示例
有关使用示例,请参阅 https://mlxtend.cn/mlxtend/user_guide/preprocessing/one_hot/