-7

使用的变量的声明如下:

self.features = {}      #dictionary defined for storing the features and the values
self.featureNameList = []  #list to store the names and values of the features
self.featureCounts = collections.defaultdict(lambda: 1) #the counts of the features and labels
self.featureVectors = [] # 
self.labelCounts = collections.defaultdict(lambda: 0)            
def Classify(self):      #featureVector is a simple list like the ones that we use to train
    probabilityPerLabel = {}
    for label in self.labelCounts.keys():
        Prob = 0
        for featureValue in self.featureVectors:
            #print self.labelCounts[label]
            Prob+=self.featureCounts[[label][self.featureNameList[self.featureVectors.index(featureValue)]][featureValue]]/self.labelCounts[label]
            # Prob+= self.featureCounts(label, self.featureNameList[self.featureVectors.index(featureValue)], featureValue)/self.labelCounts[label]
        probabilityPerLabel[label] = (self.labelCounts[label]/sum(self.labelCounts.values())) * (Prob)
    print probabilityPerLabel
    return max(probabilityPerLabel, key = lambda classLabel: probabilityPerLabel[classLabel])

该错误是在该行产生的:

Prob+=self.featureCounts[[label][self.featureNameList[self.featureVectors.index(featureValue)]][featureValue]]/self.labelCounts[label]
4

1 回答 1

2

你的问题可能是:

[label][self.featureNameList[self.featureVectors.index(featureValue)]

在我看来,您正在制作一个长度为 1 的列表:

[label]

然后你试图通过索引从中获取一个元素:

[self.featureNameList[self.featureVectors.index(featureValue)]

但是外括号内的东西评估为一个字符串。并且字符串不能用于索引列表。

最终,这几乎肯定不是你想要做的,但我认为它解释了错误。一般来说,我建议您避免像这样非常长且令人困惑的 1 行,并使用临时(但恰当命名)变量将其分解为组成部分。这将使您的代码更容易理解,因此更容易编写和开发。

于 2012-11-21T14:20:31.663 回答