Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'float' object cannot be interpreted as an index

I am facing an issue which was not occurring before, maybe some rules have been changed.

    Traceback (most recent call last)
    <ipython-input-3-f47687e192a7> in <module>()
          5 n_examples = X.shape[0]
          6 n_train = n_examples * 0.5
    ----> 7 train_idx = np.random.choice(range(0,n_examples), size=n_train, replace=False)
          8 test_idx = list(set(range(0,n_examples))-set(train_idx))
          9 X_train = X[train_idx]

    mtrand.pyx in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:18822)()

    TypeError: 'float' object cannot be interpreted as an index
like image 994
iMatrix Avatar asked Mar 10 '23 11:03

iMatrix


1 Answers

The issue might be with the range function, which comes with Python. Its arguments must be integers. n_train gets turned to a float when n_examples is multiplied by 0.5. You just need to reconvert it to an int like int(n_examples * 0.5). This is actually the correct thing to do. If you'd have 11 examples, it wouldn't make sense to have 5.5 training and test examples.

like image 172
Horia Coman Avatar answered Mar 20 '23 08:03

Horia Coman