Пример #1
0
  def testWList(self):
    w = [4, 7, 11]
    patternMachine = PatternMachine(100, w, num=50)
    widths = dict((el, 0) for el in w)

    for i in range(50):
      pattern = patternMachine.get(i)
      width = len(pattern)
      self.assertTrue(width in w)
      widths[len(pattern)] += 1

    for i in w:
      self.assertTrue(widths[i] > 0)
Пример #2
0
  def testWList(self):
    w = [4, 7, 11]
    patternMachine = PatternMachine(100, w, num=50)
    widths = dict((el, 0) for el in w)

    for i in range(50):
      pattern = patternMachine.get(i)
      width = len(pattern)
      self.assertTrue(width in w)
      widths[len(pattern)] += 1

    for i in w:
      self.assertTrue(widths[i] > 0)
Пример #3
0
  def testB1(self):
    """Basic sequence learner.  M=1, N=100, P=1."""
    self.initTM()
    self.finishSetUp(PatternMachine(
      self.tm.connections.numberOfColumns(), 23))

    numbers = range(100)
    shuffle(numbers)
    sequence = self.sequenceMachine.generateFromNumbers(numbers)
    sequence.append(None)

    self.feedTM(sequence)

    (_,
     predictedInactiveCellsList,
     predictedActiveColumnsList,
     _,
     unpredictedActiveColumnsList) = self.feedTM(sequence,
                                                 learn=False)

    numUnpredictedActiveColumns = sum(
      [len(x) for x in unpredictedActiveColumnsList])
    self.assertEqual(numUnpredictedActiveColumns, 0)

    for i in range(1, len(predictedActiveColumnsList) - 1):
      self.assertEqual(len(predictedActiveColumnsList[i]), 23)

    for i in range(1, len(predictedInactiveCellsList) - 1):
      self.assertTrue(len(predictedInactiveCellsList[i]) < 5)
Пример #4
0
  def testAddSpatialNoise(self):
    patternMachine = PatternMachine(10000, 1000, num=100)
    sequenceMachine = SequenceMachine(patternMachine)
    numbers = range(0, 100)
    numbers.append(None)

    sequence = sequenceMachine.generateFromNumbers(numbers)
    noisy = sequenceMachine.addSpatialNoise(sequence, 0.5)

    overlap = len(noisy[0] & patternMachine.get(0))
    self.assertTrue(400 < overlap < 600)

    sequence = sequenceMachine.generateFromNumbers(numbers)
    noisy = sequenceMachine.addSpatialNoise(sequence, 0.0)

    overlap = len(noisy[0] & patternMachine.get(0))
    self.assertEqual(overlap, 1000)
Пример #5
0
class PatternMachineTest(unittest.TestCase):
    def setUp(self):
        self.patternMachine = PatternMachine(10000, 5, num=50)

    def testGet(self):
        patternA = self.patternMachine.get(48)
        self.assertEqual(len(patternA), 5)

        patternB = self.patternMachine.get(49)
        self.assertEqual(len(patternB), 5)

        self.assertEqual(patternA & patternB, set())

    def testGetOutOfBounds(self):
        args = [50]
        self.assertRaises(IndexError, self.patternMachine.get, *args)

    def testNumbersForBit(self):
        pattern = self.patternMachine.get(49)

        for bit in pattern:
            self.assertEqual(self.patternMachine.numbersForBit(bit), set([49]))

    def testNumbersForBitOutOfBounds(self):
        args = [10000]
        self.assertRaises(IndexError, self.patternMachine.numbersForBit, *args)

    def testNumberMapForBits(self):
        pattern = self.patternMachine.get(49)
        numberMap = self.patternMachine.numberMapForBits(pattern)

        self.assertEqual(numberMap.keys(), [49])
        self.assertEqual(numberMap[49], pattern)
