我正面临一个以前没有发生过的问题,也许某些规则已更改。

    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_train 乘以 n_examples 时,0.5 变为浮点数。您只需要将其重新转换为 int 类型 int(n_examples * 0.5) 。这实际上是正确的做法。如果您有 11 示例,那么拥有 5.5 训练和测试示例就没有意义了。

关于python - 类型错误 : 'float' object cannot be interpreted as an index,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43086584/

10-15 22:47