keras 中的 One-hot 编码标签

emm*_*asa 5 keras tensorflow one-hot-encoding

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

y = df.iloc[:,10].values
y = tf.keras.utils.to_categorical(y, num_classes = 5)
y
Run Code Online (Sandbox Code Playgroud)

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

IndexError: index 5 is out of bounds for axis 1 with size 5
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

M.I*_*nat 8

如果您使用tf.keras.utils.to_categoricalone-hot 标签向量,则整数应从0to num_classes、source开始。对于您的情况,您应该执行以下操作

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)
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用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)
Run Code Online (Sandbox Code Playgroud)