def trainUP(tm, sequences, up=None, trials=trials, clearhistory=True, verbose=0):

  for i in range(trials):
    for j, sensorPattern in enumerate(sequences):
      if sensorPattern is None:
        tm.reset()
        if up is not None:
          up.reset()
      else:
        if up is None:
          feedback = set()
        else:
          feedback = set(np.nonzero(up.getUnionSDR())[0])
        tm.compute(sensorPattern, activeApicalCells=feedback,
                   learn=True, sequenceLabel=None)
        if up is not None:
          activeCells, predActiveCells, burstingCols, = getUnionTemporalPoolerInput(tm)
          up.compute(activeCells, predActiveCells, learn=False)

    if clearhistory:
      if i == trials-1:
        if verbose > 0:
          print " TM metrics after training"
          print MonitorMixinBase.mmPrettyPrintMetrics(tm.mmGetDefaultMetrics())

        if verbose > 1:
          print " TM traces after training"
          print MonitorMixinBase.mmPrettyPrintTraces(tm.mmGetDefaultTraces(verbosity=True),
                                                     breakOnResets=tm.mmGetTraceResets())

      tm.mmClearHistory()
def train(tm, sequences, feedback_seq=None, trials=trials,
          feedback_buffer=10, clearhistory=True, verbose=0):

  for i in range(trials):
    for j, sensorPattern in enumerate(sequences):
      if sensorPattern is None:
        tm.reset()
      else:
        if i<feedback_buffer:
          feedback = set([random.randint(0, 2047) for _ in range(feedback_n)])
        elif feedback_seq is not None:
          feedback = feedback_seq[j]
        else:
          feedback = set()
        tm.compute(sensorPattern, activeApicalCells=feedback,
                   learn=True, sequenceLabel=None)

    if clearhistory:
      if i == trials-1:
        if verbose > 0:
          print " TM metrics after training"
          print MonitorMixinBase.mmPrettyPrintMetrics(tm.mmGetDefaultMetrics())

        if verbose > 1:
          print " TM traces after training"
          print MonitorMixinBase.mmPrettyPrintTraces(tm.mmGetDefaultTraces(verbosity=True),
                                                     breakOnResets=tm.mmGetTraceResets())

      tm.mmClearHistory()
