Python keras: to_categorical for multilabel values gives ValueError: invalid literal for int() with base 10

Viewed 1530

I have a training set y_train( which has 8 unique classes) derived using train_test_split on my dataset.

y_train

    2019       AD
    777     QUERY
    282      INFO
    1879     REAL
    910     QUERY
        ...  
    997     QUERY
    510      FAKE
    252      REAL
    1334     FAKE
    1579     INFO
    Name: target, Length: 1653, dtype: object

Now when I run to_categorical on this set I get this error.

y_train = to_categorical(np.asarray(y_train),8, dtype='O')

     41     """
     42 
---> 43     y = np.array(y, dtype='int')
     44     input_shape = y.shape
     45     if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:

ValueError: invalid literal for int() with base 10: 'AD'

I have also tried the y_train = to_categorical(np.asarray(y_train)) but it gives the same error, which I cannot figure out why? The dtype is 'object' of my training set and I am setting it as dtype = 'O' so what seems to be the problem?

1 Answers

This worked.

y_train = to_categorical(np.asarray(y_train.factorize()[0]))

The factorize() method encodes each string to a categorical value because to_categorical can only take dtpye of int or float

Related