类别标签嵌入成为数字的代码
时间: 2024-02-22 20:58:39 浏览: 14
将类别标签嵌入成数字通常有两种方法:Label Encoding 和 One-Hot Encoding。
下面是使用Python实现这两种方法的代码示例:
```
# Label Encoding
from sklearn.preprocessing import LabelEncoder
# 定义标签
labels = ['cat', 'dog', 'bird', 'cat', 'dog', 'dog']
# 创建LabelEncoder对象
le = LabelEncoder()
# 将标签编码为数字
label_encoded = le.fit_transform(labels)
print(label_encoded) # 输出:[0 1 2 0 1 1]
# One-Hot Encoding
from sklearn.preprocessing import OneHotEncoder
# 将标签转换为二维数组形式
labels = [['cat'], ['dog'], ['bird'], ['cat'], ['dog'], ['dog']]
# 创建OneHotEncoder对象
enc = OneHotEncoder(handle_unknown='ignore')
# 将标签转换为One-Hot编码
onehot_encoded = enc.fit_transform(labels).toarray()
print(onehot_encoded) # 输出:[[1. 0. 0.], [0. 1. 0.], [0. 0. 1.], [1. 0. 0.], [0. 1. 0.], [0. 1. 0.]]
```
在Label Encoding中,使用LabelEncoder对象的`fit_transform()`方法将标签编码为数字,不同的标签被编码为不同的数字。在One-Hot Encoding中,使用OneHotEncoder对象的`fit_transform()`方法将标签转换为二维数组形式,并将其转换为One-Hot编码,每个标签被编码为一个长度为类别数的向量,向量中只有一个元素为1,其余元素为0,表示该标签属于对应的类别。