Пример #6
0
class PatternMachineTest(unittest.TestCase):


  def setUp(self):
    self.patternMachine = PatternMachine(10000, 5, num=50)


  def testGet(self):
    patternA = self.patternMachine.get(48)
    self.assertEqual(len(patternA), 5)

    patternB = self.patternMachine.get(49)
    self.assertEqual(len(patternB), 5)

    self.assertEqual(patternA & patternB, set())


  def testGetOutOfBounds(self):
    args = [50]
    self.assertRaises(IndexError, self.patternMachine.get, *args)


  def testNumbersForBit(self):
    pattern = self.patternMachine.get(49)

    for bit in pattern:
      self.assertEqual(self.patternMachine.numbersForBit(bit), set([49]))


  def testNumbersForBitOutOfBounds(self):
    args = [10000]
    self.assertRaises(IndexError, self.patternMachine.numbersForBit, *args)


  def testNumberMapForBits(self):
    pattern = self.patternMachine.get(49)
    numberMap = self.patternMachine.numberMapForBits(pattern)

    self.assertEqual(numberMap.keys(), [49])
    self.assertEqual(numberMap[49], pattern)


  def testWList(self):
    w = [4, 7, 11]
    patternMachine = PatternMachine(100, w, num=50)
    widths = dict((el, 0) for el in w)

    for i in range(50):
      pattern = patternMachine.get(i)
      width = len(pattern)
      self.assertTrue(width in w)
      widths[len(pattern)] += 1

    for i in w:
      self.assertTrue(widths[i] > 0)
Пример #7
0
  def testAddNoise(self):
    patternMachine = PatternMachine(10000, 1000, num=1)
    pattern = patternMachine.get(0)

    noisy = patternMachine.addNoise(pattern, 0.0)
    self.assertEqual(len(pattern & noisy), 1000)

    noisy = patternMachine.addNoise(pattern, 0.5)
    self.assertTrue(400 < len(pattern & noisy) < 600)

    noisy = patternMachine.addNoise(pattern, 1.0)
    self.assertTrue(50 < len(pattern & noisy) < 150)
Пример #8
0
  def setUp(self):
    self.tm = TemporalMemory(columnDimensions=[2048],
                             cellsPerColumn=32,
                             initialPermanence=0.5,
                             connectedPermanence=0.8,
                             minThreshold=10,
                             maxNewSynapseCount=12,
                             permanenceIncrement=0.1,
                             permanenceDecrement=0.05,
                             activationThreshold=15)

    self.tp = TP(numberOfCols=2048,
                 cellsPerColumn=32,
                 initialPerm=0.5,
                 connectedPerm=0.8,
                 minThreshold=10,
                 newSynapseCount=12,
                 permanenceInc=0.1,
                 permanenceDec=0.05,
                 activationThreshold=15,
                 globalDecay=0, burnIn=1,
                 checkSynapseConsistency=False,
                 pamLength=1)

    self.tp10x2 = TP10X2(numberOfCols=2048,
                         cellsPerColumn=32,
                         initialPerm=0.5,
                         connectedPerm=0.8,
                         minThreshold=10,
                         newSynapseCount=12,
                         permanenceInc=0.1,
                         permanenceDec=0.05,
                         activationThreshold=15,
                         globalDecay=0, burnIn=1,
                         checkSynapseConsistency=False,
                         pamLength=1)

    self.patternMachine = PatternMachine(2048, 40, num=100)
    self.sequenceMachine = SequenceMachine(self.patternMachine)
Пример #9
0
class PatternMachineTest(unittest.TestCase):


  def setUp(self):
    self.patternMachine = PatternMachine(10000, 5, num=50)


  def testGet(self):
    patternA = self.patternMachine.get(48)
    self.assertEqual(len(patternA), 5)

    patternB = self.patternMachine.get(49)
    self.assertEqual(len(patternB), 5)

    self.assertEqual(patternA & patternB, set())


  def testGetOutOfBounds(self):
    args = [50]
    self.assertRaises(IndexError, self.patternMachine.get, *args)


  def testNumbersForBit(self):
    pattern = self.patternMachine.get(49)

    for bit in pattern:
      self.assertEqual(self.patternMachine.numbersForBit(bit), set([49]))


  def testNumbersForBitOutOfBounds(self):
    args = [10000]
    self.assertRaises(IndexError, self.patternMachine.numbersForBit, *args)


  def testNumberMapForBits(self):
    pattern = self.patternMachine.get(49)
    numberMap = self.patternMachine.numberMapForBits(pattern)

    self.assertEqual(numberMap.keys(), [49])
    self.assertEqual(numberMap[49], pattern)