def run(tm, mutate_times, sequences, alphabet, feedback_seq=None, mutation=0, verbose=0):

  allLabels = []
  tm.reset()
  for j, sensorPattern in enumerate(sequences):
    if sensorPattern is None:
      tm.reset()
    else:
      if j in mutate_times:
        if mutation:
          continue
        else:
          sensorPattern = set([random.randint(0, 2047) for _ in sensorPattern])

      if feedback_seq is not None:
        feedback = feedback_seq[j]
      else:
        feedback = set()

      tm.compute(sensorPattern, activeApicalCells=feedback,
                 learn=True, sequenceLabel=None)

      allLabels.append(labelPattern(sensorPattern, alphabet))

  ys = [len(x) for x in tm.mmGetTraceUnpredictedActiveColumns().data]

  if verbose > 0:
    print " TM metrics on test sequence"
    print MonitorMixinBase.mmPrettyPrintMetrics(tm.mmGetDefaultMetrics())

  if verbose > 1:
    print MonitorMixinBase.mmPrettyPrintTraces(tm.mmGetDefaultTraces(verbosity=True),
                                               breakOnResets=tm.mmGetTraceResets())

  return ys, allLabels
  def runNetworkOnSequences(self, inputSequences, inputCategories, tmLearn=True,
                            upLearn=None, classifierLearn=False, verbosity=0,
                            progressInterval=None):
    """
    Runs Union Pooler network on specified sequence.

    @param inputSequences           One or more sequences of input patterns.
                                    Each should be terminated with None.

    @param inputCategories          A sequence of category representations
                                    for each element in inputSequences
                                    Each should be terminated with None.

    @param tmLearn:   (bool)        Temporal Memory learning mode
    @param upLearn:   (None, bool)  Union Pooler learning mode. If None,
                                    Union Pooler will not be run.
    @param classifierLearn: (bool)  Classifier learning mode

    @param progressInterval: (int)  Interval of console progress updates
                                    in terms of timesteps.
    """

    currentTime = time.time()
    for i in xrange(len(inputSequences)):
      sensorPattern = inputSequences[i]
      inputCategory = inputCategories[i]

      self.runNetworkOnPattern(sensorPattern,
                               tmLearn=tmLearn,
                               upLearn=upLearn,
                               sequenceLabel=inputCategory)

      if classifierLearn and sensorPattern is not None:
        unionSDR = self.up.getUnionSDR()
        upCellCount = self.up.getColumnDimensions()
        self.classifier.learn(unionSDR, inputCategory, isSparse=upCellCount)
        if verbosity > 1:
          pprint.pprint("{0} is category {1}".format(unionSDR, inputCategory))

      if progressInterval is not None and i > 0 and i % progressInterval == 0:
        elapsed = (time.time() - currentTime) / 60.0
        print ("Ran {0} / {1} elements of sequence in "
               "{2:0.2f} minutes.".format(i, len(inputSequences), elapsed))
        currentTime = time.time()
        print MonitorMixinBase.mmPrettyPrintMetrics(
          self.tm.mmGetDefaultMetrics())

    if verbosity >= 2:
      traces = self.tm.mmGetDefaultTraces(verbosity=verbosity)
      print MonitorMixinBase.mmPrettyPrintTraces(traces,
                                                 breakOnResets=
                                                 self.tm.mmGetTraceResets())

      if upLearn is not None:
        traces = self.up.mmGetDefaultTraces(verbosity=verbosity)
        print MonitorMixinBase.mmPrettyPrintTraces(traces,
                                                   breakOnResets=
                                                   self.up.mmGetTraceResets())
      print
  def runNetworkOnSequences(self, inputSequences, inputCategories, tmLearn=True,
                            upLearn=None, classifierLearn=False, verbosity=0,
                            progressInterval=None):
    """
    Runs Union Temporal Pooler network on specified sequence.

    @param inputSequences           One or more sequences of input patterns.
                                    Each should be terminated with None.

    @param inputCategories          A sequence of category representations
                                    for each element in inputSequences
                                    Each should be terminated with None.

    @param tmLearn:   (bool)        Temporal Memory learning mode
    @param upLearn:   (None, bool)  Union Temporal Pooler learning mode. If None,
                                    Union Temporal Pooler will not be run.
    @param classifierLearn: (bool)  Classifier learning mode

    @param progressInterval: (int)  Interval of console progress updates
                                    in terms of timesteps.
    """

    currentTime = time.time()
    for i in xrange(len(inputSequences)):
      sensorPattern = inputSequences[i]
      inputCategory = inputCategories[i]

      self.runNetworkOnPattern(sensorPattern,
                               tmLearn=tmLearn,
                               upLearn=upLearn,
                               sequenceLabel=inputCategory)

      if classifierLearn and sensorPattern is not None:
        unionSDR = self.up.getUnionSDR()
        upCellCount = self.up.getColumnDimensions()
        self.classifier.learn(unionSDR, inputCategory, isSparse=upCellCount)
        if verbosity > 1:
          pprint.pprint("{0} is category {1}".format(unionSDR, inputCategory))

      if progressInterval is not None and i > 0 and i % progressInterval == 0:
        elapsed = (time.time() - currentTime) / 60.0
        print ("Ran {0} / {1} elements of sequence in "
               "{2:0.2f} minutes.".format(i, len(inputSequences), elapsed))
        currentTime = time.time()
        print MonitorMixinBase.mmPrettyPrintMetrics(
          self.tm.mmGetDefaultMetrics())

    if verbosity >= 2:
      traces = self.tm.mmGetDefaultTraces(verbosity=verbosity)
      print MonitorMixinBase.mmPrettyPrintTraces(traces,
                                                 breakOnResets=
                                                 self.tm.mmGetTraceResets())

      if upLearn is not None:
        traces = self.up.mmGetDefaultTraces(verbosity=verbosity)
        print MonitorMixinBase.mmPrettyPrintTraces(traces,
                                                   breakOnResets=
                                                   self.up.mmGetTraceResets())
      print
    def feedLayers(self,
                   sequences,
                   tmLearn=True,
                   tpLearn=None,
                   verbosity=0,
                   showProgressInterval=None):
        """
    Feed the given sequences to the HTM algorithms.

    @param tmLearn:   (bool)      Either False, or True
    @param tpLearn:   (None,bool) Either None, False, or True. If None,
                                  temporal pooler will be skipped.

    @param showProgressInterval: (int) Prints progress every N iterations,
                                       where N is the value of this param
    """
        (sensorSequence, motorSequence, sensorimotorSequence,
         sequenceLabels) = sequences

        currentTime = time.time()

        for i in xrange(len(sensorSequence)):
            sensorPattern = sensorSequence[i]
            motorPattern = motorSequence[i]
            sensorimotorPattern = sensorimotorSequence[i]
            sequenceLabel = sequenceLabels[i]

            self.feedTransition(sensorPattern,
                                motorPattern,
                                sensorimotorPattern,
                                tmLearn=tmLearn,
                                tpLearn=tpLearn,
                                sequenceLabel=sequenceLabel)

            if (showProgressInterval is not None and i > 0
                    and i % showProgressInterval == 0):
                print(
                    "Fed {0} / {1} elements of the sequence "
                    "in {2:0.2f} seconds.".format(i, len(sensorSequence),
                                                  time.time() - currentTime))
                currentTime = time.time()

        if verbosity >= 2:
            # Print default TM traces
            traces = self.tm.mmGetDefaultTraces(verbosity=verbosity)
            print MonitorMixinBase.mmPrettyPrintTraces(
                traces, breakOnResets=self.tm.mmGetTraceResets())

            if tpLearn is not None:
                # Print default TP traces
                traces = self.tp.mmGetDefaultTraces(verbosity=verbosity)
                print MonitorMixinBase.mmPrettyPrintTraces(
                    traces, breakOnResets=self.tp.mmGetTraceResets())
            print
