Skip to content
This repository
tree: fb27a4085e
Fetching contributors…

Cannot retrieve contributors at this time

file 46 lines (40 sloc) 1.655 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
from sklearn.naive_bayes import GaussianNB
from Data import DataSet
import numpy as np

class SciKitLearner(object):
   def __init__(self, testSet, trainSet, classifiers, learner):
      assert(isinstance(testSet, DataSet))
      assert(isinstance(trainSet, DataSet))
      assert(isinstance(classifiers, list))
      classes = [1, 0]
      classMap = {True: 1, False: 0}
      self.inverseClassMap = {1: 'Truth', 0: 'Lie'}

      testFeatures = []
      testClasses = []
      trainFeatures = []
      trainClasses = []

      self.classifiers = classifiers

      for instance in testSet:
         testFeature = []
         for classifier in classifiers:
            testFeature.append(classifier.build(instance))
         testFeatures.append(testFeature)
         testClasses.append(classMap[instance.isTrue])
      for instance in trainSet:
         trainFeature = []
         for classifier in classifiers:
            trainFeature.append(classifier.build(instance))
         trainFeatures.append(trainFeature)
         trainClasses.append(classMap[instance.isTrue])

      self.learner = learner.fit(trainFeatures, trainClasses)
      pred_class = self.learner.predict(testFeatures)
      total_errors = (pred_class != np.array(testClasses)).sum()
      self.accuracy = 1.0 - float(total_errors)/float(len(testClasses))

   def classify(self, instances):
      features = []
      for instance in instances:
         feature = []
         for classifier in self.classifiers:
            feature.append(classifier.build(instance))
         features.append(feature)
      return map(lambda r: self.inverseClassMap[r], self.learner.predict(features))
Something went wrong with that request. Please try again.