当前位置: 首页>>代码示例>>Python>>正文


Python SpatialPooler.getColumnDimensions方法代码示例

本文整理汇总了Python中nupic.research.spatial_pooler.SpatialPooler.getColumnDimensions方法的典型用法代码示例。如果您正苦于以下问题:Python SpatialPooler.getColumnDimensions方法的具体用法?Python SpatialPooler.getColumnDimensions怎么用?Python SpatialPooler.getColumnDimensions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在nupic.research.spatial_pooler.SpatialPooler的用法示例。


在下文中一共展示了SpatialPooler.getColumnDimensions方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: calculateOverlapCurve

# 需要导入模块: from nupic.research.spatial_pooler import SpatialPooler [as 别名]
# 或者: from nupic.research.spatial_pooler.SpatialPooler import getColumnDimensions [as 别名]
      inputOverlapScore, outputOverlapScore = calculateOverlapCurve(
        sp, inputVectors, inputVectorType)
      plt.plot(np.mean(inputOverlapScore, 0), np.mean(outputOverlapScore, 0),
               color=cmap(float(epoch) / epochs))

    activeColumnsPreviousEpoch = copy.copy(activeColumnsCurrentEpoch)
    connectedCountsPreviousEpoch = copy.copy(connectedCounts)

    # train SP here,
    # Learn is turned off at the first epoch to gather stats of untrained SP
    learn = False if epoch == 0 else True

    # randomize the presentation order of input vectors
    sdrOrders = np.random.permutation(np.arange(numInputVector))
    for i in range(numInputVector):
      outputColumns = np.zeros(sp.getColumnDimensions(), dtype=uintType)
      inputVector = copy.deepcopy(inputVectors[sdrOrders[i]][:])
      # addNoiseToVector(inputVector, 0.05, inputVectorType)
      sp.compute(inputVector, learn, outputColumns)

      activeColumnsCurrentEpoch[sdrOrders[i]][:] = np.reshape(outputColumns,
                                                              (1, columnNumber))

    sp.getConnectedCounts(connectedCounts)

    entropyTrace.append(calculateEntropy(activeColumnsCurrentEpoch))

    if epoch >= 1:
      activeColumnsDiff = activeColumnsCurrentEpoch > activeColumnsPreviousEpoch
      numBitDiffTrace.append(np.mean(np.sum(activeColumnsDiff, 1)))
开发者ID:vaua,项目名称:nupic.research,代码行数:32,代码来源:train_sp.py

示例2: FeedbackModel

# 需要导入模块: from nupic.research.spatial_pooler import SpatialPooler [as 别名]
# 或者: from nupic.research.spatial_pooler.SpatialPooler import getColumnDimensions [as 别名]