Beispiel #7
0
  def _printInfo(self):
    if VERBOSITY >= 2:
      print MonitorMixinBase.mmPrettyPrintTraces(
        self.tp.mmGetDefaultTraces(verbosity=3) +
        self.tm.mmGetDefaultTraces(verbosity=3),
        breakOnResets=self.tm.mmGetTraceResets())
      print

    if VERBOSITY >= 1:
      print MonitorMixinBase.mmPrettyPrintMetrics(
        self.tp.mmGetDefaultMetrics() + self.tm.mmGetDefaultMetrics())
      print
  def _printInfo(self):
    if VERBOSITY >= 2:
      print MonitorMixinBase.mmPrettyPrintTraces(
        self.tp.mmGetDefaultTraces(verbosity=3) +
        self.tm.mmGetDefaultTraces(verbosity=3),
        breakOnResets=self.tm.mmGetTraceResets())
      print

    if VERBOSITY >= 1:
      print MonitorMixinBase.mmPrettyPrintMetrics(
        self.tp.mmGetDefaultMetrics() + self.tm.mmGetDefaultMetrics())
      print
    def feed(self,
             sequences,
             tmLearn=True,
             tpLearn=None,
             verbosity=2,
             showProgressInterval=None):
        # Note: not setup for TP...
        # https://github.com/numenta/nupic.research/blob/master/sensorimotor/sensorimotor/sensorimotor_experiment_runner.py#L131
        """
    Feed the given sequences to the HTM algorithms.
    @param tmLearn:   (bool)      Either False, or True
    @param tpLearn:   (None,bool) Either None, False, or True. If None,
                                  temporal pooler will be skipped.
    @param showProgressInterval: (int) Prints progress every N iterations,
                                       where N is the value of this param
    """
        #    (sensorSequence,
        #     motorSequence,
        #     sensorimotorSequence,
        #     sequenceLabels) = sequences
        (sensorSequences, motorSequences) = sequences

        currentTime = time.time()

        for i in xrange(len(sensorSequences)):
            for j in xrange(len(sensorSequences[i])):
                sensorPattern = set(sensorSequences[i][j])
                motorPattern = set(motorSequences[i][j])
                #        sensorimotorPattern = sensorimotorSequence[i][j]
                #        import pdb; pdb.set_trace()
                self.tm.compute(
                    sensorPattern,  # here the sequences are e.g. set([224, 480, 195, 277, 235,...])
                    activeExternalCells=motorPattern,
                    formInternalConnections=True,
                    learn=tmLearn)

        if (showProgressInterval is not None and i > 0
                and i % showProgressInterval == 0):
            print(
                "Fed {0} / {1} elements of the sequence "
                "in {2:0.2f} seconds.".format(i, len(sensorSequence),
                                              time.time() - currentTime))
            currentTime = time.time()

        if verbosity >= 2:
            traces = []
            traces += self.tm.mmGetDefaultTraces(verbosity=verbosity)
            if tpLearn is not None:
                traces += self.tp.mmGetDefaultTraces(verbosity=verbosity)
            print MonitorMixinBase.mmPrettyPrintTraces(
                traces, breakOnResets=self.tm.mmGetTraceResets())
            print
  def feedLayers(self, sequences, tmLearn=True, tpLearn=None, verbosity=0,
                 showProgressInterval=None):
    """
    Feed the given sequences to the HTM algorithms.

    @param tmLearn:   (bool)      Either False, or True
    @param tpLearn:   (None,bool) Either None, False, or True. If None,
                                  temporal pooler will be skipped.

    @param showProgressInterval: (int) Prints progress every N iterations,
                                       where N is the value of this param
    """
    (sensorSequence,
     motorSequence,
     sensorimotorSequence,
     sequenceLabels) = sequences

    currentTime = time.time()

    for i in xrange(len(sensorSequence)):
      sensorPattern = sensorSequence[i]
      motorPattern = motorSequence[i]
      sensorimotorPattern = sensorimotorSequence[i]
      sequenceLabel = sequenceLabels[i]

      self.feedTransition(sensorPattern, motorPattern, sensorimotorPattern,
                          tmLearn=tmLearn, tpLearn=tpLearn,
                          sequenceLabel=sequenceLabel)

      if (showProgressInterval is not None and
          i > 0 and
          i % showProgressInterval == 0):
        print ("Fed {0} / {1} elements of the sequence "
               "in {2:0.2f} seconds.".format(
                 i, len(sensorSequence), time.time() - currentTime))
        currentTime = time.time()

    if verbosity >= 2:
      # Print default TM traces
      traces = self.tm.mmGetDefaultTraces(verbosity=verbosity)
      print MonitorMixinBase.mmPrettyPrintTraces(traces,
                                                 breakOnResets=
                                                 self.tm.mmGetTraceResets())

      if tpLearn is not None:
        # Print default TP traces
        traces = self.tp.mmGetDefaultTraces(verbosity=verbosity)
        print MonitorMixinBase.mmPrettyPrintTraces(traces,
                                                   breakOnResets=
                                                   self.tp.mmGetTraceResets())
      print
  def runNetworkOnSequence(self, sensorSequences, sequencesLabels, tmLearn=True,
                           upLearn=None, verbosity=0, progressInterval=None):
    """
    Runs Union Pooler network on specified sequence.

    @param sensorSequences        A sequence of sensor sequences. Each
                                  sequence is terminated by None.

    @param sequenceLabels         A sequence of string representations of the
                                  current sequence. Each sequence is terminated
                                  by None.

    @param tmLearn:   (bool)      Either False, or True
    @param upLearn:   (None,bool) Either None, False, or True. If None,
                                  union pooler will be skipped.

    @param progressInterval: (int) Prints progress every N iterations,
                                   where N is the value of this param
    """

    currentTime = time.time()

    for i in xrange(len(sensorSequences)):
      sensorPattern = sensorSequences[i]
      sequenceLabel = sequencesLabels[i]

      self.runNetworkOnPattern(sensorPattern,
                               tmLearn=tmLearn,
                               upLearn=upLearn,
                               sequenceLabel=sequenceLabel)

      if progressInterval is not None and i > 0 and i % progressInterval == 0:
        elapsed = (time.time() - currentTime) / 60.0
        print ("Ran {0} / {1} elements of sequence in "
               "{2:0.2f} minutes.".format(i, len(sensorSequences), elapsed))
        currentTime = time.time()
        print MonitorMixinBase.mmPrettyPrintMetrics(
          self.tm.mmGetDefaultMetrics())

    if verbosity >= 2:
      traces = self.tm.mmGetDefaultTraces(verbosity=verbosity)
      print MonitorMixinBase.mmPrettyPrintTraces(traces,
                                                 breakOnResets=
                                                 self.tm.mmGetTraceResets())

      if upLearn is not None:
        traces = self.up.mmGetDefaultTraces(verbosity=verbosity)
        print MonitorMixinBase.mmPrettyPrintTraces(traces,
                                                   breakOnResets=
                                                   self.up.mmGetTraceResets())
      print
