3
此代碼生成錯誤:如何解決IndexError:無效的指數標量
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]
y [1]在最後一行的期望值是多少?您正在迭代y_test值,那麼示例值是什麼? – Monkpit
http://stackoverflow.com/questions/13594507/what-does-it-mean-to-have-an-index-to-scalar-variable-error-python –
@Monkey:y_test values:[6175.36384809 6267.20711569 5783.46657446。 ..,4323.34539658 4332.18318557 3481.93371173] –