to_categorical() missing 1 required positional arg

2019-08-24 13:13发布

问题:

I am trying to run example from https://github.com/tflearn/tflearn/blob/master/examples/nlp/bidirectional_lstm.py on jupyter notebook. Since I am new on Tflearn, Jupyter and DNN I could not debug what is the error and how to resolve it. The error look like:

`TypeError                                 Traceback (most recent call last)
<ipython-input-1-fa67bb48a391> in <module>()
     38 testX = pad_sequences(testX, maxlen=100, value=0.)
     39 # Converting labels to binary vectors
---> 40 trainY = to_categorical(trainY)
     41 testY = to_categorical(testY)
     42 

TypeError: to_categorical() missing 1 required positional argument: 'nb_classes'`

Also I could not understand how it is loading the dataset. Thank you!

回答1:

In the latest stable version of TFLearn (0.3.2 at the time of writing), installed with pip, the argument nb_classes is necessary:

import tflearn
from tflearn.data_utils import to_categorical
from tflearn.datasets import imdb
train, test, _ = imdb.load_data(path = 'imdb.pkl', n_words = 10000, valid_portion = 0.1)
trainX, trainY = train
testX, testY = test

trainY[0:5]
# [0, 0, 0, 1, 0]

# this gives error:
trainY = to_categorical(trainY)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-4a293ba390bc> in <module>()
----> 1 trainY = to_categorical(trainY) #, nb_classes=2)

TypeError: to_categorical() takes exactly 2 arguments (1 given)

Essentially, this is the same error message with the one you get, despite the different wording; including nb_classes=2 resolves it:

trainY = to_categorical(y=trainY, nb_classes=2) 
trainY[0:5]
# array([[ 1.,  0.],
#        [ 1.,  0.],
#        [ 1.,  0.],
#        [ 0.,  1.],
#        [ 1.,  0.]])

So, what I suggest is:

  • Uninstall your current TFLearn
  • Install the latest stable version with pip install tflearn
  • Include the argument nb_classes=2 in to_categorical

Of course, simply updating your code with nb_classes=2 might work, but it also might not - see this question and my answer there.



回答2:

I encounter thr same issue.

It looks like the tflearn version is too low and only in the newer version the nb_classes argument is no longer required.

You can either try update to the newest version of it. (Not from pip install tflearn. Until now--2017/10/25--it's not new enough.) pip install git+https://github.com/tflearn/tflearn.git

Or you can just add the extra argument, which is a integer indicating the total number of classes, which may vary according to your dataset used.