Beispiel #12
0
def runUP(tm,
          mutate_times,
          sequences,
          alphabet,
          up=None,
          mutation=0,
          verbose=0):

    allLabels = []

    for j, sensorPattern in enumerate(sequences):
        if sensorPattern is None:
            tm.reset()
        else:
            if j in mutate_times:
                if mutation:
                    continue
                else:
                    sensorPattern = set(
                        [random.randint(0, 2047) for _ in sensorPattern])

            if up is None:
                feedback = set()
            else:
                feedback = set(np.nonzero(up.getUnionSDR())[0])

            tm.compute(sensorPattern,
                       activeApicalCells=feedback,
                       learn=True,
                       sequenceLabel=None)

            if up is not None:
                activeCells, predActiveCells, burstingCols, = getUnionTemporalPoolerInput(
                    tm)
                up.compute(activeCells, predActiveCells, learn=False)

            allLabels.append(labelPattern(sensorPattern, alphabet))

    ys = [len(x) for x in tm.mmGetTraceUnpredictedActiveColumns().data]

    if verbose > 0:
        print " TM metrics on test sequence"
        print MonitorMixinBase.mmPrettyPrintMetrics(tm.mmGetDefaultMetrics())

    if verbose > 1:
        print MonitorMixinBase.mmPrettyPrintTraces(
            tm.mmGetDefaultTraces(verbosity=True),
            breakOnResets=tm.mmGetTraceResets())

    return ys, allLabels
