Python 如何修复 IndexError:标量变量的无效索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32978575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:34:06  来源:igfitidea点击:

How to fix IndexError: invalid index to scalar variable

pythonnumpypandas

提问by Klausos Klausos

This code generates error:

此代码生成错误:

IndexError: invalid index to scalar variable.

at the line: results.append(RMSPE(np.expm1(y_train[testcv]), [y[1] for y in y_test]))

在线: results.append(RMSPE(np.expm1(y_train[testcv]), [y[1] for y in y_test]))

How to fix it?

如何解决?

import pandas as pd
import numpy as np
from sklearn import ensemble
from sklearn import cross_validation

def ToWeight(y):
    w = np.zeros(y.shape, dtype=float)
    ind = y != 0
    w[ind] = 1./(y[ind]**2)
    return w

def RMSPE(y, yhat):
    w = ToWeight(y)
    rmspe = np.sqrt(np.mean( w * (y - yhat)**2 ))
    return rmspe

forest = ensemble.RandomForestRegressor(n_estimators=10, min_samples_split=2, n_jobs=-1)

print ("Cross validations")
cv = cross_validation.KFold(len(train), n_folds=5)

results = []
for traincv, testcv in cv:
    y_test = np.expm1(forest.fit(X_train[traincv], y_train[traincv]).predict(X_train[testcv]))
    results.append(RMSPE(np.expm1(y_train[testcv]), [y[1] for y in y_test]))

testcvis:

testcv是:

[False False False ...,  True  True  True]

采纳答案by Monkpit

You are trying to index into a scalar (non-iterable) value:

您正在尝试索引标量(不可迭代)值:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test]you are iterating over the values already, so you get a single value in y.

当您调用时,[y for y in test]您已经在迭代这些值,因此您在y.

Your code is the same as trying to do the following:

您的代码与尝试执行以下操作相同:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

我不确定您想将什么放入结果数组中,但是您需要摆脱[y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

如果您想将 y_test 中的每个 y 附加到结果中,您需要将列表理解进一步扩展为如下所示:

[results.append(..., y) for y in y_test]

Or just use a for loop:

或者只是使用 for 循环:

for y in y_test:
    results.append(..., y)

回答by gies0r

Basically, 1is not a valid index of y. If the visitor is comming from his own code he should check if his ycontains the index which he tries to access (in this case the index is 1).

基本上,1不是 的有效索引y。如果访问者来自他自己的代码,他应该检查他的代码是否y包含他试图访问的索引(在这种情况下,索引是1)。