np_utils.to_categorical方法给我一个错误

时间:2019-05-19 04:22:36

标签: python keras neural-network deep-learning conv-neural-network

np_utils.to_categorical Keras方法给我一个包含三个类别的[962]元素矢量的错误,该向量包含3个类[1,1,1,...,2,2,2,... 3,3 ,3]。

使用的代码:

from keras.utils import np_utils
Y_train = np_utils.to_categorical(testY, 3)

我得到这个错误:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-24-9b7d3117ff6a> in <module>()
      1 print(trainY[720])
----> 2 Y_train = np_utils.to_categorical(testY, 3)
      3 print(Y_train[100])

/usr/local/lib/python3.6/dist-packages/keras/utils/np_utils.py in to_categorical(y, num_classes, dtype)
     32     n = y.shape[0]
     33     categorical = np.zeros((n, num_classes), dtype=dtype)
---> 34     categorical[np.arange(n), y] = 1
     35     output_shape = input_shape + (num_classes,)
     36     categorical = np.reshape(categorical, output_shape)

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

2 个答案:

答案 0 :(得分:1)

method documentation中所述:

  

参数

y: class vector to be converted into a matrix (integers from 0 to num_classes).
num_classes: total number of classes.

因此,当您传递num_classes=3时,它会期望y的元素位于{0, 1, 2}中。 您可以将数据简单地转换为从零开始的格式:

Y_test = np_utils.to_categorical(testY - 1, 3)

答案 1 :(得分:1)

请尝试此操作,它对我有用-

y_train = keras.utils.to_categorical(y_train,num_classes,dtype ='float32')

y_test = keras.utils.to_categorical(y_test,num_classes,dtype ='float32')