Beispiel #13
0
def run(tm,
        mutate_times,
        sequences,
        alphabet,
        feedback_seq=None,
        mutation=0,
        verbose=0):

    allLabels = []
    tm.reset()
    for j, sensorPattern in enumerate(sequences):
        if sensorPattern is None:
            tm.reset()
        else:
            if j in mutate_times:
                if mutation:
                    continue
                else:
                    sensorPattern = set(
                        [random.randint(0, 2047) for _ in sensorPattern])

            if feedback_seq is not None:
                feedback = feedback_seq[j]
            else:
                feedback = set()

            tm.compute(sensorPattern,
                       activeApicalCells=feedback,
                       learn=True,
                       sequenceLabel=None)

            allLabels.append(labelPattern(sensorPattern, alphabet))

    ys = [len(x) for x in tm.mmGetTraceUnpredictedActiveColumns().data]

    if verbose > 0:
        print " TM metrics on test sequence"
        print MonitorMixinBase.mmPrettyPrintMetrics(tm.mmGetDefaultMetrics())

    if verbose > 1:
        print MonitorMixinBase.mmPrettyPrintTraces(
            tm.mmGetDefaultTraces(verbosity=True),
            breakOnResets=tm.mmGetTraceResets())

    return ys, allLabels
Beispiel #14
0
def trainUP(tm,
            sequences,
            up=None,
            trials=trials,
            clearhistory=True,
            verbose=0):

    for i in range(trials):
        for j, sensorPattern in enumerate(sequences):
            if sensorPattern is None:
                tm.reset()
                if up is not None:
                    up.reset()
            else:
                if up is None:
                    feedback = set()
                else:
                    feedback = set(np.nonzero(up.getUnionSDR())[0])
                tm.compute(sensorPattern,
                           activeApicalCells=feedback,
                           learn=True,
                           sequenceLabel=None)
                if up is not None:
                    activeCells, predActiveCells, burstingCols, = getUnionTemporalPoolerInput(
                        tm)
                    up.compute(activeCells, predActiveCells, learn=False)

        if clearhistory:
            if i == trials - 1:
                if verbose > 0:
                    print " TM metrics after training"
                    print MonitorMixinBase.mmPrettyPrintMetrics(
                        tm.mmGetDefaultMetrics())

                if verbose > 1:
                    print " TM traces after training"
                    print MonitorMixinBase.mmPrettyPrintTraces(
                        tm.mmGetDefaultTraces(verbosity=True),
                        breakOnResets=tm.mmGetTraceResets())

            tm.mmClearHistory()
