如何修复索引器错误:标量变量的索引无效

2024-10-17 06:20:28 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码生成错误:

IndexError: invalid index to scalar variable.

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

怎么解决?

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]))

testcv是:

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

Tags: intestimportfalsetruefornptrain
2条回答

基本上,1不是y的有效索引。如果访问者是从他自己的代码提交的,他应该检查他的y是否包含他试图访问的索引(在本例中,索引是1)。

您正试图索引到标量(不可iterable)值:

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

当您调用[y for y in test]时,您已经在这些值上迭代了,所以您在y中得到了一个值。

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

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

我不知道你想在结果数组中加入什么,但是你需要去掉[y[1] for y in y_test]

如果你想将y-in-y测验中的每一个y附加到结果中,你需要进一步扩展你的列表理解能力,如下所示:

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

或者使用for循环:

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

相关问题 更多 >