0

不确定到底出了什么问题。但是,我的目标是建立一个交叉验证的 python 代码。我知道有各种指标,但我认为我使用的是正确的指标。我没有得到我想要的 CV10 结果,而是收到一个错误:

“标量变量的索引无效”

我在 StackOverflow 上发现了这一点: IndexError: invalid index to scalar variable 当您尝试索引 numpy 标量(例如 numpy.int64 或 numpy.float64)时发生。它与 TypeError 非常相似:'int' object has no attribute '_ getitem _' 当您尝试索引 int 时。

任何帮助,将不胜感激...

我正在尝试关注 :: http://scikit-learn.org/stable/modules/model_evaluation.html

from sklearn.ensemble import RandomForestClassifier
from sklearn import cross_validation
from numpy import genfromtxt
import numpy as np
from sklearn.metrics import accuracy_score

def main():
    #read in  data, parse into training and target sets
    dataset = genfromtxt(open('D:\\CA_DataPrediction_TrainData\\CA_DataPrediction_TrainDataGenetic.csv','r'), delimiter=',', dtype='f8')[1:]   
    target = np.array( [x[0] for x in dataset] )
    train = np.array( [x[1:] for x in dataset] )

    #In this case we'll use a random forest, but this could be any classifier
    cfr = RandomForestClassifier(n_estimators=10)

    #Simple K-Fold cross validation. 10 folds.
    cv = cross_validation.KFold(len(train), k=10, indices=False)

    #iterate through the training and test cross validation segments and
    #run the classifier on each one, aggregating the results into a list
    results = []
    for traincv, testcv in cv:
        pred = cfr.fit(train[traincv], target[traincv]).predict(train[testcv])
        results.append(accuracy_score(target[testcv], [x[1] for x in pred]) )

    #print out the mean of the cross-validated results
    print "Results: " + str( np.array(results).mean() )

if __name__=="__main__":
    main()
4

1 回答 1

2

你的pred变量只是一个预测列表,所以你不能索引它的元素(这是错误的原因)

results.append(accuracy_score(target[testcv], [x[1] for x in pred]) )

应该

results.append(accuracy_score(target[testcv], pred) )

或者如果你真的想要一份

results.append(accuracy_score(target[testcv], [x for x in pred]) )
于 2013-10-06T19:44:55.770 回答