Пример #10
0
class ExtensiveTemporalMemoryTest(AbstractTemporalMemoryTest):
    """
  ==============================================================================
                  Basic First Order Sequences
  ==============================================================================

  These tests ensure the most basic (first order) sequence learning mechanism is
  working.

  Parameters: Use a "fast learning mode": initPerm should be greater than
  connectedPerm and permanenceDec should be zero. With these settings sequences
  should be learned in one pass:

    minThreshold = newSynapseCount
    initialPermanence = 0.8
    connectedPermanence = 0.7
    permanenceDecrement = 0
    permanenceIncrement = 0.4

  Other Parameters:
    columnDimensions = [100]
    cellsPerColumn = 1
    newSynapseCount = 11
    activationThreshold = 11

  Note: this is not a high order sequence, so one cell per column is fine.

  Input Sequence: We train with M input sequences, each consisting of N random
  patterns. Each pattern consists of a random number of bits on. The number of
  1's in each pattern should be between 21 and 25 columns.

  Each input pattern can optionally have an amount of spatial noise represented
  by X, where X is the probability of switching an on bit with a random bit.

  Training: The TP is trained with P passes of the M sequences. There
  should be a reset between sequences. The total number of iterations during
  training is P*N*M.

  Testing: Run inference through the same set of sequences, with a reset before
  each sequence. For each sequence the system should accurately predict the
  pattern at the next time step up to and including the N-1'st pattern. The number
  of predicted inactive cells at each time step should be reasonably low.

  We can also calculate the number of synapses that should be
  learned. We raise an error if too many or too few were learned.

  B1) Basic sequence learner.  M=1, N=100, P=1.

  B2) Same as above, except P=2. Test that permanences go up and that no
  additional synapses are learned. [TODO]

  B3) N=300, M=1, P=1. (See how high we can go with N)

  B4) N=100, M=3, P=1. (See how high we can go with N*M)

  B5) Like B1 but with cellsPerColumn = 4. First order sequences should still
  work just fine.

  B6) Like B4 but with cellsPerColumn = 4. First order sequences should still
  work just fine.

  B7) Like B1 but with slower learning. Set the following parameters differently:

      initialPermanence = 0.2
      connectedPermanence = 0.7
      permanenceIncrement = 0.2

  Now we train the TP with the B1 sequence 4 times (P=4). This will increment
  the permanences to be above 0.8 and at that point the inference will be correct.
  This test will ensure the basic match function and segment activation rules are
  working correctly.

  B8) Like B7 but with 4 cells per column. Should still work.

  B9) Like B7 but present the sequence less than 4 times: the inference should be
  incorrect.

  B10) Like B2, except that cells per column = 4. Should still add zero additional
  synapses. [TODO]

  B11) Like B5, but with activationThreshold = 8 and with each pattern
  corrupted by a small amount of spatial noise (X = 0.05).


  ===============================================================================
                  High Order Sequences
  ===============================================================================

  These tests ensure that high order sequences can be learned in a multiple cells
  per column instantiation.

  Parameters: Same as Basic First Order Tests above, but with varying cells per
  column.

  Input Sequence: We train with M input sequences, each consisting of N random
  patterns. Each pattern consists of a random number of bits on. The number of
  1's in each pattern should be between 21 and 25 columns. The sequences are
  constructed to contain shared subsequences, such as:

  A B C D E F G H I J
  K L M D E F N O P Q

  The position and length of shared subsequences are parameters in the tests.

  Each input pattern can optionally have an amount of spatial noise represented
  by X, where X is the probability of switching an on bit with a random bit.

  Training: Identical to basic first order tests above.

  Testing: Identical to basic first order tests above unless noted.

  We can also calculate the number of segments and synapses that should be
  learned. We raise an error if too many or too few were learned.

  H1) Learn two sequences with a shared subsequence in the middle. Parameters
  should be the same as B1. Since cellsPerColumn == 1, it should make more
  predictions than necessary.

  H2) Same as H1, but with cellsPerColumn == 4, and train multiple times.
  It should make just the right number of predictions.

  H3) Like H2, except the shared subsequence is in the beginning (e.g.
  "ABCDEF" and "ABCGHIJ"). At the point where the shared subsequence ends, all
  possible next patterns should be predicted. As soon as you see the first unique
  pattern, the predictions should collapse to be a perfect prediction.

  H4) Shared patterns. Similar to H2 except that patterns are shared between
  sequences.  All sequences are different shufflings of the same set of N
  patterns (there is no shared subsequence).

  H5) Combination of H4) and H2). Shared patterns in different sequences, with a
  shared subsequence.

  H6) Stress test: every other pattern is shared. [TODO]

  H7) Start predicting in the middle of a sequence. [TODO]

  H8) Hub capacity. How many patterns can use that hub? [TODO]

  H9) Sensitivity to small amounts of spatial noise during inference (X = 0.05).
  Parameters the same as B11, and sequences like H2.

  H10) Higher order patterns with alternating elements.

  Create the following 4 sequences:

       A B A B A C
       A B A B D E
       A B F G H I
       A J K L M N

  After training we should verify that the expected transitions are in the
  model. Prediction accuracy should be perfect. In addition, during inference,
  after the first element is presented, the columns should not burst any more.
  Need to verify, for the first sequence, that the high order representation
  when presented with the second A and B is different from the representation
  in the first presentation. [TODO]
  """

    VERBOSITY = 1
    DEFAULT_TM_PARAMS = {
        "columnDimensions": [100],
        "cellsPerColumn": 1,
        "initialPermanence": 0.8,
        "connectedPermanence": 0.7,
        "minThreshold": 11,
        "maxNewSynapseCount": 11,
        "permanenceIncrement": 0.4,
        "permanenceDecrement": 0,
        "activationThreshold": 11
    }
    PATTERN_MACHINE = PatternMachine(100, range(21, 26), num=300)

    def testB1(self):
        """Basic sequence learner.  M=1, N=100, P=1."""
        self.init()

        numbers = self.sequenceMachine.generateNumbers(1, 100)
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)
        self.assertAllInactiveWereUnpredicted(stats)

    def testB3(self):
        """N=300, M=1, P=1. (See how high we can go with N)"""
        self.init()

        numbers = self.sequenceMachine.generateNumbers(1, 300)
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)
        self.assertAllInactiveWereUnpredicted(stats)

    def testB4(self):
        """N=100, M=3, P=1. (See how high we can go with N*M)"""
        self.init()

        numbers = self.sequenceMachine.generateNumbers(3, 100)
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)

    def testB5(self):
        """Like B1 but with cellsPerColumn = 4.
    First order sequences should still work just fine."""
        self.init({"cellsPerColumn": 4})

        numbers = self.sequenceMachine.generateNumbers(1, 100)
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)
        self.assertAllInactiveWereUnpredicted(stats)

    def testB6(self):
        """Like B4 but with cellsPerColumn = 4.
    First order sequences should still work just fine."""
        self.init({"cellsPerColumn": 4})

        numbers = self.sequenceMachine.generateNumbers(3, 100)
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)
        self.assertAllInactiveWereUnpredicted(stats)

    def testB7(self):
        """Like B1 but with slower learning.

    Set the following parameters differently:

      initialPermanence = 0.2
      connectedPermanence = 0.7
      permanenceIncrement = 0.2

    Now we train the TP with the B1 sequence 4 times (P=4). This will increment
    the permanences to be above 0.8 and at that point the inference will be correct.
    This test will ensure the basic match function and segment activation rules are
    working correctly.
    """
        self.init({
            "initialPermanence": 0.2,
            "connectedPermanence": 0.7,
            "permanenceIncrement": 0.2
        })

        numbers = self.sequenceMachine.generateNumbers(1, 100)
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        for _ in xrange(4):
            self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)
        self.assertAllInactiveWereUnpredicted(stats)

    def testB8(self):
        """Like B7 but with 4 cells per column.
    Should still work."""
        self.init({
            "initialPermanence": 0.2,
            "connectedPermanence": 0.7,
            "permanenceIncrement": 0.2,
            "cellsPerColumn": 4
        })

        numbers = self.sequenceMachine.generateNumbers(1, 100)
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        for _ in xrange(4):
            self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)
        self.assertAllInactiveWereUnpredicted(stats)

    def testB9(self):
        """Like B7 but present the sequence less than 4 times.
    The inference should be incorrect."""
        self.init({
            "initialPermanence": 0.2,
            "connectedPermanence": 0.7,
            "permanenceIncrement": 0.2
        })

        numbers = self.sequenceMachine.generateNumbers(1, 100)
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        for _ in xrange(3):
            self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWereUnpredicted(stats)

    def testB11(self):
        """Like B5, but with activationThreshold = 8 and with each pattern
    corrupted by a small amount of spatial noise (X = 0.05)."""
        self.init({"cellsPerColumn": 4, "activationThreshold": 8})

        numbers = self.sequenceMachine.generateNumbers(1, 100)
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        self.feedTM(sequence)

        sequence = self.sequenceMachine.addSpatialNoise(sequence, 0.05)
        stats = self._testTM(sequence)

        averageUnpredictedActiveColumns = stats[4][3]
        self.assertTrue(averageUnpredictedActiveColumns < 1)

    def testH1(self):
        """Learn two sequences with a short shared pattern.
    Parameters should be the same as B1.
    Since cellsPerColumn == 1, it should make more predictions than necessary.
    """
        self.init()

        numbers = self.sequenceMachine.generateNumbers(2, 20, (10, 15))
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)

        averagePredictedInactiveColumns = stats[1][3]
        self.assertTrue(averagePredictedInactiveColumns > 0)

        # At the end of both shared sequences, there should be
        # predicted but inactive columns
        self.assertTrue(len(self.tm.predictedInactiveColumnsList[15]) > 0)
        self.assertTrue(len(self.tm.predictedInactiveColumnsList[36]) > 0)

    def testH2(self):
        """Same as H1, but with cellsPerColumn == 4, and train multiple times.
    It should make just the right number of predictions."""
        self.init({"cellsPerColumn": 4})

        numbers = self.sequenceMachine.generateNumbers(2, 20, (10, 15))
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        for _ in xrange(10):
            self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)

        # Without some kind of decay, expect predicted inactive columns at the
        # end of the first shared sequence
        sumPredictedInactiveColumns = stats[1][2]
        self.assertTrue(sumPredictedInactiveColumns < 26)

        # At the end of the second shared sequence, there should be no
        # predicted but inactive columns
        self.assertEqual(len(self.tm.predictedInactiveColumnsList[36]), 0)

    def testH3(self):
        """Like H2, except the shared subsequence is in the beginning.
    (e.g. "ABCDEF" and "ABCGHIJ") At the point where the shared subsequence
    ends, all possible next patterns should be predicted. As soon as you see
    the first unique pattern, the predictions should collapse to be a perfect
    prediction."""
        self.init({"cellsPerColumn": 4})

        numbers = self.sequenceMachine.generateNumbers(2, 20, (0, 5))
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)

        sumPredictedInactiveColumns = stats[1][2]
        self.assertTrue(sumPredictedInactiveColumns < 26 * 2)

        # At the end of each shared sequence, there should be
        # predicted but inactive columns
        self.assertTrue(len(self.tm.predictedInactiveColumnsList[5]) > 0)
        self.assertTrue(len(self.tm.predictedInactiveColumnsList[26]) > 0)

    def testH4(self):
        """Shared patterns. Similar to H2 except that patterns are shared between
    sequences.  All sequences are different shufflings of the same set of N
    patterns (there is no shared subsequence)."""
        self.init({"cellsPerColumn": 4})

        numbers = []
        for _ in xrange(2):
            numbers += self.sequenceMachine.generateNumbers(1, 20)

        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        for _ in xrange(20):
            self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)

        averagePredictedInactiveColumns = stats[1][3]
        self.assertTrue(averagePredictedInactiveColumns < 3)

    def testH5(self):
        """Combination of H4) and H2).
    Shared patterns in different sequences, with a shared subsequence."""
        self.init({"cellsPerColumn": 4})

        numbers = []
        shared = self.sequenceMachine.generateNumbers(1, 5)[:-1]
        for _ in xrange(2):
            sublist = self.sequenceMachine.generateNumbers(1, 20)
            sublist = [x for x in sublist if x not in xrange(5)]
            numbers += sublist[0:10] + shared + sublist[10:]

        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        for _ in xrange(20):
            self.feedTM(sequence)

        stats = self._testTM(sequence)

        self.assertAllActiveWerePredicted(stats)

        averagePredictedInactiveColumns = stats[1][3]
        self.assertTrue(averagePredictedInactiveColumns < 3)

    def testH9(self):
        """Sensitivity to small amounts of spatial noise during inference
    (X = 0.05). Parameters the same as B11, and sequences like H2."""
        self.init({"cellsPerColumn": 4, "activationThreshold": 8})

        numbers = self.sequenceMachine.generateNumbers(2, 20, (10, 15))
        sequence = self.sequenceMachine.generateFromNumbers(numbers)

        for _ in xrange(10):
            self.feedTM(sequence)

        sequence = self.sequenceMachine.addSpatialNoise(sequence, 0.05)
        stats = self._testTM(sequence)

        averageUnpredictedActiveColumns = stats[4][3]
        self.assertTrue(averageUnpredictedActiveColumns < 3)

    # ==============================
    # Overrides
    # ==============================

    @classmethod
    def setUpClass(cls):
        cls.allStats = []

    @classmethod
    def tearDownClass(cls):
        cols = [
            "Test", "predicted active cells (stats)",
            "predicted inactive cells (stats)",
            "predicted active columns (stats)",
            "predicted inactive columns (stats)",
            "unpredicted active columns (stats)"
        ]

        table = PrettyTable(cols)

        for stats in cls.allStats:
            row = [stats[0]] + [tuple(x) for x in list(stats[1])]
            table.add_row(row)

        print
        print table
        print "(stats) => (min, max, sum, average, standard deviation)"

    def setUp(self):
        super(ExtensiveTemporalMemoryTest, self).setUp()

        if self.VERBOSITY >= 2:
            print(
                "\n"
                "======================================================\n"
                "Test: {0} \n"
                "{1}\n"
                "======================================================\n"
            ).format(self.id(), self.shortDescription())

    def feedTM(self, sequence, learn=True, num=1):
        super(ExtensiveTemporalMemoryTest, self).feedTM(sequence,
                                                        learn=learn,
                                                        num=num)

        if self.VERBOSITY >= 2:
            print self.tm.prettyPrintHistory(verbosity=self.VERBOSITY - 2)
            print

        if learn and self.VERBOSITY >= 3:
            print self.tm.prettyPrintConnections()

    # ==============================
    # Helper functions
    # ==============================

    def _testTM(self, sequence):
        self.feedTM(sequence, learn=False)
        stats = self.tm.getStatistics()

        self.allStats.append((self.id(), stats))

        return stats

    def assertAllActiveWerePredicted(self, stats):
        self.assertEqual(stats.unpredictedActiveColumns.sum, 0)

        self.assertEqual(stats.predictedActiveColumns.min, 21)
        self.assertEqual(stats.predictedActiveColumns.max, 25)

    def assertAllInactiveWereUnpredicted(self, stats):
        self.assertEqual(stats.predictedInactiveColumns.sum, 0)

    def assertAllActiveWereUnpredicted(self, stats):
        self.assertEqual(stats.predictedActiveColumns.sum, 0)

        self.assertEqual(stats.unpredictedActiveColumns.min, 21)
        self.assertEqual(stats.unpredictedActiveColumns.max, 25)
