本文整理汇总了Python中nupic.encoders.date.DateEncoder类的典型用法代码示例。如果您正苦于以下问题:Python DateEncoder类的具体用法?Python DateEncoder怎么用?Python DateEncoder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DateEncoder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
def setUp(self):
# 3 bits for season, 1 bit for day of week, 1 for weekend, 5 for time of
# day
# use of forced is not recommended, used here for readability, see scalar.py
self._e = DateEncoder(season=3, dayOfWeek=1, weekend=1, timeOfDay=5)
# in the middle of fall, Thursday, not a weekend, afternoon - 4th Nov,
# 2010, 14:55
self._d = datetime.datetime(2010, 11, 4, 14, 55)
self._bits = self._e.encode(self._d)
# season is aaabbbcccddd (1 bit/month) # TODO should be <<3?
# should be 000000000111 (centered on month 11 - Nov)
seasonExpected = [0,0,0,0,0,0,0,0,0,1,1,1]
# week is MTWTFSS
# contrary to localtime documentation, Monday = 0 (for python
# datetime.datetime.timetuple()
dayOfWeekExpected = [0,0,0,1,0,0,0]
# not a weekend, so it should be "False"
weekendExpected = [1, 0]
# time of day has radius of 4 hours and w of 5 so each bit = 240/5
# min = 48min 14:55 is minute 14*60 + 55 = 895; 895/48 = bit 18.6
# should be 30 bits total (30 * 48 minutes = 24 hours)
timeOfDayExpected = (
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0])
self._expected = numpy.array(seasonExpected +
dayOfWeekExpected +
weekendExpected +
timeOfDayExpected, dtype=defaultDtype)
示例2: 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
)
示例3: testHoliday
def testHoliday(self):
'''look at holiday more carefully because of the smooth transition'''
e = DateEncoder(holiday=5)
holiday = numpy.array([0,0,0,0,0,1,1,1,1,1], dtype='uint8')
notholiday = numpy.array([1,1,1,1,1,0,0,0,0,0], dtype='uint8')
holiday2 = numpy.array([0,0,0,1,1,1,1,1,0,0], dtype='uint8')
d = datetime.datetime(2010, 12, 25, 4, 55)
self.assertTrue((e.encode(d) == holiday).all())
d = datetime.datetime(2008, 12, 27, 4, 55)
self.assertTrue((e.encode(d) == notholiday).all())
d = datetime.datetime(1999, 12, 26, 8, 00)
self.assertTrue((e.encode(d) == holiday2).all())
d = datetime.datetime(2011, 12, 24, 16, 00)
self.assertTrue((e.encode(d) == holiday2).all())
示例4: testHolidayMultiple
def testHolidayMultiple(self):
"""look at holiday more carefully because of the smooth transition"""
# use of forced is not recommended, used here for readability, see
# scalar.py
e = DateEncoder(holiday=5, forced=True, holidays=[(12, 25), (2018, 4, 1), (2017, 4, 16)])
holiday = numpy.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1], dtype="uint8")
notholiday = numpy.array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0], dtype="uint8")
d = datetime.datetime(2011, 12, 25, 4, 55)
self.assertTrue(numpy.array_equal(e.encode(d), holiday))
d = datetime.datetime(2007, 12, 2, 4, 55)
self.assertTrue(numpy.array_equal(e.encode(d), notholiday))
d = datetime.datetime(2018, 4, 1, 16, 10)
self.assertTrue(numpy.array_equal(e.encode(d), holiday))
d = datetime.datetime(2017, 4, 16, 16, 10)
self.assertTrue(numpy.array_equal(e.encode(d), holiday))
示例5: testHoliday
def testHoliday(self):
'''look at holiday more carefully because of the smooth transition'''
# use of forced is not recommended, used here for readibility, see scalar.py
e = DateEncoder(holiday=5, forced=True)
holiday = numpy.array([0,0,0,0,0,1,1,1,1,1], dtype='uint8')
notholiday = numpy.array([1,1,1,1,1,0,0,0,0,0], dtype='uint8')
holiday2 = numpy.array([0,0,0,1,1,1,1,1,0,0], dtype='uint8')
d = datetime.datetime(2010, 12, 25, 4, 55)
self.assertTrue((e.encode(d) == holiday).all())
d = datetime.datetime(2008, 12, 27, 4, 55)
self.assertTrue((e.encode(d) == notholiday).all())
d = datetime.datetime(1999, 12, 26, 8, 00)
self.assertTrue((e.encode(d) == holiday2).all())
d = datetime.datetime(2011, 12, 24, 16, 00)
self.assertTrue((e.encode(d) == holiday2).all())
示例6: testHoliday
def testHoliday(self):
"""look at holiday more carefully because of the smooth transition"""
# use of forced is not recommended, used here for readability, see
# scalar.py
e = DateEncoder(holiday=5, forced=True)
holiday = numpy.array([0,0,0,0,0,1,1,1,1,1], dtype="uint8")
notholiday = numpy.array([1,1,1,1,1,0,0,0,0,0], dtype="uint8")
holiday2 = numpy.array([0,0,0,1,1,1,1,1,0,0], dtype="uint8")
d = datetime.datetime(2010, 12, 25, 4, 55)
self.assertTrue(numpy.array_equal(e.encode(d), holiday))
d = datetime.datetime(2008, 12, 27, 4, 55)
self.assertTrue(numpy.array_equal(e.encode(d), notholiday))
d = datetime.datetime(1999, 12, 26, 8, 00)
self.assertTrue(numpy.array_equal(e.encode(d), holiday2))
d = datetime.datetime(2011, 12, 24, 16, 00)
self.assertTrue(numpy.array_equal(e.encode(d), holiday2))
示例7: testWeekend
def testWeekend(self):
"""Test weekend encoder"""
# use of forced is not recommended, used here for readability, see scalar.py
e = DateEncoder(customDays=(21, ["sat", "sun", "fri"]), forced=True)
mon = DateEncoder(customDays=(21, "Monday"), forced=True)
e2 = DateEncoder(weekend=(21, 1), forced=True)
d = datetime.datetime(1988, 5, 29, 20, 00)
self.assertTrue(numpy.array_equal(e.encode(d), e2.encode(d)))
for _ in range(300):
d = d+datetime.timedelta(days=1)
self.assertTrue(numpy.array_equal(e.encode(d), e2.encode(d)))
#Make sure
if mon.decode(mon.encode(d))[0]["Monday"][0][0][0] == 1.0:
self.assertEqual(d.weekday(), 0)
else:
self.assertNotEqual(d.weekday(), 0)
示例8: __init__
def __init__(self):
self.lat = ScalarEncoder(name='latitude', w=3, n=100, minval=-90, maxval=90,
periodic=False)
self.long= ScalarEncoder(name='longitude', w=3, n=100, minval=-180, maxval=180,
periodic=True)
self.timeenc= DateEncoder(season=0, dayOfWeek=1, weekend=3, timeOfDay=5)
self.likes = ScalarEncoder(name='likes', w=3, n=50, minval=0, maxval=100000,
periodic=False)
self.people = ScalarEncoder(name='numpeople', w=3, n=20, minval=0, maxval=100,
periodic=False)
self.categories = SDRCategoryEncoder(n=87, w=3, categoryList = None,
name="cats", verbosity=0)
self.run()
示例9: testReadWrite
def testReadWrite(self):
originalTS = datetime.datetime(1997, 8, 29, 2, 14)
originalValue = self._e.encode(originalTS)
proto1 = DateEncoderProto.new_message()
self._e.write(proto1)
# Write the proto to a temp file and read it back into a new proto
with tempfile.TemporaryFile() as f:
proto1.write(f)
f.seek(0)
proto2 = DateEncoderProto.read(f)
encoder = DateEncoder.read(proto2)
self.assertIsInstance(encoder, DateEncoder)
self.assertEqual(encoder.width, self._e.width)
self.assertEqual(encoder.weekendOffset, self._e.weekendOffset)
self.assertEqual(encoder.timeOfDayOffset, self._e.timeOfDayOffset)
self.assertEqual(encoder.seasonOffset, self._e.seasonOffset)
self.assertEqual(encoder.dayOfWeekOffset, self._e.dayOfWeekOffset)
self.assertIsInstance(encoder.customDaysEncoder,
self._e.customDaysEncoder.__class__)
self.assertIsInstance(encoder.dayOfWeekEncoder,
self._e.dayOfWeekEncoder.__class__)
self.assertIsInstance(encoder.seasonEncoder,
self._e.seasonEncoder.__class__)
self.assertIsInstance(encoder.timeOfDayEncoder,
self._e.timeOfDayEncoder.__class__)
self.assertIsInstance(encoder.weekendEncoder,
self._e.weekendEncoder.__class__)
self.assertTrue(numpy.array_equal(self._bits, encoder.encode(self._d)))
self.assertTrue(numpy.array_equal(encoder.encode(originalTS),
originalValue))
self.assertEqual(self._e.decode(encoder.encode(self._d)),
encoder.decode(self._e.encode(self._d)))
示例10: runHotgym
def runHotgym(numRecords):
with open(_PARAMS_PATH, "r") as f:
modelParams = yaml.safe_load(f)["modelParams"]
enParams = modelParams["sensorParams"]["encoders"]
spParams = modelParams["spParams"]
tmParams = modelParams["tmParams"]
timeOfDayEncoder = DateEncoder(
timeOfDay=enParams["timestamp_timeOfDay"]["timeOfDay"])
weekendEncoder = DateEncoder(
weekend=enParams["timestamp_weekend"]["weekend"])
scalarEncoder = RandomDistributedScalarEncoder(
enParams["consumption"]["resolution"])
encodingWidth = (timeOfDayEncoder.getWidth()
+ weekendEncoder.getWidth()
+ scalarEncoder.getWidth())
sp = SpatialPooler(
# How large the input encoding will be.
inputDimensions=(encodingWidth),
# How many mini-columns will be in the Spatial Pooler.
columnDimensions=(spParams["columnCount"]),
# What percent of the columns"s receptive field is available for potential
# synapses?
potentialPct=spParams["potentialPct"],
# This means that the input space has no topology.
globalInhibition=spParams["globalInhibition"],
localAreaDensity=spParams["localAreaDensity"],
# Roughly 2%, giving that there is only one inhibition area because we have
# turned on globalInhibition (40 / 2048 = 0.0195)
numActiveColumnsPerInhArea=spParams["numActiveColumnsPerInhArea"],
# How quickly synapses grow and degrade.
synPermInactiveDec=spParams["synPermInactiveDec"],
synPermActiveInc=spParams["synPermActiveInc"],
synPermConnected=spParams["synPermConnected"],
# boostStrength controls the strength of boosting. Boosting encourages
# efficient usage of SP columns.
boostStrength=spParams["boostStrength"],
# Random number generator seed.
seed=spParams["seed"],
# TODO: is this useful?
# Determines if inputs at the beginning and end of an input dimension should
# be considered neighbors when mapping columns to inputs.
wrapAround=False
)
tm = TemporalMemory(
# Must be the same dimensions as the SP
columnDimensions=(tmParams["columnCount"],),
# How many cells in each mini-column.
cellsPerColumn=tmParams["cellsPerColumn"],
# A segment is active if it has >= activationThreshold connected synapses
# that are active due to infActiveState
activationThreshold=tmParams["activationThreshold"],
initialPermanence=tmParams["initialPerm"],
# TODO: This comes from the SP params, is this normal
connectedPermanence=spParams["synPermConnected"],
# Minimum number of active synapses for a segment to be considered during
# search for the best-matching segments.
minThreshold=tmParams["minThreshold"],
# The max number of synapses added to a segment during learning
maxNewSynapseCount=tmParams["newSynapseCount"],
permanenceIncrement=tmParams["permanenceInc"],
permanenceDecrement=tmParams["permanenceDec"],
predictedSegmentDecrement=0.0,
maxSegmentsPerCell=tmParams["maxSegmentsPerCell"],
maxSynapsesPerSegment=tmParams["maxSynapsesPerSegment"],
seed=tmParams["seed"]
)
classifier = SDRClassifierFactory.create()
results = []
with open(_INPUT_FILE_PATH, "r") as fin:
reader = csv.reader(fin)
headers = reader.next()
reader.next()
reader.next()
for count, record in enumerate(reader):
if count >= numRecords: break
# Convert data string into Python date object.
dateString = datetime.datetime.strptime(record[0], "%m/%d/%y %H:%M")
# Convert data value string into float.
consumption = float(record[1])
# To encode, we need to provide zero-filled numpy arrays for the encoders
# to populate.
timeOfDayBits = numpy.zeros(timeOfDayEncoder.getWidth())
weekendBits = numpy.zeros(weekendEncoder.getWidth())
consumptionBits = numpy.zeros(scalarEncoder.getWidth())
# Now we call the encoders create bit representations for each value.
timeOfDayEncoder.encodeIntoArray(dateString, timeOfDayBits)
weekendEncoder.encodeIntoArray(dateString, weekendBits)
scalarEncoder.encodeIntoArray(consumption, consumptionBits)
# Concatenate all these encodings into one large encoding for Spatial
#.........这里部分代码省略.........
示例11: 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)
#.........这里部分代码省略.........
示例12: FourSquareAnomalyDetector
class FourSquareAnomalyDetector():
def __init__(self):
self.lat = ScalarEncoder(name='latitude', w=3, n=100, minval=-90, maxval=90,
periodic=False)
self.long= ScalarEncoder(name='longitude', w=3, n=100, minval=-180, maxval=180,
periodic=True)
self.timeenc= DateEncoder(season=0, dayOfWeek=1, weekend=3, timeOfDay=5)
self.likes = ScalarEncoder(name='likes', w=3, n=50, minval=0, maxval=100000,
periodic=False)
self.people = ScalarEncoder(name='numpeople', w=3, n=20, minval=0, maxval=100,
periodic=False)
self.categories = SDRCategoryEncoder(n=87, w=3, categoryList = None,
name="cats", verbosity=0)
self.run()
def run(self):
check1=Checkin(10,100,datetime.datetime.utcnow(),12,5,"cafe")
check2=Checkin(10,100,datetime.datetime.utcnow(),12,5,"cafe")
check3=Checkin(10,100,datetime.datetime.utcnow(),12,5,"cafe")
check4=Checkin(10,100,datetime.datetime.utcnow(),12,5,"cafe")
check5=Checkin(10,100,datetime.datetime.utcnow(),12,5,"cafe")
check6=Checkin(10,100,datetime.datetime.utcnow(),12,5,"cafe")
check7=Checkin(10,100,datetime.datetime.utcnow(),12,5,"cafe")
check8=Checkin(10,100,datetime.datetime.utcnow(),12,5,"cafe")
list_of_unencoded_checkins=[check1,check2,check3,check4,check5,check6,check7,check8]
list_of_encoded_checkins=[]
for check in list_of_unencoded_checkins:
print check
list_of_encoded_checkins.append(self.encode(check))
print self.LastAnomalyScore(list_of_encoded_checkins)
def createModel(self):
return ModelFactory.create(model_params.MODEL_PARAMS)
def encode(self, checkin):
print checkin
latenc=self.lat.encode(checkin.latitude)
longenc=self.long.encode(checkin.longitude)
timenc=self.timeenc.encode(checkin.time)
likeenc=self.likes.encode(checkin.likes)
peoplenc=self.people.encode(checkin.people)
for cat in checkin.categories:
try:
catenc=numpy.logical_or(catenc,self.categories.encode(cat))
except:
catenc=self.categories.encode(cat)
checkinsdr=numpy.concatenate((latenc,longenc,timenc,likeenc,peoplenc,catenc))
print checkinsdr
print type(checkinsdr)
return checkinsdr
def LastAnomalyScore(self, checkin_list):
model = self.createModel()
model.enableInference({'predictedField': 'checkin'})
last_anomaly = 0
for i, record in enumerate(checkin_list, start=1):
modelInput = {"checkin": record}
result = model.run(modelInput)
anomalyScore = result.inferences['anomalyScore']
last_anomaly = anomalyScore
return last_anomaly
示例13: testWeekend
def testWeekend(self):
'''Test weekend encoder'''
e = DateEncoder(customDays = (21,["sat","sun","fri"]))
mon = DateEncoder(customDays = (21,"Monday"))
e2 = DateEncoder(weekend=(21,1))
d = datetime.datetime(1988,5,29,20,00)
self.assertTrue((e.encode(d) == e2.encode(d)).all())
for _ in range(300):
d = d+datetime.timedelta(days=1)
self.assertTrue((e.encode(d) == e2.encode(d)).all())
print mon.decode(mon.encode(d))
#Make sure
if mon.decode(mon.encode(d))[0]["Monday"][0][0][0]==1.0:
self.assertEqual(d.weekday(), 0)
else:
self.assertFalse(d.weekday()==0)
示例14: DateEncoderTest
class DateEncoderTest(unittest.TestCase):
"""Unit tests for DateEncoder class"""
def setUp(self):
# 3 bits for season, 1 bit for day of week, 1 for weekend, 5 for time of
# day
# use of forced is not recommended, used here for readability, see scalar.py
self._e = DateEncoder(season=3, dayOfWeek=1, weekend=1, timeOfDay=5)
# in the middle of fall, Thursday, not a weekend, afternoon - 4th Nov,
# 2010, 14:55
self._d = datetime.datetime(2010, 11, 4, 14, 55)
self._bits = self._e.encode(self._d)
# season is aaabbbcccddd (1 bit/month) # TODO should be <<3?
# should be 000000000111 (centered on month 11 - Nov)
seasonExpected = [0,0,0,0,0,0,0,0,0,1,1,1]
# week is MTWTFSS
# contrary to localtime documentation, Monday = 0 (for python
# datetime.datetime.timetuple()
dayOfWeekExpected = [0,0,0,1,0,0,0]
# not a weekend, so it should be "False"
weekendExpected = [1, 0]
# time of day has radius of 4 hours and w of 5 so each bit = 240/5
# min = 48min 14:55 is minute 14*60 + 55 = 895; 895/48 = bit 18.6
# should be 30 bits total (30 * 48 minutes = 24 hours)
timeOfDayExpected = (
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0])
self._expected = numpy.array(seasonExpected +
dayOfWeekExpected +
weekendExpected +
timeOfDayExpected, dtype=defaultDtype)
def testDateEncoder(self):
"""creating date encoder instance"""
self.assertSequenceEqual(
self._e.getDescription(),
[("season", 0),
("day of week", 12),
("weekend", 19), ("time of day", 21)])
self.assertTrue(numpy.array_equal(self._expected, self._bits))
def testMissingValues(self):
"""missing values"""
mvOutput = self._e.encode(SENTINEL_VALUE_FOR_MISSING_DATA)
self.assertEqual(sum(mvOutput), 0)
def testDecoding(self):
"""decoding date"""
decoded = self._e.decode(self._bits)
(fieldsDict, _) = decoded
self.assertEqual(len(fieldsDict), 4)
(ranges, _) = fieldsDict['season']
self.assertEqual(len(ranges), 1)
self.assertSequenceEqual(ranges[0], [305, 305])
(ranges, _) = fieldsDict['time of day']
self.assertEqual(len(ranges), 1)
self.assertSequenceEqual(ranges[0], [14.4, 14.4])
(ranges, _) = fieldsDict['day of week']
self.assertEqual(len(ranges), 1)
self.assertSequenceEqual(ranges[0], [3, 3])
(ranges, _) = fieldsDict['weekend']
self.assertEqual(len(ranges), 1)
self.assertSequenceEqual(ranges[0], [0, 0])
def testTopDownCompute(self):
"""Check topDownCompute"""
topDown = self._e.topDownCompute(self._bits)
topDownValues = numpy.array([elem.value for elem in topDown])
errs = topDownValues - numpy.array([320.25, 3.5, .167, 14.8])
self.assertAlmostEqual(errs.max(), 0, 4)
def testBucketIndexSupport(self):
"""Check bucket index support"""
bucketIndices = self._e.getBucketIndices(self._d)
topDown = self._e.getBucketInfo(bucketIndices)
topDownValues = numpy.array([elem.value for elem in topDown])
errs = topDownValues - numpy.array([320.25, 3.5, .167, 14.8])
self.assertAlmostEqual(errs.max(), 0, 4)
encodings = []
for x in topDown:
encodings.extend(x.encoding)
self.assertTrue(numpy.array_equal(encodings, self._expected))
def testHoliday(self):
"""look at holiday more carefully because of the smooth transition"""
# use of forced is not recommended, used here for readability, see
#.........这里部分代码省略.........
示例15: 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]
#.........这里部分代码省略.........