#.........这里部分代码省略.........
            print("Using external Parameters!")

        else:
            self.wordSP = SpatialPooler(**self.defaultWordSPParams)
            self.wordTM = TemporalMemory(**self.defaultWordTMParams)
            self.actionSP = SpatialPooler(**self.defaultActionSPParams)
            self.actionTM = TemporalMemory(**self.defaultActionTMParams)
            print("External parameters invalid or not found, using"\
                " the default ones")

            defaultGeneralTMParams = {
                'columnDimensions': (2, max(self.wordTM.numberOfCells(),
                     self.actionTM.numberOfCells())),
                'seed': self.tmSeed
            }

            self.generalTM = TemporalMemory(**defaultGeneralTMParams)


        self.classifier = CLAClassifierCond(
            steps=[1, 2, 3],
            alpha=0.1,
            actValueAlpha=0.3,
            verbosity=0
        )

        self.startPointOverlap = CommonOverlap('==', 1,
            self.actionTM.columnDimensions, threshold=0.5)

    def processInput(self, sentence, actionSeq, wordSDR=None,
                     actionSDR=None, verbosity=0, learn=True):

        if wordSDR is None:
            wordSDR = numpy.zeros(self.wordSP.getColumnDimensions(),
                              dtype=numpy.uint8)
        if actionSDR is None:
            actionSDR = numpy.zeros(self.actionSP.getColumnDimensions(),
                              dtype=numpy.uint8)

        nCellsFromSentence = self.generalTM.columnDimensions[1]
        sentenceActiveCells = set()
        actionSeqActiveCells = set()
        recordNum = 0

        # Feed the words from the sentence to the region 1
        for word in sentence:
            encodedWord = self.wordEncoder.encode(word)
            self.wordSP.compute(encodedWord, learn, wordSDR)
            self.wordTM.compute(
                set(numpy.where(wordSDR > 0)[0]),
                learn
            )
            region1Predicting = (self.wordTM.predictiveCells != set())
            sentenceActiveCells.update(self.wordTM.getActiveCells())

            #print("{} - {}".format(word, ))
            retVal = self.classifier.compute(
                recordNum=recordNum,
                patternNZ=self.wordTM.getActiveCells(),
                classification={
                    'bucketIdx': self.wordEncoder.getBucketIndices(word)[0],
                    'actValue': word
                },
                learn=learn,
                infer=True,
                conditionFunc=lambda x: x.endswith("-event")
开发者ID:Kigalahad,项目名称:htm-teul,代码行数:70,代码来源:FeedbackModel.py

示例3: JoinedInputsModel

# 需要导入模块: from nupic.research.spatial_pooler import SpatialPooler [as 别名]
# 或者: from nupic.research.spatial_pooler.SpatialPooler import getColumnDimensions [as 别名]

#.........这里部分代码省略.........

            if maxTimeReached:
                break

            self.iterationsTrained += 1

    def processInput(self, inputData, recordNum, verbosity=0, learn=False):

        inputName = inputData[0]
        actualValue = inputData[1]

        if verbosity > 1:
            print("===== " + inputName + ": " + str(actualValue) + " =====")

        encodedValue = numpy.zeros(
            self.generalSP.getInputDimensions(),
            dtype=numpy.uint8
        )

        if inputName == 'wordInput':
            for word in actualValue:
                encodedValue[self.wordEncoder.getBucketIndices(word)] = 1

            actualValue = ' '.join(actualValue)

        elif(inputName == 'actionInput'):
            aux = self.actionEncoder.encode(actualValue)
            encodedValue[numpy.where(aux > 1)] = 1

        if actualValue not in self.buckets:
            self.buckets[actualValue] = len(self.buckets)

        bucketIndex = self.buckets[actualValue]

        if verbosity > 1:
            print("Encoded Value: {0}\n"\
                "Bucket Index: {1}\n".format(encodedValue, bucketIndex))

        spOutput = numpy.zeros(self.generalSP.getColumnDimensions(),
                    dtype=numpy.uint8)
        self.generalSP.compute(encodedValue, learn, spOutput)

        tmInput = numpy.where(spOutput > 0)[0]
        self.generalTM.compute(set(tmInput), learn)

        retVal = self.classifier.compute(
                recordNum=recordNum,
                patternNZ=self.generalTM.activeCells,
                classification={
                    'bucketIdx': self.buckets[actualValue],
                    'actValue': actualValue
                },
                learn=learn,
                infer=True,
                conditionFunc=lambda x: x.endswith("-event")
            )

        bestPredictions = []

        for step in retVal:
            if step == 'actualValues':
                continue

            higherProbIndex = numpy.argmax(retVal[step])
            bestPredictions.append(
                retVal['actualValues'][higherProbIndex]
            )

        if verbosity > 2 :
            print("  |  CLAClassifier best predictions for step1: ")
            top = sorted(retVal[1].tolist(), reverse=True)[:3]

            for prob in top:
                probIndex = retVal[1].tolist().index(prob)
                print(str(retVal['actualValues'][probIndex]) +
                    " - " + str(prob))

            print("  |  CLAClassifier best predictions for step2: ")
            top = sorted(retVal[2].tolist(), reverse=True)[:3]

            for prob in top:
                probIndex = retVal[2].tolist().index(prob)
                print(str(retVal['actualValues'][probIndex]) +
                    " - " + str(prob))

            print("")
            print("---------------------------------------------------")
            print("")

        return bestPredictions

    def inputSentence(self, sentence, verbosity=0, learn=False):

        inputData = ('wordInput', sentence)
        bestPredictions = self.processInput(inputData, 0, verbosity, learn)

        if verbosity > 1:
            print('Best Predictions: ' + str(bestPredictions))

        return bestPredictions
开发者ID:Kigalahad,项目名称:htm-teul,代码行数:104,代码来源:JoinedInputsModel.py


注:本文中的nupic.research.spatial_pooler.SpatialPooler.getColumnDimensions方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。