此代码生成错误:
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]
基本上,
1
不是y
的有效索引。如果访问者是从他自己的代码提交的,他应该检查他的y
是否包含他试图访问的索引(在本例中,索引是1
)。您正试图索引到标量(不可iterable)值:
当您调用
[y for y in test]
时,您已经在这些值上迭代了,所以您在y
中得到了一个值。您的代码与尝试执行以下操作相同:
我不知道你想在结果数组中加入什么,但是你需要去掉
[y[1] for y in y_test]
。如果你想将y-in-y测验中的每一个y附加到结果中,你需要进一步扩展你的列表理解能力,如下所示:
或者使用for循环:
相关问题 更多 >
编程相关推荐