Beispiel #15
0
def train(tm,
          sequences,
          feedback_seq=None,
          trials=trials,
          feedback_buffer=10,
          clearhistory=True,
          verbose=0):

    for i in range(trials):
        for j, sensorPattern in enumerate(sequences):
            if sensorPattern is None:
                tm.reset()
            else:
                if i < feedback_buffer:
                    feedback = set(
                        [random.randint(0, 2047) for _ in range(feedback_n)])
                elif feedback_seq is not None:
                    feedback = feedback_seq[j]
                else:
                    feedback = set()
                tm.compute(sensorPattern,
                           activeApicalCells=feedback,
                           learn=True,
                           sequenceLabel=None)

        if clearhistory:
            if i == trials - 1:
                if verbose > 0:
                    print " TM metrics after training"
                    print MonitorMixinBase.mmPrettyPrintMetrics(
                        tm.mmGetDefaultMetrics())

                if verbose > 1:
                    print " TM traces after training"
                    print MonitorMixinBase.mmPrettyPrintTraces(
                        tm.mmGetDefaultTraces(verbosity=True),
                        breakOnResets=tm.mmGetTraceResets())

            tm.mmClearHistory()
def runUP(tm, mutate_times, sequences, alphabet, up=None, mutation=0, verbose=0):

  allLabels = []

  for j, sensorPattern in enumerate(sequences):
    if sensorPattern is None:
      tm.reset()
    else:
      if j in mutate_times:
        if mutation:
          continue
        else:
          sensorPattern = set([random.randint(0, 2047) for _ in sensorPattern])

      if up is None:
        feedback = set()
      else:
        feedback = set(np.nonzero(up.getUnionSDR())[0])

      tm.compute(sensorPattern, activeApicalCells=feedback,
                 learn=True, sequenceLabel=None)

      if up is not None:
        activeCells, predActiveCells, burstingCols, = getUnionTemporalPoolerInput(tm)
        up.compute(activeCells, predActiveCells, learn=False)

      allLabels.append(labelPattern(sensorPattern, alphabet))

  ys = [len(x) for x in tm.mmGetTraceUnpredictedActiveColumns().data]

  if verbose > 0:
    print " TM metrics on test sequence"
    print MonitorMixinBase.mmPrettyPrintMetrics(tm.mmGetDefaultMetrics())

  if verbose > 1:
    print MonitorMixinBase.mmPrettyPrintTraces(tm.mmGetDefaultTraces(verbosity=True),
                                               breakOnResets=tm.mmGetTraceResets())

  return ys, allLabels
  def feedLayers(self, sequences, tmLearn, tpLearn=None, verbosity=0,
                 showProgressInterval=None):
    """
    Feed the given sequences to the HTM algorithms.

    @param tmLearn:   (bool)      Either False, or True
    @param tpLearn:   (None,bool) Either None, False, or True. If None,
                                  temporal pooler will be skipped.

    @param showProgressInterval: (int) Prints progress every N iterations,
                                       where N is the value of this param
    """
    (sensorSequence,
     motorSequence,
     sensorimotorSequence,
     sequenceLabels) = sequences

    self.tm.mmClearHistory()
    self.tp.mmClearHistory()

    currentTime = time.time()

    for i in xrange(len(sensorSequence)):
      sensorPattern = sensorSequence[i]
      sensorimotorPattern = sensorimotorSequence[i]
      sequenceLabel = sequenceLabels[i]

      if sensorPattern is None:
        self.tm.reset()
        self.tp.reset()

      else:
        # Feed the TM
        self.tm.compute(sensorPattern,
                  activeExternalCells=sensorimotorPattern,
                  formInternalConnections=False,
                  learn=tmLearn,
                  sequenceLabel=sequenceLabel)

        # If requested, feed the TP
        if tpLearn is not None:
          tpInputVector, burstingColumns, correctlyPredictedCells = (
              self.formatInputForTP())
          activeArray = numpy.zeros(self.tp.getNumColumns())

          self.tp.compute(tpInputVector,
                          tpLearn,
                          activeArray,
                          burstingColumns,
                          correctlyPredictedCells,
                          sequenceLabel=sequenceLabel)

        if (showProgressInterval is not None and
            i > 0 and
            i % showProgressInterval == 0):
          print ("Fed {0} / {1} elements of the sequence "
                 "in {2:0.2f} seconds.".format(
                   i, len(sensorSequence), time.time() - currentTime))
          currentTime = time.time()

    if verbosity >= 2:
      traces = []
      traces += self.tm.mmGetDefaultTraces(verbosity=verbosity)
      if tpLearn is not None:
        traces += self.tp.mmGetDefaultTraces(verbosity=verbosity)
      print MonitorMixinBase.mmPrettyPrintTraces(
        traces, breakOnResets=self.tm.mmGetTraceResets())
      print
