Kla*_*sos 7 python numpy pandas
此代码生成错误:
IndexError: invalid index to scalar variable.
Run Code Online (Sandbox Code Playgroud)
在线: 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]))
Run Code Online (Sandbox Code Playgroud)
testcv 是:
[False False False ..., True True True]
Run Code Online (Sandbox Code Playgroud)
Tej*_*eer 27
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()]
它对我有用
您正在尝试索引标量(不可迭代)值:
[y[1] for y in y_test]
# ^ this is the problem
Run Code Online (Sandbox Code Playgroud)
当你打电话时,[y for y in test]你正在迭代这些值,所以你得到一个值y.
您的代码与尝试执行以下操作相同:
y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail
Run Code Online (Sandbox Code Playgroud)
我不确定你想要进入你的结果数组,但是你需要摆脱它[y[1] for y in y_test].
如果要将y_test中的每个y附加到结果中,则需要将列表推导进一步扩展为以下内容:
[results.append(..., y) for y in y_test]
Run Code Online (Sandbox Code Playgroud)
或者只使用for循环:
for y in y_test:
results.append(..., y)
Run Code Online (Sandbox Code Playgroud)