本文整理汇总了Python中nupic.bindings.algorithms.SpatialPooler.compute方法的典型用法代码示例。如果您正苦于以下问题:Python SpatialPooler.compute方法的具体用法?Python SpatialPooler.compute怎么用?Python SpatialPooler.compute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nupic.bindings.algorithms.SpatialPooler
的用法示例。
在下文中一共展示了SpatialPooler.compute方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BaseNetwork
# 需要导入模块: from nupic.bindings.algorithms import SpatialPooler [as 别名]
# 或者: from nupic.bindings.algorithms.SpatialPooler import compute [as 别名]
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
#.........这里部分代码省略.........
示例2: Example
# 需要导入模块: from nupic.bindings.algorithms import SpatialPooler [as 别名]
# 或者: from nupic.bindings.algorithms.SpatialPooler import compute [as 别名]
class Example(object):
"""A class to hold our code.
TODO: Get rid of this class, it just makes it more difficult to read the
code.
"""
def __init__(self, inputDimensions, columnDimensions):
"""
Parameters:
----------
_inputDimensions: The size of the input. (m,n) will give a size m x n
_inputDimensions: 입력의 크기. (m, n) 이라면 m x n 이 된다.
_columnDimensions: The size of the 2 dimensional array of columns
_columnDimensions: 2차원 컬럼 배열의 크기
"""
self.inputDimensions = inputDimensions
self.columnDimensions = columnDimensions
self.inputSize = np.array(inputDimensions).prod()
self.columnNumber = np.array(columnDimensions).prod()
self.inputArray = np.zeros(self.inputSize, dtype=uintType)
self.activeArray = np.zeros(self.columnNumber, dtype=uintType)
random.seed(1)
self.sp = SP(self.inputDimensions,
self.columnDimensions,
potentialRadius = self.inputSize,
numActiveColumnsPerInhArea = int(0.02*self.columnNumber),
globalInhibition = True,
seed = 1,
synPermActiveInc = 0.01,
synPermInactiveDec = 0.008)
def createInput(self):
"""create a random input vector"""
print "-" * 70 + "Creating a random input vector" + "-" * 70
#clear the inputArray to zero before creating a new input vector
self.inputArray[0:] = 0
for i in range(self.inputSize):
#randrange returns 0 or 1
#0이나 1로 랜덤하게 집어넣는다.
self.inputArray[i] = random.randrange(2)
def run(self):
"""Run the spatial pooler with the input vector
input vector로 sparial pooler를 돌려보자"""
print "-" * 80 + "Computing the SDR" + "-" * 80
#activeArray[column]=1 if column is active after spatial pooling
#activeArray[column]=1 이면 spatial pooling 결과 활성화된 컬럼이다.
self.sp.compute(self.inputArray, True, self.activeArray)
print self.activeArray.nonzero()
def addNoise(self, noiseLevel):
"""Flip the value of 10% of input bits (add noise)
:param noiseLevel: The percentage of total input bits that should be flipped
10% 정도 input bits를 뒤집어서(flip) 노이즈를 추가하자
:param noiseLevel: 몇 퍼센트나 노이즈를 추가할 것인지?
"""
for _ in range(int(noiseLevel * self.inputSize)):
# 0.1*self.inputSize represents 10% of the total input bits
# random.random() returns a float between 0 and 1
# 0.1*self.inputSize 이면 전체 input bits의 10%다.
# random.random() 은 0과 1사이의 실수를 반환하다.
randomPosition = int(random.random() * self.inputSize)
# Flipping the bit at the randomly picked position
# 랜덤한 위치의 bit를 뒤집자... 1이면 0으로, 0이면 1로!
if self.inputArray[randomPosition] == 1:
self.inputArray[randomPosition] = 0
else:
self.inputArray[randomPosition] = 1
示例3: NumentaTMLowLevelDetector
# 需要导入模块: from nupic.bindings.algorithms import SpatialPooler [as 别名]
# 或者: from nupic.bindings.algorithms.SpatialPooler import compute [as 别名]
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)
#.........这里部分代码省略.........
示例4: Example
# 需要导入模块: from nupic.bindings.algorithms import SpatialPooler [as 别名]
# 或者: from nupic.bindings.algorithms.SpatialPooler import compute [as 别名]
class Example(object):
"""A class to hold our code.
TODO: Get rid of this class, it just makes it more difficult to read the
code.
"""
def __init__(self, inputDimensions, columnDimensions):
"""
Parameters:
----------
_inputDimensions: The size of the input. (m,n) will give a size m x n
_columnDimensions: The size of the 2 dimensional array of columns
"""
self.inputDimensions = inputDimensions
self.columnDimensions = columnDimensions
self.inputSize = np.array(inputDimensions).prod()
self.columnNumber = np.array(columnDimensions).prod()
self.inputArray = np.zeros(self.inputSize)
self.activeArray = np.zeros(self.columnNumber)
self.sp = SP(self.inputDimensions,
self.columnDimensions,
potentialRadius = self.inputSize,
numActiveColumnsPerInhArea = int(0.02*self.columnNumber),
globalInhibition = True,
synPermActiveInc = 0.01)
def createInput(self):
"""create a random input vector"""
print "-" * 70 + "Creating a random input vector" + "-" * 70
#clear the inputArray to zero before creating a new input vector
self.inputArray[0:] = 0
for i in range(self.inputSize):
#randrange returns 0 or 1
self.inputArray[i] = randrange(2)
def run(self):
"""Run the spatial pooler with the input vector"""
print "-" * 80 + "Computing the SDR" + "-" * 80
#activeArray[column]=1 if column is active after spatial pooling
self.sp.compute(self.inputArray, True, self.activeArray)
print self.activeArray.nonzero()
def addNoise(self, noiseLevel):
"""Flip the value of 10% of input bits (add noise)
:param noiseLevel: The percentage of total input bits that should be flipped
"""
for _ in range(int(noiseLevel * self.inputSize)):
# 0.1*self.inputSize represents 10% of the total input bits
# random.random() returns a float between 0 and 1
randomPosition = int(random() * self.inputSize)
# Flipping the bit at the randomly picked position
if self.inputArray[randomPosition] == 1:
self.inputArray[randomPosition] = 0
else:
self.inputArray[randomPosition] = 1
示例5: frequency
# 需要导入模块: from nupic.bindings.algorithms import SpatialPooler [as 别名]
# 或者: from nupic.bindings.algorithms.SpatialPooler import compute [as 别名]
def frequency(self,
n=15,
w=7,
columnDimensions = 2048,
numActiveColumnsPerInhArea = 40,
stimulusThreshold = 0,
spSeed = 1,
spVerbosity = 0,
numColors = 2,
seed=42,
minVal=0,
maxVal=10,
encoder = 'category',
forced=True):
""" Helper function that tests whether the SP predicts the most
frequent record """
print "\nRunning SP overlap test..."
print encoder, 'encoder,', 'Random seed:', seed, 'and', numColors, 'colors'
#Setting up SP and creating training patterns
# Instantiate Spatial Pooler
spImpl = SpatialPooler(
columnDimensions=(columnDimensions, 1),
inputDimensions=(1, n),
potentialRadius=n/2,
numActiveColumnsPerInhArea=numActiveColumnsPerInhArea,
spVerbosity=spVerbosity,
stimulusThreshold=stimulusThreshold,
potentialPct=0.5,
seed=spSeed,
)
rnd.seed(seed)
numpy.random.seed(seed)
colors = []
coincs = []
reUsedCoincs = []
spOutput = []
patterns = set([])
# Setting up the encodings
if encoder=='scalar':
enc = scalar.ScalarEncoder(name='car', w=w, n=n, minval=minVal,
maxval=maxVal, periodic=False, forced=True) # forced: it's strongly recommended to use w>=21, in the example we force skip the check for readibility
for y in xrange(numColors):
temp = enc.encode(rnd.random()*maxVal)
colors.append(numpy.array(temp, dtype=realDType))
else:
for y in xrange(numColors):
sdr = numpy.zeros(n, dtype=realDType)
# Randomly setting w out of n bits to 1
sdr[rnd.sample(xrange(n), w)] = 1
colors.append(sdr)
# Training the sp
print 'Starting to train the sp on', numColors, 'patterns'
startTime = time.time()
for i in xrange(numColors):
# TODO: See https://github.com/numenta/nupic/issues/2072
spInput = colors[i]
onCells = numpy.zeros(columnDimensions)
spImpl.compute(spInput, True, onCells)
spOutput.append(onCells.tolist())
activeCoincIndices = set(onCells.nonzero()[0])
# Checking if any of the active cells have been previously active
reUsed = activeCoincIndices.intersection(patterns)
if len(reUsed) == 0:
# The set of all coincidences that have won at least once
coincs.append((i, activeCoincIndices, colors[i]))
else:
reUsedCoincs.append((i, activeCoincIndices, colors[i]))
# Adding the active cells to the set of coincs that have been active at
# least once
patterns.update(activeCoincIndices)
if (i + 1) % 100 == 0:
print 'Record number:', i + 1
print "Elapsed time: %.2f seconds" % (time.time() - startTime)
print len(reUsedCoincs), "re-used coinc(s),"
# Check if results match expectations
summ = []
for z in coincs:
summ.append(sum([len(z[1].intersection(y[1])) for y in reUsedCoincs]))
zeros = len([x for x in summ if x==0])
factor = max(summ)*len(summ)/sum(summ)
if len(reUsed) < 10:
self.assertLess(factor, 41,
"\nComputed factor: %d\nExpected Less than %d" % (
factor, 41))
self.assertLess(zeros, 0.99*len(summ),
"\nComputed zeros: %d\nExpected Less than %d" % (
zeros, 0.99*len(summ)))
#.........这里部分代码省略.........
示例6: testComputeParametersValidation
# 需要导入模块: from nupic.bindings.algorithms import SpatialPooler [as 别名]
# 或者: from nupic.bindings.algorithms.SpatialPooler import compute [as 别名]
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)
示例7: SpatialPoolerAPITest
# 需要导入模块: from nupic.bindings.algorithms import SpatialPooler [as 别名]
# 或者: from nupic.bindings.algorithms.SpatialPooler import compute [as 别名]
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)
#.........这里部分代码省略.........
示例8: DistalTimestamps1CellPerColumnDetector
# 需要导入模块: from nupic.bindings.algorithms import SpatialPooler [as 别名]
# 或者: from nupic.bindings.algorithms.SpatialPooler import compute [as 别名]
#.........这里部分代码省略.........
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]
self.sp.compute(self.encodedValue, True, self.spOutput)
activeColumns = self.spOutput.nonzero()[0]
activeColumnsSet = set(activeColumns.tolist())
prevPredictedColumns = set(self.etm.columnForCell(cell)
for cell in self.etm.getPredictiveCells())
rawScore = (len(activeColumnsSet - prevPredictedColumns) /
float(len(activeColumns)))
anomalyScore = self.anomalyLikelihood.anomalyProbability(
inputData["value"], rawScore, inputData["timestamp"])
logScore = self.anomalyLikelihood.computeLogLikelihood(anomalyScore)
self.etm.compute(activeColumns,
activeCellsExternalBasal=self.activeExternalCells,
reinforceCandidatesExternalBasal=self.prevActiveExternalCells,
growthCandidatesExternalBasal=self.prevActiveExternalCells)
return (logScore, rawScore)
示例9: SpatialPoolerAgent
# 需要导入模块: from nupic.bindings.algorithms import SpatialPooler [as 别名]
# 或者: from nupic.bindings.algorithms.SpatialPooler import compute [as 别名]
class SpatialPoolerAgent(Agent):
""" agent that uses CAM (content-addresable memory;
uses SpatialPooler to make abstractions and generalizations of inputs to learn actions.
Can be trained in both supervised and unsupervised ways.
Uses utility encoder with feedback = 1, to remember 1 step -> start={stateA, actionA} , score(start)==score after applying actionA"""
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
def testSP(self):
dataSize = 5
totalPatterns = 5
patterns=[]
for i in xrange(0,totalPatterns):
patterns.append(numpy.random.randint(0,2,dataSize).tolist()) # generate input patterns
# SP learn patterns
for _ in xrange(0,10): #learn-repeate
for pattern in patterns:
ret = numpy.zeros(1024)
print "input=", pattern
enc = self.enc.encode(pattern)
print "encoded=",enc
self.sp.compute(enc,True, ret)
nz = numpy.nonzero(ret)[0].tolist()
print len(nz)
score = self.enc.getScoreIN(pattern)
buckets = self.enc.getBucketIndices({'simpleUtility' : pattern,'utility' : score})
print self.enc.getScalarNames(), buckets
print self.cls.compute(recordNum=1, patternNZ=nz, classification={'bucketIdx': buckets[0], 'actValue': score }, learn=True, infer=True)
print "Test"
for pattern in patterns:
ret = numpy.zeros(1024)
enc = self.enc.encode(pattern)
self.sp.compute(enc,False, ret)
nz = numpy.nonzero(ret)[0].tolist()
score = self.enc.getScoreIN(pattern)
buckets = self.enc.getBucketIndices({'simpleUtility' : pattern,'utility' : score})
print self.cls.compute(recordNum=1, patternNZ=nz, classification={'bucketIdx': buckets[0], 'actValue': None }, learn=False, infer=True)