python的one-hot编码怎么实现
在Python中,可以使用scikit-learn库中的OneHotEncoder类来实现one-hot编码。以下是一个简单的示例:
from sklearn.preprocessing import OneHotEncoder
# 创建一个OneHotEncoder对象
encoder = OneHotEncoder()
# 假设有一个包含3个类别的向量
categories = [[0], [1], [2]]
# 对该向量进行one-hot编码
encoded = encoder.fit_transform(categories)
# 输出编码结果
print(encoded.toarray())
输出结果为:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
这里将一个包含3个类别的向量进行了one-hot编码,得到了一个3x3的矩阵,每一行代表一个类别,其中只有一个元素为1,其余元素都为0。
原文地址: https://www.cveoy.top/t/topic/fsQ1 著作权归作者所有。请勿转载和采集!