怎么把分类的独热编码变成0,1,2
时间: 2023-10-15 20:08:07 浏览: 61
可以使用 `argmax` 函数来将独热编码转换为类别标签。具体方法如下:
1. 对于每个样本的独热编码,使用 `argmax` 函数找到其中值为1的位置,即为该样本所属的类别标签。
2. 将类别标签映射为0、1、2等整数编号,可以使用字典或者 sklearn 中的 `LabelEncoder` 类实现。
下面是一个简单的示例代码:
```python
import numpy as np
from sklearn.preprocessing import LabelEncoder
# 假设有3个类别
num_classes = 3
# 生成5个样本的独热编码
y_onehot = np.eye(num_classes)[np.random.randint(0, num_classes, size=5)]
print("独热编码:")
print(y_onehot)
# 将独热编码转换为类别标签
y_labels = np.argmax(y_onehot, axis=1)
print("类别标签:")
print(y_labels)
# 将类别标签映射为0、1、2等整数编号
label_encoder = LabelEncoder()
y_integers = label_encoder.fit_transform(y_labels)
print("整数编号:")
print(y_integers)
```
输出结果如下:
```
独热编码:
[[0. 1. 0.]
[0. 1. 0.]
[0. 0. 1.]
[0. 0. 1.]
[1. 0. 0.]]
类别标签:
[1 1 2 2 0]
整数编号:
[1 1 2 2 0]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)