如何修复 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]

原文由 Klausos Klausos 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.5k
2 个回答

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

 [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_test 中的每个 y 附加到结果,您需要将列表理解进一步扩展到如下所示:

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

或者只使用 for 循环:

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

原文由 Kyle Pittman 发布,翻译遵循 CC BY-SA 3.0 许可协议

YOLO 物体检测

layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

不需要在 layer_names[i[0] - 1] 中索引 i 。只需将其删除并执行 layer_names[i - 1]

layer_names = net.getLayerNames() output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

它对我有用

原文由 Tejas Veer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题