本文整理汇总了Python中nupic.bindings.algorithms.SpatialPooler类的典型用法代码示例。如果您正苦于以下问题:Python SpatialPooler类的具体用法?Python SpatialPooler怎么用?Python SpatialPooler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SpatialPooler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testInhibitColumnsGlobal
def testInhibitColumnsGlobal(self):
sp = SpatialPooler(inputDimensions = [10],
columnDimensions = [10],
globalInhibition = True,
numActiveColumnsPerInhArea = 10)
overlaps = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
expectedActive = set([5, 6, 7, 8, 9])
active = sp._inhibitColumns(np.array(overlaps, dtype=realDType))
active = set(active)
self.assertSetEqual(active, expectedActive,
"Input: {0}\tExpected: {1}\tActual: {2}".format(
overlaps, expectedActive, active))
示例2: __init__
def __init__(self, numFields):
a=dict()
t=[] # target
super(SpatialPoolerAgent, self).__init__(a, t, listMemFields=["score", "visited"], name='SPlearner')
self.me['x']=0
self.me['y']=0
self.me['steps']=0
self.enc = UtilEncoder(length=numFields, minval=0, maxval=100, scoreMin=0, scoreMax=100, scoreResolution=0.1)
self.enc.setEvaluationFn(evalFn)
# spatial pooler
self.sp = SP(
inputDimensions = [self.enc._offset],
columnDimensions = [1024],
potentialRadius = 15,
potentialPct = 0.5,
globalInhibition = True,
localAreaDensity = -1.0,
numActiveColumnsPerInhArea = 5,
stimulusThreshold=0,
synPermInactiveDec=0.01,
synPermActiveInc = 0.1,
synPermConnected = 0.20,
minPctOverlapDutyCycle = 0.1,
minPctActiveDutyCycle = 0.1,
dutyCyclePeriod = 10,
maxBoost = 10.0,
seed = -1,
spVerbosity = 2,)
self.cls = Clas() # classifier
示例3: initialize
def initialize(self):
# Initialize the RDSE with a resolution; calculated from the data min and
# max, the resolution is specific to the data stream.
rangePadding = abs(self.inputMax - self.inputMin) * 0.2
minVal = self.inputMin - rangePadding
maxVal = (self.inputMax + rangePadding
if self.inputMin != self.inputMax
else self.inputMin + 1)
numBuckets = 130.0
resolution = max(0.001, (maxVal - minVal) / numBuckets)
self.valueEncoder = RandomDistributedScalarEncoder(resolution, seed=42)
self.encodedValue = np.zeros(self.valueEncoder.getWidth(),
dtype=np.uint32)
# Initialize the timestamp encoder
self.timestampEncoder = DateEncoder(timeOfDay=(21, 9.49, ))
self.encodedTimestamp = np.zeros(self.timestampEncoder.getWidth(),
dtype=np.uint32)
inputWidth = (self.timestampEncoder.getWidth() +
self.valueEncoder.getWidth())
self.sp = SpatialPooler(**{
"globalInhibition": True,
"columnDimensions": [2048],
"inputDimensions": [inputWidth],
"potentialRadius": inputWidth,
"numActiveColumnsPerInhArea": 40,
"seed": 1956,
"potentialPct": 0.8,
"boostStrength": 0.0,
"synPermActiveInc": 0.003,
"synPermConnected": 0.2,
"synPermInactiveDec": 0.0005,
})
self.spOutput = np.zeros(2048, dtype=np.float32)
self.tm = TemporalMemory(**{
"activationThreshold": 20,
"cellsPerColumn": 32,
"columnDimensions": (2048,),
"initialPermanence": 0.24,
"maxSegmentsPerCell": 128,
"maxSynapsesPerSegment": 128,
"minThreshold": 13,
"maxNewSynapseCount": 31,
"permanenceDecrement": 0.008,
"permanenceIncrement": 0.04,
"seed": 1960,
})
if self.useLikelihood:
learningPeriod = math.floor(self.probationaryPeriod / 2.0)
self.anomalyLikelihood = anomaly_likelihood.AnomalyLikelihood(
claLearningPeriod=learningPeriod,
estimationSamples=self.probationaryPeriod - learningPeriod,
reestimationPeriod=100
)
示例4: testCalculateOverlap
def testCalculateOverlap(self):
sp = SpatialPooler(inputDimensions = [10],
columnDimensions = [5])
permanences = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1]
]
inputVectors = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
]
expectedOverlaps = [
[0, 0, 0, 0, 0],
[10, 8, 6, 4, 2],
[5, 4, 3, 2, 1],
[5, 3, 1, 0, 0],
[1, 1, 1, 1, 1]
]
for column, permanence in enumerate(permanences):
sp.setPermanence(column, np.array(permanence, dtype=realDType))
for inputVector, expectedOverlap in zip(inputVectors, expectedOverlaps):
inputVector = np.array(inputVector, dtype=uintDType)
overlap = set(sp._calculateOverlap(inputVector))
expected = set(expectedOverlap)
self.assertSetEqual(overlap, expected,
"Input: {0}\tExpected: {1}\tActual: {2}".format(
inputVector, expected, overlap))
示例5: loadSpatialPooler
def loadSpatialPooler(self, id, iteration=None):
start = time.time() * 1000
if iteration is None:
iteration = self.getMaxIteration(id)
key = self.SP_KEY.format(id, iteration)
path = self._workingDir + "/" + key
with open(path, "r") as spFile:
proto = SpatialPoolerProto_capnp.SpatialPoolerProto.read(spFile)
sp = SpatialPooler.read(proto)
end = time.time() * 1000
print "\t{} SP de-serialization from {} took {} ms".format(
id, key, (end - start)
)
return sp
示例6: initialize
def initialize(self):
# Scalar Encoder
resolution = self.getEncoderResolution()
self.encoder = RandomDistributedScalarEncoder(resolution, seed=42)
self.encoderOutput = np.zeros(self.encoder.getWidth(), dtype=np.uint32)
# Spatial Pooler
spInputWidth = self.encoder.getWidth()
self.spParams = {
"globalInhibition": True,
"columnDimensions": [self.numColumns],
"inputDimensions": [spInputWidth],
"potentialRadius": spInputWidth,
"numActiveColumnsPerInhArea": 40,
"seed": 1956,
"potentialPct": 0.8,
"boostStrength": 5.0,
"synPermActiveInc": 0.003,
"synPermConnected": 0.2,
"synPermInactiveDec": 0.0005,
}
self.sp = SpatialPooler(**self.spParams)
self.spOutput = np.zeros(self.numColumns, dtype=np.uint32)
# Temporal Memory
self.tmParams = {
"activationThreshold": 20,
"cellsPerColumn": self.cellsPerColumn,
"columnDimensions": (self.numColumns,),
"initialPermanence": 0.24,
"maxSegmentsPerCell": 128,
"maxSynapsesPerSegment": 128,
"minThreshold": 13,
"maxNewSynapseCount": 31,
"permanenceDecrement": 0.008,
"permanenceIncrement": 0.04,
"seed": 1960,
}
self.tm = TemporalMemory(**self.tmParams)
# Sanity
if self.runSanity:
self.sanity = sanity.SPTMInstance(self.sp, self.tm)
示例7: testUpdatePermanencesForColumn
def testUpdatePermanencesForColumn(self):
sp = SpatialPooler(inputDimensions = [5],
columnDimensions = [5])
sp.setSynPermTrimThreshold(0.05)
permanencesList = [
[ -0.10, 0.500, 0.400, 0.010, 0.020 ],
[ 0.300, 0.010, 0.020, 0.120, 0.090 ],
[ 0.070, 0.050, 1.030, 0.190, 0.060 ],
[ 0.180, 0.090, 0.110, 0.010, 0.030 ],
[ 0.200, 0.101, 0.050, -0.09, 1.100 ]]
expectedPermanencesList = [
[ 0.000, 0.500, 0.400, 0.000, 0.000],
# Clip - - Trim Trim
[0.300, 0.000, 0.000, 0.120, 0.090],
# - Trim Trim - -
[0.070, 0.050, 1.000, 0.190, 0.060],
# - - Clip - -
[0.180, 0.090, 0.110, 0.000, 0.000],
# - - - Trim Trim
[0.200, 0.101, 0.050, 0.000, 1.000]]
# - - - Clip Clip
expectedConnectedSynapsesList = [
[0, 1, 1, 0, 0],
[1, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[1, 0, 1, 0, 0],
[1, 1, 0, 0, 1]]
expectedConnectedCounts = [2, 2, 2, 2, 3]
for i in xrange(5):
permanences = np.array(permanencesList[i], dtype=realDType)
expectedPermanences = np.array(expectedPermanencesList[i],
dtype=realDType)
expectedConnectedSynapses = expectedConnectedSynapsesList[i]
sp._updatePermanencesForColumn(permanences, i, False)
updatedPermanences = np.zeros(5, dtype=realDType)
connectedSynapses = np.zeros(5, dtype=uintDType)
connectedCounts = np.zeros(5, dtype=uintDType)
sp.getPermanence(i, updatedPermanences)
sp.getConnectedSynapses(i, connectedSynapses)
sp.getConnectedCounts(connectedCounts)
np.testing.assert_almost_equal(updatedPermanences, expectedPermanences)
self.assertEqual(list(connectedSynapses), expectedConnectedSynapses)
self.assertEqual(connectedCounts[i], expectedConnectedCounts[i])
示例8: DistalTimestamps1CellPerColumnDetector
class DistalTimestamps1CellPerColumnDetector(AnomalyDetector):
"""The 'numenta' detector, with the following changes:
- Use pure Temporal Memory, not the classic TP that uses backtracking.
- Don't spatial pool the timestamp. Pass it in as distal input.
- 1 cell per column.
- Use w=41 in the scalar encoding, rather than w=21, to make up for the
lost timestamp input to the spatial pooler.
"""
def __init__(self, *args, **kwargs):
super(DistalTimestamps1CellPerColumnDetector, self).__init__(*args,
**kwargs)
self.valueEncoder = None
self.encodedValue = None
self.timestampEncoder = None
self.encodedTimestamp = None
self.activeExternalCells = []
self.prevActiveExternalCells = []
self.sp = None
self.spOutput = None
self.etm = None
self.anomalyLikelihood = None
def getAdditionalHeaders(self):
"""Returns a list of strings."""
return ["raw_score"]
def initialize(self):
rangePadding = abs(self.inputMax - self.inputMin) * 0.2
minVal = self.inputMin - rangePadding
maxVal = (self.inputMax + rangePadding
if self.inputMin != self.inputMax
else self.inputMin + 1)
numBuckets = 130.0
resolution = max(0.001, (maxVal - minVal) / numBuckets)
self.valueEncoder = RandomDistributedScalarEncoder(resolution,
w=41,
seed=42)
self.encodedValue = np.zeros(self.valueEncoder.getWidth(),
dtype=np.uint32)
self.timestampEncoder = DateEncoder(timeOfDay=(21,9.49,))
self.encodedTimestamp = np.zeros(self.timestampEncoder.getWidth(),
dtype=np.uint32)
inputWidth = self.valueEncoder.getWidth()
self.sp = SpatialPooler(**{
"globalInhibition": True,
"columnDimensions": [2048],
"inputDimensions": [inputWidth],
"potentialRadius": inputWidth,
"numActiveColumnsPerInhArea": 40,
"seed": 1956,
"potentialPct": 0.8,
"boostStrength": 0.0,
"synPermActiveInc": 0.003,
"synPermConnected": 0.2,
"synPermInactiveDec": 0.0005,
})
self.spOutput = np.zeros(2048, dtype=np.float32)
self.etm = ExtendedTemporalMemory(**{
"activationThreshold": 13,
"cellsPerColumn": 1,
"columnDimensions": (2048,),
"basalInputDimensions": (self.timestampEncoder.getWidth(),),
"initialPermanence": 0.21,
"maxSegmentsPerCell": 128,
"maxSynapsesPerSegment": 32,
"minThreshold": 10,
"maxNewSynapseCount": 20,
"permanenceDecrement": 0.1,
"permanenceIncrement": 0.1,
"seed": 1960,
"checkInputs": False,
})
learningPeriod = math.floor(self.probationaryPeriod / 2.0)
self.anomalyLikelihood = anomaly_likelihood.AnomalyLikelihood(
claLearningPeriod=learningPeriod,
estimationSamples=self.probationaryPeriod - learningPeriod,
reestimationPeriod=100
)
def handleRecord(self, inputData):
"""Returns a tuple (anomalyScore, rawScore)."""
self.valueEncoder.encodeIntoArray(inputData["value"],
self.encodedValue)
self.timestampEncoder.encodeIntoArray(inputData["timestamp"],
self.encodedTimestamp)
self.prevActiveExternalCells = self.activeExternalCells
self.activeExternalCells = self.encodedTimestamp.nonzero()[0]
#.........这里部分代码省略.........
示例9: NumentaTMLowLevelDetector
class NumentaTMLowLevelDetector(AnomalyDetector):
"""The 'numentaTM' detector, but not using the CLAModel or network API """
def __init__(self, *args, **kwargs):
super(NumentaTMLowLevelDetector, self).__init__(*args, **kwargs)
self.valueEncoder = None
self.encodedValue = None
self.timestampEncoder = None
self.encodedTimestamp = None
self.sp = None
self.spOutput = None
self.tm = None
self.anomalyLikelihood = None
# Set this to False if you want to get results based on raw scores
# without using AnomalyLikelihood. This will give worse results, but
# useful for checking the efficacy of AnomalyLikelihood. You will need
# to re-optimize the thresholds when running with this setting.
self.useLikelihood = True
def getAdditionalHeaders(self):
"""Returns a list of strings."""
return ["raw_score"]
def initialize(self):
# Initialize the RDSE with a resolution; calculated from the data min and
# max, the resolution is specific to the data stream.
rangePadding = abs(self.inputMax - self.inputMin) * 0.2
minVal = self.inputMin - rangePadding
maxVal = (self.inputMax + rangePadding
if self.inputMin != self.inputMax
else self.inputMin + 1)
numBuckets = 130.0
resolution = max(0.001, (maxVal - minVal) / numBuckets)
self.valueEncoder = RandomDistributedScalarEncoder(resolution, seed=42)
self.encodedValue = np.zeros(self.valueEncoder.getWidth(),
dtype=np.uint32)
# Initialize the timestamp encoder
self.timestampEncoder = DateEncoder(timeOfDay=(21, 9.49, ))
self.encodedTimestamp = np.zeros(self.timestampEncoder.getWidth(),
dtype=np.uint32)
inputWidth = (self.timestampEncoder.getWidth() +
self.valueEncoder.getWidth())
self.sp = SpatialPooler(**{
"globalInhibition": True,
"columnDimensions": [2048],
"inputDimensions": [inputWidth],
"potentialRadius": inputWidth,
"numActiveColumnsPerInhArea": 40,
"seed": 1956,
"potentialPct": 0.8,
"boostStrength": 0.0,
"synPermActiveInc": 0.003,
"synPermConnected": 0.2,
"synPermInactiveDec": 0.0005,
})
self.spOutput = np.zeros(2048, dtype=np.float32)
self.tm = TemporalMemory(**{
"activationThreshold": 20,
"cellsPerColumn": 32,
"columnDimensions": (2048,),
"initialPermanence": 0.24,
"maxSegmentsPerCell": 128,
"maxSynapsesPerSegment": 128,
"minThreshold": 13,
"maxNewSynapseCount": 31,
"permanenceDecrement": 0.008,
"permanenceIncrement": 0.04,
"seed": 1960,
})
if self.useLikelihood:
learningPeriod = math.floor(self.probationaryPeriod / 2.0)
self.anomalyLikelihood = anomaly_likelihood.AnomalyLikelihood(
claLearningPeriod=learningPeriod,
estimationSamples=self.probationaryPeriod - learningPeriod,
reestimationPeriod=100
)
def handleRecord(self, inputData):
"""Returns a tuple (anomalyScore, rawScore)."""
# Encode the input data record
self.valueEncoder.encodeIntoArray(
inputData["value"], self.encodedValue)
self.timestampEncoder.encodeIntoArray(
inputData["timestamp"], self.encodedTimestamp)
# Run the encoded data through the spatial pooler
self.sp.compute(np.concatenate((self.encodedTimestamp,
self.encodedValue,)),
True, self.spOutput)
#.........这里部分代码省略.........
示例10: SpatialPoolerAPITest
class SpatialPoolerAPITest(unittest.TestCase):
"""Tests for SpatialPooler public API"""
def setUp(self):
self.sp = SpatialPooler(columnDimensions=[5], inputDimensions=[5])
def testCompute(self):
# Check that there are no errors in call to compute
inputVector = numpy.ones(5)
activeArray = numpy.zeros(5)
self.sp.compute(inputVector, True, activeArray)
def testGetUpdatePeriod(self):
inParam = 1234
self.sp.setUpdatePeriod(inParam)
outParam = self.sp.getUpdatePeriod()
self.assertEqual(inParam, outParam)
def testGetPotentialRadius(self):
inParam = 56
self.sp.setPotentialRadius(inParam)
outParam = self.sp.getPotentialRadius()
self.assertEqual(inParam, outParam)
def testGetPotentialPct(self):
inParam = 0.4
self.sp.setPotentialPct(inParam)
outParam = self.sp.getPotentialPct()
self.assertAlmostEqual(inParam, outParam)
def testGetGlobalInhibition(self):
inParam = True
self.sp.setGlobalInhibition(inParam)
outParam = self.sp.getGlobalInhibition()
self.assertEqual(inParam, outParam)
inParam = False
self.sp.setGlobalInhibition(inParam)
outParam = self.sp.getGlobalInhibition()
self.assertEqual(inParam, outParam)
def testGetNumActiveColumnsPerInhArea(self):
inParam = 7
self.sp.setNumActiveColumnsPerInhArea(inParam)
outParam = self.sp.getNumActiveColumnsPerInhArea()
self.assertEqual(inParam, outParam)
def testGetLocalAreaDensity(self):
inParam = 0.4
self.sp.setLocalAreaDensity(inParam)
outParam = self.sp.getLocalAreaDensity()
self.assertAlmostEqual(inParam, outParam)
def testGetStimulusThreshold(self):
inParam = 89
self.sp.setStimulusThreshold(inParam)
outParam = self.sp.getStimulusThreshold()
self.assertEqual(inParam, outParam)
def testGetInhibitionRadius(self):
inParam = 4
self.sp.setInhibitionRadius(inParam)
outParam = self.sp.getInhibitionRadius()
self.assertEqual(inParam, outParam)
def testGetDutyCyclePeriod(self):
inParam = 2020
self.sp.setDutyCyclePeriod(inParam)
outParam = self.sp.getDutyCyclePeriod()
self.assertEqual(inParam, outParam)
def testGetBoostStrength(self):
inParam = 78
self.sp.setBoostStrength(inParam)
outParam = self.sp.getBoostStrength()
self.assertEqual(inParam, outParam)
def testGetIterationNum(self):
inParam = 999
self.sp.setIterationNum(inParam)
outParam = self.sp.getIterationNum()
self.assertEqual(inParam, outParam)
def testGetIterationLearnNum(self):
inParam = 666
self.sp.setIterationLearnNum(inParam)
#.........这里部分代码省略.........
示例11: convertSP
def convertSP(self, pySp, newSeed):
columnDim = pySp._columnDimensions
inputDim = pySp._inputDimensions
numInputs = pySp.getNumInputs()
numColumns = pySp.getNumColumns()
cppSp = CPPSpatialPooler(inputDim,columnDim)
cppSp.setPotentialRadius(pySp.getPotentialRadius())
cppSp.setPotentialPct(pySp.getPotentialPct())
cppSp.setGlobalInhibition(pySp.getGlobalInhibition())
numActiveColumnsPerInhArea = pySp.getNumActiveColumnsPerInhArea()
localAreaDensity = pySp.getLocalAreaDensity()
if (numActiveColumnsPerInhArea > 0):
cppSp.setNumActiveColumnsPerInhArea(numActiveColumnsPerInhArea)
else:
cppSp.setLocalAreaDensity(localAreaDensity)
cppSp.setStimulusThreshold(pySp.getStimulusThreshold())
cppSp.setInhibitionRadius(pySp.getInhibitionRadius())
cppSp.setDutyCyclePeriod(pySp.getDutyCyclePeriod())
cppSp.setMaxBoost(pySp.getMaxBoost())
cppSp.setIterationNum(pySp.getIterationNum())
cppSp.setIterationLearnNum(pySp.getIterationLearnNum())
cppSp.setSpVerbosity(pySp.getSpVerbosity())
cppSp.setUpdatePeriod(pySp.getUpdatePeriod())
cppSp.setSynPermTrimThreshold(pySp.getSynPermTrimThreshold())
cppSp.setSynPermActiveInc(pySp.getSynPermActiveInc())
cppSp.setSynPermInactiveDec(pySp.getSynPermInactiveDec())
cppSp.setSynPermBelowStimulusInc(pySp.getSynPermBelowStimulusInc())
cppSp.setSynPermConnected(pySp.getSynPermConnected())
cppSp.setMinPctOverlapDutyCycles(pySp.getMinPctOverlapDutyCycles())
cppSp.setMinPctActiveDutyCycles(pySp.getMinPctActiveDutyCycles())
boostFactors = numpy.zeros(numColumns).astype(realType)
pySp.getBoostFactors(boostFactors)
cppSp.setBoostFactors(boostFactors)
overlapDuty = numpy.zeros(numColumns).astype(realType)
pySp.getOverlapDutyCycles(overlapDuty)
cppSp.setOverlapDutyCycles(overlapDuty)
activeDuty = numpy.zeros(numColumns).astype(realType)
pySp.getActiveDutyCycles(activeDuty)
cppSp.setActiveDutyCycles(activeDuty)
minOverlapDuty = numpy.zeros(numColumns).astype(realType)
pySp.getMinOverlapDutyCycles(minOverlapDuty)
cppSp.setMinOverlapDutyCycles(minOverlapDuty)
minActiveDuty = numpy.zeros(numColumns).astype(realType)
pySp.getMinActiveDutyCycles(minActiveDuty)
cppSp.setMinActiveDutyCycles(minActiveDuty)
for i in xrange(numColumns):
potential = numpy.zeros(numInputs).astype(uintType)
pySp.getPotential(i, potential)
cppSp.setPotential(i, potential)
perm = numpy.zeros(numInputs).astype(realType)
pySp.getPermanence(i, perm)
cppSp.setPermanence(i, perm)
pySp._random = NupicRandom(newSeed)
cppSp.seed_(newSeed)
return cppSp
示例12: setUp
def setUp(self):
self.sp = SpatialPooler(columnDimensions=[5], inputDimensions=[5])
示例13: BaseNetwork
class BaseNetwork(object):
def __init__(self, inputMin=None, inputMax=None, runSanity=False):
self.inputMin = inputMin
self.inputMax = inputMax
self.runSanity = runSanity
self.encoder = None
self.encoderOutput = None
self.sp = None
self.spOutput = None
self.spOutputNZ = None
self.tm = None
self.anomalyScore = None
if runSanity:
self.sanity = None
self.defaultEncoderResolution = 0.0001
self.numColumns = 2048
self.cellsPerColumn = 32
self.predictedActiveCells = None
self.previouslyPredictiveCells = None
def initialize(self):
# Scalar Encoder
resolution = self.getEncoderResolution()
self.encoder = RandomDistributedScalarEncoder(resolution, seed=42)
self.encoderOutput = np.zeros(self.encoder.getWidth(), dtype=np.uint32)
# Spatial Pooler
spInputWidth = self.encoder.getWidth()
self.spParams = {
"globalInhibition": True,
"columnDimensions": [self.numColumns],
"inputDimensions": [spInputWidth],
"potentialRadius": spInputWidth,
"numActiveColumnsPerInhArea": 40,
"seed": 1956,
"potentialPct": 0.8,
"boostStrength": 5.0,
"synPermActiveInc": 0.003,
"synPermConnected": 0.2,
"synPermInactiveDec": 0.0005,
}
self.sp = SpatialPooler(**self.spParams)
self.spOutput = np.zeros(self.numColumns, dtype=np.uint32)
# Temporal Memory
self.tmParams = {
"activationThreshold": 20,
"cellsPerColumn": self.cellsPerColumn,
"columnDimensions": (self.numColumns,),
"initialPermanence": 0.24,
"maxSegmentsPerCell": 128,
"maxSynapsesPerSegment": 128,
"minThreshold": 13,
"maxNewSynapseCount": 31,
"permanenceDecrement": 0.008,
"permanenceIncrement": 0.04,
"seed": 1960,
}
self.tm = TemporalMemory(**self.tmParams)
# Sanity
if self.runSanity:
self.sanity = sanity.SPTMInstance(self.sp, self.tm)
def handleRecord(self, scalarValue, label=None, skipEncoding=False,
learningMode=True):
"""Process one record."""
if self.runSanity:
self.sanity.waitForUserContinue()
# Encode the input data record if it hasn't already been encoded.
if not skipEncoding:
self.encodeValue(scalarValue)
# Run the encoded data through the spatial pooler
self.sp.compute(self.encoderOutput, learningMode, self.spOutput)
self.spOutputNZ = self.spOutput.nonzero()[0]
# WARNING: this needs to happen here, before the TM runs.
self.previouslyPredictiveCells = self.tm.getPredictiveCells()
# Run SP output through temporal memory
self.tm.compute(self.spOutputNZ)
self.predictedActiveCells = _computePredictedActiveCells(
self.tm.getActiveCells(), self.previouslyPredictiveCells)
# Anomaly score
self.anomalyScore = _computeAnomalyScore(self.spOutputNZ,
self.previouslyPredictiveCells,
self.cellsPerColumn)
# Run Sanity
#.........这里部分代码省略.........
示例14: testUpdateDutyCycles
def testUpdateDutyCycles(self):
sp = SpatialPooler(inputDimensions = [5],
columnDimensions = [5])
initOverlapArr1 = np.array([1, 1, 1, 1, 1], dtype=realDType)
sp.setOverlapDutyCycles(initOverlapArr1);
overlaps = np.array([1, 5, 7, 0, 0], dtype=uintDType)
active = np.array([0, 0, 0, 0, 0], dtype=uintDType)
sp.setIterationNum(2)
sp._updateDutyCycles(overlaps, active);
resultOverlapArr1 = np.zeros(5, dtype=realDType)
sp.getOverlapDutyCycles(resultOverlapArr1)
trueOverlapArr1 = np.array([1, 1, 1, 0.5, 0.5], dtype=realDType)
self.assertEqual(list(resultOverlapArr1), list(trueOverlapArr1))
sp.setOverlapDutyCycles(initOverlapArr1);
sp.setIterationNum(2000);
sp.setUpdatePeriod(1000);
sp._updateDutyCycles(overlaps, active);
resultOverlapArr2 = np.zeros(5, dtype=realDType)
sp.getOverlapDutyCycles(resultOverlapArr2);
trueOverlapArr2 = np.array([1, 1, 1, 0.999, 0.999], dtype=realDType)
self.assertEqual(list(resultOverlapArr2), list(trueOverlapArr2))
示例15: testComputeParametersValidation
def testComputeParametersValidation(self):
sp = SpatialPooler(inputDimensions=[5], columnDimensions=[5])
inputGood = np.ones(5, dtype=uintDType)
outGood = np.zeros(5, dtype=uintDType)
inputBad = np.ones(5, dtype=realDType)
inputBad2D = np.ones((5, 5), dtype=realDType)
outBad = np.zeros(5, dtype=realDType)
outBad2D = np.zeros((5, 5), dtype=realDType)
# Validate good parameters
sp.compute(inputGood, False, outGood)
# Validate bad parameters
with self.assertRaises(RuntimeError):
sp.compute(inputBad, False, outBad)
# Validate bad input
with self.assertRaises(RuntimeError):
sp.compute(inputBad, False, outGood)
# Validate bad 2d input
with self.assertRaises(RuntimeError):
sp.compute(inputBad2D, False, outGood)
# Validate bad output
with self.assertRaises(RuntimeError):
sp.compute(inputGood, False, outBad)
# Validate bad 2d output
with self.assertRaises(RuntimeError):
sp.compute(inputGood, False, outBad2D)