Beispiel #18
0
def main():
  print "Initializing robot..."
  robot = Robot()
  print "Initializing model..."
  model = Model()
  print "Initializing plot..."
  plot = Plot(model)
  print "Initializing classifier..."
  classifier = Classifier()

  with open(OUTFILE_PATH, "wb") as csvFile:
    csvWriter = csv.writer(csvFile)

    for i in count(1):
      behaviorType = None
      while behaviorType is None:
        behaviorType = raw_input("Enter behavior type: "
                                 "Exhaustive (e), Random (r), "
                                 "Sweep (s), User (u): ")
        behaviorType = behaviorType if behaviorType in ["e", "r", "s", "u"] else None

      targets = None
      while targets is None:
        try:
          targets = input("Enter targets (Python code returning a list): ")
          targets = targets if type(targets) is list and len(targets) else None
        except: pass


      def callback(sensorValue, current, target):
        motorValue = target - current
        row = [sensorValue, motorValue, i]
        csvWriter.writerow(row)
        csvFile.flush()

        model.feed(sensorValue, motorValue, sequenceLabel=i)
        tpActiveCells = model.experimentRunner.tp.mmGetTraceActiveCells().data[-1]
        classification = classifier.feed(tpActiveCells)

        print "Current: {0}\tSensor: {1}\tNext: {2}\tClassification: {3}".format(
          current, sensorValue, target, classification)

        if classification is not None:
          robot.playTune(classification)

        plot.update(model)


      if behaviorType == "s":
        sweep(targets, robot, callback)
      elif behaviorType == "e":
        exhaustive(targets, robot, callback)
      elif behaviorType == "r":
        randomlyExplore(targets, robot, callback)

      print MonitorMixinBase.mmPrettyPrintTraces(
        model.experimentRunner.tm.mmGetDefaultTraces(verbosity=2) +
        model.experimentRunner.tp.mmGetDefaultTraces(verbosity=2),
        breakOnResets=model.experimentRunner.tm.mmGetTraceResets())

      print MonitorMixinBase.mmPrettyPrintMetrics(
        model.experimentRunner.tm.mmGetDefaultMetrics() +
        model.experimentRunner.tp.mmGetDefaultMetrics())

      robot.reset()

      doReset = None
      while doReset is None:
        doReset = raw_input("Reset (y/n)? ")
        doReset = doReset if doReset in ["y", "n"] else None

      if doReset == "y":
        model.experimentRunner.tm.reset()
        model.experimentRunner.tp.reset()

      model.experimentRunner.tm.mmClearHistory()
      model.experimentRunner.tp.mmClearHistory()
    def feedLayers(self,
                   sequences,
                   tmLearn,
                   tpLearn=None,
                   verbosity=0,
                   showProgressInterval=None):
        """
    Feed the given sequences to the HTM algorithms.

    @param tmLearn:   (bool)      Either False, or True
    @param tpLearn:   (None,bool) Either None, False, or True. If None,
                                  temporal pooler will be skipped.

    @param showProgressInterval: (int) Prints progress every N iterations,
                                       where N is the value of this param
    """
        (sensorSequence, motorSequence, sensorimotorSequence,
         sequenceLabels) = sequences

        self.tm.mmClearHistory()
        self.tp.mmClearHistory()

        currentTime = time.time()

        for i in xrange(len(sensorSequence)):
            sensorPattern = sensorSequence[i]
            sensorimotorPattern = sensorimotorSequence[i]
            sequenceLabel = sequenceLabels[i]

            if sensorPattern is None:
                self.tm.reset()
                self.tp.reset()

            else:
                # Feed the TM
                self.tm.compute(sensorPattern,
                                activeExternalCells=sensorimotorPattern,
                                formInternalConnections=False,
                                learn=tmLearn,
                                sequenceLabel=sequenceLabel)

                # If requested, feed the TP
                if tpLearn is not None:
                    tpInputVector, burstingColumns, correctlyPredictedCells = (
                        self.formatInputForTP())
                    activeArray = numpy.zeros(self.tp.getNumColumns())

                    self.tp.compute(tpInputVector,
                                    tpLearn,
                                    activeArray,
                                    burstingColumns,
                                    correctlyPredictedCells,
                                    sequenceLabel=sequenceLabel)

                if (showProgressInterval is not None and i > 0
                        and i % showProgressInterval == 0):
                    print(
                        "Fed {0} / {1} elements of the sequence "
                        "in {2:0.2f} seconds.".format(
                            i, len(sensorSequence),
                            time.time() - currentTime))
                    currentTime = time.time()

        if verbosity >= 2:
            traces = []
            traces += self.tm.mmGetDefaultTraces(verbosity=verbosity)
            if tpLearn is not None:
                traces += self.tp.mmGetDefaultTraces(verbosity=verbosity)
            print MonitorMixinBase.mmPrettyPrintTraces(
                traces, breakOnResets=self.tm.mmGetTraceResets())
            print