diff --git a/p5_classification/answers.py b/p5_classification/answers.py index dd38ce8..163ffd8 100644 --- a/p5_classification/answers.py +++ b/p5_classification/answers.py @@ -13,4 +13,4 @@ def q2(): - "*** YOUR CODE HERE ***" + return 'a' diff --git a/p5_classification/perceptron.py b/p5_classification/perceptron.py index b3a17b7..bf7ad9a 100644 --- a/p5_classification/perceptron.py +++ b/p5_classification/perceptron.py @@ -54,8 +54,14 @@ class PerceptronClassifier: for iteration in range(self.max_iterations): print "Starting iteration ", iteration, "..." for i in range(len(trainingData)): - "*** YOUR CODE HERE ***" - util.raiseNotDefined() + datum, expectedLabel = trainingData[i], trainingLabels[i] + vectors = util.Counter() + for l in self.legalLabels: + vectors[l] = self.weights[l] * datum + highestScoreLabel = vectors.argMax() + if highestScoreLabel != expectedLabel: + self.weights[expectedLabel] = self.weights[expectedLabel] + datum + self.weights[highestScoreLabel] = self.weights[highestScoreLabel] - datum def classify(self, data ): """ @@ -77,9 +83,8 @@ class PerceptronClassifier: """ Returns a list of the 100 features with the greatest weight for some label """ - featuresWeights = [] - - "*** YOUR CODE HERE ***" - util.raiseNotDefined() - + featureWeightTuples = self.weights[label].items() + weightFeatureTuples = [(w, f) for f, w in featureWeightTuples] + weightFeatureTuples.sort(reverse=True) + featuresWeights = [feature for _, feature in weightFeatureTuples[:100]] return featuresWeights