如何修复IndexError:标量变量的索引无效 [英] How to fix IndexError: invalid index to scalar variable
问题描述
此代码生成错误:
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]
推荐答案
您正尝试索引到标量(不可迭代)值中:
You are trying to index into a scalar (non-iterable) value:
[y[1] for y in y_test]
# ^ this is the problem
调用[y for y in test]
时,您已经在遍历这些值,因此您在y
中得到一个值.
When you call [y for y in test]
you are iterating over the values already, so you get a single value in 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
我不确定您要尝试进入结果数组中的什么,但是您需要摆脱[y[1] for y in y_test]
.
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_test中的每个y追加到结果中,则需要将列表理解进一步扩展为类似以下内容:
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:
[results.append(..., y) for y in y_test]
或仅使用for循环:
for y in y_test:
results.append(..., y)
这篇关于如何修复IndexError:标量变量的索引无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!