TypeError:"float"对象无法解释为索引 [英] TypeError: 'float' object cannot be interpreted as an index
本文介绍了TypeError:"float"对象无法解释为索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到的是以前未曾发生过的问题,也许某些规则已更改.
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
推荐答案
问题可能出在Python随附的range
函数上.它的参数必须是整数.当n_examples
乘以0.5
时,n_train
变为浮点数.您只需要将其重新转换为int(n_examples * 0.5)
这样的int即可.这实际上是正确的做法.如果您有11
示例,那么没有5.5
培训和测试示例就没有意义了.
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.
这篇关于TypeError:"float"对象无法解释为索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文