Пример #11
0
 def setUp(self):
   self.patternMachine = PatternMachine(10000, 5, num=50)
Пример #12
0
 def setUp(self):
   self.patternMachine = PatternMachine(10000, 5, num=50)
Пример #13
0
class PatternMachineTest(unittest.TestCase):


  def setUp(self):
    self.patternMachine = PatternMachine(10000, 5, num=50)


  def testGet(self):
    patternA = self.patternMachine.get(48)
    self.assertEqual(len(patternA), 5)

    patternB = self.patternMachine.get(49)
    self.assertEqual(len(patternB), 5)

    self.assertEqual(patternA & patternB, set())


  def testGetOutOfBounds(self):
    args = [50]
    self.assertRaises(IndexError, self.patternMachine.get, *args)


  def testAddNoise(self):
    patternMachine = PatternMachine(10000, 1000, num=1)
    pattern = patternMachine.get(0)

    noisy = patternMachine.addNoise(pattern, 0.0)
    self.assertEqual(len(pattern & noisy), 1000)

    noisy = patternMachine.addNoise(pattern, 0.5)
    self.assertTrue(400 < len(pattern & noisy) < 600)

    noisy = patternMachine.addNoise(pattern, 1.0)
    self.assertTrue(50 < len(pattern & noisy) < 150)


  def testNumbersForBit(self):
    pattern = self.patternMachine.get(49)

    for bit in pattern:
      self.assertEqual(self.patternMachine.numbersForBit(bit), set([49]))


  def testNumbersForBitOutOfBounds(self):
    args = [10000]
    self.assertRaises(IndexError, self.patternMachine.numbersForBit, *args)


  def testNumberMapForBits(self):
    pattern = self.patternMachine.get(49)
    numberMap = self.patternMachine.numberMapForBits(pattern)

    self.assertEqual(numberMap.keys(), [49])
    self.assertEqual(numberMap[49], pattern)


  def testWList(self):
    w = [4, 7, 11]
    patternMachine = PatternMachine(100, w, num=50)
    widths = dict((el, 0) for el in w)

    for i in range(50):
      pattern = patternMachine.get(i)
      width = len(pattern)
      self.assertTrue(width in w)
      widths[len(pattern)] += 1

    for i in w:
      self.assertTrue(widths[i] > 0)