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

廉价感情. 提交于 2020-02-01 05:44:05

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/43086584/typeerror-float-object-cannot-be-interpreted-as-an-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!