keras 中的 One-hot 编码标签 [英] One-hot encode labels in keras

查看:55
本文介绍了keras 中的 One-hot 编码标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组来自 CSV 文件中标签列的整数 - [1,2,4,3,5,2,..].类的数量为5,即16的范围.我想使用以下代码对它们进行单热编码.

I have a set of integers from a label column in a CSV file - [1,2,4,3,5,2,..]. The number of classes is 5 ie range of 1 to 6. I want to one-hot encode them using the below code.

y = df.iloc[:,10].values
y = tf.keras.utils.to_categorical(y, num_classes = 5)
y

但是这段代码给了我一个错误

But this code gives me an error

IndexError: index 5 is out of bounds for axis 1 with size 5

我该如何解决这个问题?

How can I fix this?

推荐答案

如果使用 tf.keras.utils.to_categorical 对标签向量进行 one-hot,则整数应从 开始0num_classes来源.在您的情况下,您应该执行以下操作

If you use tf.keras.utils.to_categorical to one-hot the label vector, the integers should start from 0 to num_classes, source. In your case, you should do as follows

import tensorflow as tf 
import numpy as np 

a = np.array([1,2,4,3,5,2,4,2,1])
y_tf = tf.keras.utils.to_categorical(a-1, num_classes = 5)
y_tf

array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 1.],
       [0., 1., 0., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 1., 0., 0., 0.],
       [1., 0., 0., 0., 0.]], dtype=float32)

或者,您可以使用 pd.get_dummies,

import pandas as pd 
import numpy as np 

a = np.array([1,2,4,3,5,2,4,2,1])
a_pd = pd.get_dummies(a).astype('float32').values 
a_pd

array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 1.],
       [0., 1., 0., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 1., 0., 0., 0.],
       [1., 0., 0., 0., 0.]], dtype=float32)

这篇关于keras 中的 One-hot 编码标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