Search code examples
pythonkerasneural-networkdeep-learningconv-neural-network

The method np_utils.to_categorical give me an error


np_utils.to_categorical Keras method give me an error when i gived it a a vector of [962] element which contain 3 classes [1,1,1,...,2,2,2,...3,3,3].

The used code:

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

and i get this error:

---------------------------------------------------------------------------
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

Solution

  • As mentioned in the method documentation:

    Arguments

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

    So when you pass num_classes=3 it expects elements of y to be in {0, 1, 2}. You could simply convert your data to this zero-based format:

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