def testBadDataset(self): filename = _getTempFileName() print 'Creating tempfile:', filename # Write bad dataset with records going backwards in time fields = [('timestamp', 'datetime', 'T')] o = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ( [datetime(day=3, month=3, year=2010)], [datetime(day=2, month=3, year=2010)]) o.appendRecord(records[0]) o.appendRecord(records[1]) o.close() # Write bad dataset with broken sequences fields = [('sid', 'int', 'S')] o = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ([1], [2], [1]) o.appendRecord(records[0]) o.appendRecord(records[1]) self.assertRaises(Exception, o.appendRecord, (records[2],)) o.close()
def testBadDataset(self): filename = _getTempFileName() print 'Creating tempfile:', filename # Write bad dataset with records going backwards in time fields = [ FieldMetaInfo('timestamp', FieldMetaType.datetime, FieldMetaSpecial.timestamp) ] o = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ([datetime(day=3, month=3, year=2010)], [datetime(day=2, month=3, year=2010)]) o.appendRecord(records[0]) o.appendRecord(records[1]) o.close() # Write bad dataset with broken sequences fields = [ FieldMetaInfo('sid', FieldMetaType.integer, FieldMetaSpecial.sequence) ] o = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ([1], [2], [1]) o.appendRecord(records[0]) o.appendRecord(records[1]) self.assertRaises(Exception, o.appendRecord, (records[2], )) o.close()
def _generateScalar(filename="simple.csv", numSequences=2, elementsPerSeq=1, numRepeats=10, stepSize=0.1, includeRandom=False): """ Generate a simple dataset. This contains a bunch of non-overlapping sequences of scalar values. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output stepSize: how far apart each scalar is includeRandom: if true, include another random field """ # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print "Creating %s..." % (pathname) fields = [('classification', 'float', ''), ('field1', 'float', '')] if includeRandom: fields += [('randomData', 'float', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences sequences = [] for i in range(numSequences): seq = [x for x in range(i * elementsPerSeq, (i + 1) * elementsPerSeq)] sequences.append(seq) random.seed(42) # Write out the sequences in random order seqIdxs = [] for i in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: if includeRandom: outFile.appendRecord([seqIdx, x * stepSize, random.random()]) else: outFile.appendRecord([seqIdx, x * stepSize]) outFile.close()
def _generateScalar( filename="simple.csv", numSequences=2, elementsPerSeq=1, numRepeats=10, stepSize=0.1, includeRandom=False ): """ Generate a simple dataset. This contains a bunch of non-overlapping sequences of scalar values. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output stepSize: how far apart each scalar is includeRandom: if true, include another random field """ # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, "datasets", filename) print "Creating %s..." % (pathname) fields = [("classification", "float", ""), ("field1", "float", "")] if includeRandom: fields += [("randomData", "float", "")] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences sequences = [] for i in range(numSequences): seq = [x for x in range(i * elementsPerSeq, (i + 1) * elementsPerSeq)] sequences.append(seq) random.seed(42) # Write out the sequences in random order seqIdxs = [] for i in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: if includeRandom: outFile.appendRecord([seqIdx, x * stepSize, random.random()]) else: outFile.appendRecord([seqIdx, x * stepSize]) outFile.close()
def _generateScalar(filename="simple.csv", numSequences=2, elementsPerSeq=1, numRepeats=10, stepSize=0.1, resets=False): """ Generate a simple dataset. This contains a bunch of non-overlapping sequences of scalar values. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output stepSize: how far apart each scalar is resets: if True, turn on reset at start of each sequence """ # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print("Creating %s..." % (pathname)) fields = [('reset', 'int', 'R'), ('category', 'int', 'C'), ('field1', 'float', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences sequences = [] for i in range(numSequences): seq = [x for x in range(i * elementsPerSeq, (i + 1) * elementsPerSeq)] sequences.append(seq) # Write out the sequences in random order seqIdxs = [] for i in range(numRepeats): seqIdxs += list(range(numSequences)) random.shuffle(seqIdxs) for seqIdx in seqIdxs: reset = int(resets) seq = sequences[seqIdx] for x in seq: outFile.appendRecord([reset, str(seqIdx), x * stepSize]) reset = 0 outFile.close()
def _generateScalar(filename="simple.csv", numSequences=2, elementsPerSeq=1, numRepeats=10, stepSize=0.1, resets=False): """ Generate a simple dataset. This contains a bunch of non-overlapping sequences of scalar values. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output stepSize: how far apart each scalar is resets: if True, turn on reset at start of each sequence """ # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print "Creating %s..." % (pathname) fields = [('reset', 'int', 'R'), ('category', 'int', 'C'), ('field1', 'float', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences sequences = [] for i in range(numSequences): seq = [x for x in range(i*elementsPerSeq, (i+1)*elementsPerSeq)] sequences.append(seq) # Write out the sequences in random order seqIdxs = [] for i in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) for seqIdx in seqIdxs: reset = int(resets) seq = sequences[seqIdx] for x in seq: outFile.appendRecord([reset, str(seqIdx), x*stepSize]) reset = 0 outFile.close()
def _generateCategory(filename="simple.csv", numSequences=2, elementsPerSeq=1, numRepeats=10): """ Generate a simple dataset. This contains a bunch of non-overlapping sequences. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output """ # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print "Creating %s..." % (pathname) fields = [('classification', 'string', ''), ('field1', 'string', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences sequences = [] for i in range(numSequences): seq = [x for x in range(i * elementsPerSeq, (i + 1) * elementsPerSeq)] sequences.append(seq) # Write out the sequences in random order seqIdxs = [] for i in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: outFile.appendRecord([str(seqIdx), str(x)]) outFile.close()
def _generateCategory(filename="simple.csv", numSequences=2, elementsPerSeq=1, numRepeats=10): """ Generate a simple dataset. This contains a bunch of non-overlapping sequences. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output """ # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print "Creating %s..." % (pathname) fields = [('classification', 'string', ''), ('field1', 'string', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences sequences = [] for i in range(numSequences): seq = [x for x in range(i*elementsPerSeq, (i+1)*elementsPerSeq)] sequences.append(seq) # Write out the sequences in random order seqIdxs = [] for i in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: outFile.appendRecord([str(seqIdx), str(x)]) outFile.close()
def testMissingValues(self): print "Beginning Missing Data test..." filename = _getTempFileName() # Some values missing of each type # read dataset from disk, retrieve values # string should return empty string, numeric types sentinelValue print 'Creating tempfile:', filename # write dataset to disk with float, int, and string fields fields = [ FieldMetaInfo('timestamp', FieldMetaType.datetime, FieldMetaSpecial.timestamp), FieldMetaInfo('name', FieldMetaType.string, FieldMetaSpecial.none), FieldMetaInfo('integer', FieldMetaType.integer, FieldMetaSpecial.none), FieldMetaInfo('real', FieldMetaType.float, FieldMetaSpecial.none) ] s = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ([datetime(day=1, month=3, year=2010), 'rec_1', 5, 6.5], [ datetime(day=2, month=3, year=2010), '', 8, 7.5 ], [datetime(day=3, month=3, year=2010), 'rec_3', '', 8.5], [ datetime(day=4, month=3, year=2010), 'rec_4', 12, '' ], [datetime(day=5, month=3, year=2010), 'rec_5', -87657496599, 6.5], [ datetime(day=6, month=3, year=2010), 'rec_6', 12, -87657496599 ], [datetime(day=6, month=3, year=2010), str(-87657496599), 12, 6.5]) for r in records: s.appendRecord(list(r)) s.close() # Read the standard file s = FileRecordStream(streamID=filename, write=False) fieldsRead = s.getFields() self.assertEqual(fields, fieldsRead) recordsRead = [] while True: r = s.getNextRecord() if r is None: break print 'Reading record ...' print r recordsRead.append(r) # sort the records by date, so we know for sure which is which sorted(recordsRead, key=lambda rec: rec[0]) # empty string self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[1][1]) # missing int self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[2][2]) # missing float self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[3][3]) # sentinel value in input handled correctly for int field self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[4][2]) # sentinel value in input handled correctly for float field self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[5][3]) # sentinel value in input handled correctly for string field # this should leave the string as-is, since a missing string # is encoded not with a sentinel value but with an empty string self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[6][1])
def testSimpleMulticlassNetwork(self): # Setup data record stream of fake data (with three categories) filename = _getTempFileName() fields = [("timestamp", "datetime", "T"), ("value", "float", ""), ("reset", "int", "R"), ("sid", "int", "S"), ("categories", "list", "C")] records = ( [datetime(day=1, month=3, year=2010), 0.0, 1, 0, ""], [datetime(day=2, month=3, year=2010), 1.0, 0, 0, "1 2"], [datetime(day=3, month=3, year=2010), 1.0, 0, 0, "1 2"], [datetime(day=4, month=3, year=2010), 2.0, 0, 0, "0"], [datetime(day=5, month=3, year=2010), 3.0, 0, 0, "1 2"], [datetime(day=6, month=3, year=2010), 5.0, 0, 0, "1 2"], [datetime(day=7, month=3, year=2010), 8.0, 0, 0, "0"], [datetime(day=8, month=3, year=2010), 13.0, 0, 0, "1 2"]) dataSource = FileRecordStream(streamID=filename, write=True, fields=fields) for r in records: dataSource.appendRecord(list(r)) # Create the network and get region instances. net = Network() net.addRegion("sensor", "py.RecordSensor", "{'numCategories': 3}") net.addRegion("classifier","py.KNNClassifierRegion", "{'k': 2,'distThreshold': 0,'maxCategoryCount': 3}") net.link("sensor", "classifier", "UniformLink", "", srcOutput = "dataOut", destInput = "bottomUpIn") net.link("sensor", "classifier", "UniformLink", "", srcOutput = "categoryOut", destInput = "categoryIn") sensor = net.regions["sensor"] classifier = net.regions["classifier"] # Setup sensor region encoder and data stream. dataSource.close() dataSource = FileRecordStream(filename) sensorRegion = sensor.getSelf() sensorRegion.encoder = MultiEncoder() sensorRegion.encoder.addEncoder( "value", ScalarEncoder(21, 0.0, 13.0, n=256, name="value")) sensorRegion.dataSource = dataSource # Get ready to run. net.initialize() # Train the network (by default learning is ON in the classifier, but assert # anyway) and then turn off learning and turn on inference mode. self.assertEqual(classifier.getParameter("learningMode"), 1) net.run(8) classifier.setParameter("inferenceMode", 1) classifier.setParameter("learningMode", 0) # Assert learning is OFF and that the classifier learned the dataset. self.assertEqual(classifier.getParameter("learningMode"), 0, "Learning mode is not turned off.") self.assertEqual(classifier.getParameter("inferenceMode"), 1, "Inference mode is not turned on.") self.assertEqual(classifier.getParameter("categoryCount"), 3, "The classifier should count three total categories.") # classififer learns 12 patterns b/c there are 12 categories amongst the # records: self.assertEqual(classifier.getParameter("patternCount"), 12, "The classifier should've learned 12 samples in total.") # Test the network on the same data as it trained on; should classify with # 100% accuracy. expectedCats = ([0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.5, 0.0], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.5, 0.0], [0.0, 0.5, 0.5]) dataSource.rewind() for i in xrange(8): net.run(1) inferredCats = classifier.getOutputData("categoriesOut") self.assertSequenceEqual(expectedCats[i], inferredCats.tolist(), "Classififer did not infer expected category probabilites for record " "number {}.".format(i)) # Close data stream, delete file. dataSource.close() os.remove(filename)
class _BasicPredictionWriter(PredictionWriterIface): """ This class defines the basic (file-based) implementation of PredictionWriterIface, whose instances are returned by BasicPredictionWriterFactory """ def __init__(self, experimentDir, label, inferenceType, fields, metricNames=None, checkpointSource=None): """ Constructor experimentDir: experiment directory path that contains description.py label: A label string to incorporate into the filename. inferenceElements: inferenceType: An constant from opfutils.InferenceType for the requested prediction writer fields: a non-empty sequence of nupic.data.fieldmeta.FieldMetaInfo representing fields that will be emitted to this prediction writer metricNames: OPTIONAL - A list of metric names that well be emiited by this prediction writer checkpointSource: If not None, a File-like object containing the previously-checkpointed predictions for setting the initial contents of this PredictionOutputStream. Will be copied before returning, if needed. """ #assert len(fields) > 0 self.__experimentDir = experimentDir # opfutils.InferenceType kind value self.__inferenceType = inferenceType # A tuple of nupic.data.fieldmeta.FieldMetaInfo self.__inputFieldsMeta = tuple(copy.deepcopy(fields)) self.__numInputFields = len(self.__inputFieldsMeta) self.__label = label if metricNames is not None: metricNames.sort() self.__metricNames = metricNames # Define our output field meta info self.__outputFieldsMeta = [] # The list of inputs that we include in the prediction output self._rawInputNames = [] # Output dataset self.__datasetPath = None self.__dataset = None # Save checkpoint data until we're ready to create the output dataset self.__checkpointCache = None if checkpointSource is not None: checkpointSource.seek(0) self.__checkpointCache = StringIO.StringIO() shutil.copyfileobj(checkpointSource, self.__checkpointCache) return ############################################################################ def __openDatafile(self, modelResult): """Open the data file and write the header row""" # Write reset bit resetFieldMeta = FieldMetaInfo(name="reset", type=FieldMetaType.integer, special=FieldMetaSpecial.reset) self.__outputFieldsMeta.append(resetFieldMeta) # ----------------------------------------------------------------------- # Write each of the raw inputs that go into the encoders rawInput = modelResult.rawInput rawFields = rawInput.keys() rawFields.sort() for field in rawFields: if field.startswith('_') or field == 'reset': continue value = rawInput[field] meta = FieldMetaInfo(name=field, type=FieldMetaType.string, special=FieldMetaSpecial.none) self.__outputFieldsMeta.append(meta) self._rawInputNames.append(field) # ----------------------------------------------------------------------- # Handle each of the inference elements for inferenceElement, value in modelResult.inferences.iteritems(): inferenceLabel = InferenceElement.getLabel(inferenceElement) # TODO: Right now we assume list inferences are associated with # The input field metadata if type(value) in (list, tuple): # Append input and prediction field meta-info self.__outputFieldsMeta.extend( self.__getListMetaInfo(inferenceElement)) elif isinstance(value, dict): self.__outputFieldsMeta.extend( self.__getDictMetaInfo(inferenceElement, value)) else: if InferenceElement.getInputElement(inferenceElement): self.__outputFieldsMeta.append( FieldMetaInfo(name=inferenceLabel + ".actual", type=FieldMetaType.string, special='')) self.__outputFieldsMeta.append( FieldMetaInfo(name=inferenceLabel, type=FieldMetaType.string, special='')) if self.__metricNames: for metricName in self.__metricNames: metricField = FieldMetaInfo(name=metricName, type=FieldMetaType.float, special=FieldMetaSpecial.none) self.__outputFieldsMeta.append(metricField) # Create the inference directory for our experiment inferenceDir = _FileUtils.createExperimentInferenceDir( self.__experimentDir) # Consctruct the prediction dataset file path filename = (self.__label + "." + opfutils.InferenceType.getLabel(self.__inferenceType) + ".predictionLog.csv") self.__datasetPath = os.path.join(inferenceDir, filename) # Create the output dataset print "OPENING OUTPUT FOR PREDICTION WRITER AT: %r" % self.__datasetPath print "Prediction field-meta: %r" % ( [tuple(i) for i in self.__outputFieldsMeta], ) self.__dataset = FileRecordStream(streamID=self.__datasetPath, write=True, fields=self.__outputFieldsMeta) # Copy data from checkpoint cache if self.__checkpointCache is not None: self.__checkpointCache.seek(0) reader = csv.reader(self.__checkpointCache, dialect='excel') # Skip header row try: header = reader.next() except StopIteration: print "Empty record checkpoint initializer for %r" % ( self.__datasetPath, ) else: assert tuple(self.__dataset.getFieldNames()) == tuple(header), \ "dataset.getFieldNames(): %r; predictionCheckpointFieldNames: %r" % ( tuple(self.__dataset.getFieldNames()), tuple(header)) # Copy the rows from checkpoint numRowsCopied = 0 while True: try: row = reader.next() except StopIteration: break #print "DEBUG: restoring row from checkpoint: %r" % (row,) self.__dataset.appendRecord(row) numRowsCopied += 1 self.__dataset.flush() print "Restored %d rows from checkpoint for %r" % ( numRowsCopied, self.__datasetPath) # Dispose of our checkpoint cache self.__checkpointCache.close() self.__checkpointCache = None return ############################################################################ def setLoggedMetrics(self, metricNames): """ Tell the writer which metrics should be written Parameters: ----------------------------------------------------------------------- metricsNames: A list of metric lables to be written """ if metricNames is None: self.__metricNames = set([]) else: self.__metricNames = set(metricNames) ############################################################################ def close(self): """ [virtual method override] Closes the writer (e.g., close the underlying file) """ if self.__dataset: self.__dataset.close() self.__dataset = None return ############################################################################ def __getListMetaInfo(self, inferenceElement): """ Get field metadata information for inferences that are of list type TODO: Right now we assume list inferences are associated with the input field metadata """ fieldMetaInfo = [] inferenceLabel = InferenceElement.getLabel(inferenceElement) for inputFieldMeta in self.__inputFieldsMeta: if InferenceElement.getInputElement(inferenceElement): outputFieldMeta = FieldMetaInfo(name=inputFieldMeta.name + ".actual", type=inputFieldMeta.type, special=inputFieldMeta.special) predictionField = FieldMetaInfo(name=inputFieldMeta.name + "." + inferenceLabel, type=inputFieldMeta.type, special=inputFieldMeta.special) fieldMetaInfo.append(outputFieldMeta) fieldMetaInfo.append(predictionField) return fieldMetaInfo ############################################################################ def __getDictMetaInfo(self, inferenceElement, inferenceDict): """Get field metadate information for inferences that are of dict type""" fieldMetaInfo = [] inferenceLabel = InferenceElement.getLabel(inferenceElement) if InferenceElement.getInputElement(inferenceElement): fieldMetaInfo.append( FieldMetaInfo(name=inferenceLabel + ".actual", type=FieldMetaType.string, special='')) keys = sorted(inferenceDict.keys()) for key in keys: fieldMetaInfo.append( FieldMetaInfo(name=inferenceLabel + "." + str(key), type=FieldMetaType.string, special='')) return fieldMetaInfo ############################################################################ def append(self, modelResult): """ [virtual method override] Emits a single prediction as input versus predicted. modelResult: An opfutils.ModelResult object that contains the model input and output for the current timestep. """ #print "DEBUG: _BasicPredictionWriter: writing modelResult: %r" % (modelResult,) # If there are no inferences, don't write anything inferences = modelResult.inferences hasInferences = False if inferences is not None: for value in inferences.itervalues(): hasInferences = hasInferences or (value is not None) if not hasInferences: return if self.__dataset is None: self.__openDatafile(modelResult) inputData = modelResult.sensorInput sequenceReset = int(bool(inputData.sequenceReset)) outputRow = [sequenceReset] # ----------------------------------------------------------------------- # Write out the raw inputs rawInput = modelResult.rawInput for field in self._rawInputNames: outputRow.append(str(rawInput[field])) # ----------------------------------------------------------------------- # Write out the inference element info for inferenceElement, outputVal in inferences.iteritems(): inputElement = InferenceElement.getInputElement(inferenceElement) if inputElement: inputVal = getattr(inputData, inputElement) else: inputVal = None if type(outputVal) in (list, tuple): assert type(inputVal) in (list, tuple, None) for iv, ov in zip(inputVal, outputVal): # Write actual outputRow.append(str(iv)) # Write inferred outputRow.append(str(ov)) elif isinstance(outputVal, dict): if inputVal is not None: # If we have a predicted field, include only that in the actuals if modelResult.predictedFieldIdx is not None: outputRow.append( str(inputVal[modelResult.predictedFieldIdx])) else: outputRow.append(str(inputVal)) for key in sorted(outputVal.keys()): outputRow.append(str(outputVal[key])) else: if inputVal is not None: outputRow.append(str(inputVal)) outputRow.append(str(outputVal)) metrics = modelResult.metrics for metricName in self.__metricNames: outputRow.append(metrics.get(metricName, 0.0)) #print "DEBUG: _BasicPredictionWriter: writing outputRow: %r" % (outputRow,) self.__dataset.appendRecord(outputRow) self.__dataset.flush() return def checkpoint(self, checkpointSink, maxRows): """ [virtual method override] Save a checkpoint of the prediction output stream. The checkpoint comprises up to maxRows of the most recent inference records. Parameters: ---------------------------------------------------------------------- checkpointSink: A File-like object where predictions checkpoint data, if any, will be stored. maxRows: Maximum number of most recent inference rows to checkpoint. """ checkpointSink.truncate() if self.__dataset is None: if self.__checkpointCache is not None: self.__checkpointCache.seek(0) shutil.copyfileobj(self.__checkpointCache, checkpointSink) checkpointSink.flush() return else: # Nothing to checkpoint return self.__dataset.flush() totalDataRows = self.__dataset.getDataRowCount() if totalDataRows == 0: # Nothing to checkpoint return # Open reader of prediction file (suppress missingValues conversion) reader = FileRecordStream(self.__datasetPath, missingValues=[]) # Create CSV writer for writing checkpoint rows writer = csv.writer(checkpointSink) # Write the header row to checkpoint sink -- just field names writer.writerow(reader.getFieldNames()) # Determine number of rows to checkpoint numToWrite = min(maxRows, totalDataRows) # Skip initial rows to get to the rows that we actually need to checkpoint numRowsToSkip = totalDataRows - numToWrite for i in xrange(numRowsToSkip): reader.next() # Write the data rows to checkpoint sink numWritten = 0 while True: row = reader.getNextRecord() if row is None: break row = [str(element) for element in row] #print "DEBUG: _BasicPredictionWriter: checkpointing row: %r" % (row,) writer.writerow(row) numWritten += 1 assert numWritten == numToWrite, \ "numWritten (%s) != numToWrite (%s)" % (numWritten, numToWrite) checkpointSink.flush() return
def _generateFile(filename, numRecords, categoryList, initProb, firstOrderProb, secondOrderProb, seqLen, numNoise=0, resetsEvery=None): """ Generate a set of records reflecting a set of probabilities. Parameters: ---------------------------------------------------------------- filename: name of .csv file to generate numRecords: number of records to generate categoryList: list of category names initProb: Initial probability for each category. This is a vector of length len(categoryList). firstOrderProb: A dictionary of the 1st order probabilities. The key is the 1st element of the sequence, the value is the probability of each 2nd element given the first. secondOrderProb: A dictionary of the 2nd order probabilities. The key is the first 2 elements of the sequence, the value is the probability of each possible 3rd element given the first two. seqLen: Desired length of each sequence. The 1st element will be generated using the initProb, the 2nd element by the firstOrder table, and the 3rd and all successive elements by the secondOrder table. None means infinite length. numNoise: Number of noise elements to place between each sequence. The noise elements are evenly distributed from all categories. resetsEvery: If not None, generate a reset every N records Here is an example of some parameters: categoryList: ['cat1', 'cat2', 'cat3'] initProb: [0.7, 0.2, 0.1] firstOrderProb: {'[0]': [0.3, 0.3, 0.4], '[1]': [0.3, 0.3, 0.4], '[2]': [0.3, 0.3, 0.4]} secondOrderProb: {'[0,0]': [0.3, 0.3, 0.4], '[0,1]': [0.3, 0.3, 0.4], '[0,2]': [0.3, 0.3, 0.4], '[1,0]': [0.3, 0.3, 0.4], '[1,1]': [0.3, 0.3, 0.4], '[1,2]': [0.3, 0.3, 0.4], '[2,0]': [0.3, 0.3, 0.4], '[2,1]': [0.3, 0.3, 0.4], '[2,2]': [0.3, 0.3, 0.4]} """ # Create the file print "Creating %s..." % (filename) fields = [('reset', 'int', 'R'), ('name', 'string', '')] outFile = FileRecordStream(filename, write=True, fields=fields) # -------------------------------------------------------------------- # Convert the probabilitie tables into cumulative probabilities initCumProb = initProb.cumsum() firstOrderCumProb = dict() for (key,value) in firstOrderProb.iteritems(): firstOrderCumProb[key] = value.cumsum() secondOrderCumProb = dict() for (key,value) in secondOrderProb.iteritems(): secondOrderCumProb[key] = value.cumsum() # -------------------------------------------------------------------- # Write out the sequences elementsInSeq = [] numElementsSinceReset = 0 maxCatIdx = len(categoryList) - 1 for i in xrange(numRecords): # Generate a reset? if numElementsSinceReset == 0: reset = 1 else: reset = 0 # Pick the next element, based on how are we are into the 2nd order # sequence. rand = numpy.random.rand() if len(elementsInSeq) == 0: catIdx = numpy.searchsorted(initCumProb, rand) elif len(elementsInSeq) == 1: catIdx = numpy.searchsorted(firstOrderCumProb[str(elementsInSeq)], rand) elif (len(elementsInSeq) >=2) and \ (seqLen is None or len(elementsInSeq) < seqLen-numNoise): catIdx = numpy.searchsorted(secondOrderCumProb[str(elementsInSeq[-2:])], rand) else: # random "noise" catIdx = numpy.random.randint(len(categoryList)) # Write out the record catIdx = min(maxCatIdx, catIdx) outFile.appendRecord([reset,categoryList[catIdx]]) #print categoryList[catIdx] # ------------------------------------------------------------ # Increment counters elementsInSeq.append(catIdx) numElementsSinceReset += 1 # Generate another reset? if resetsEvery is not None and numElementsSinceReset == resetsEvery: numElementsSinceReset = 0 elementsInSeq = [] # Start another 2nd order sequence? if seqLen is not None and (len(elementsInSeq) == seqLen+numNoise): elementsInSeq = [] outFile.close()
class StreamReader(RecordStreamIface): """ Implements a stream reader. This is a high level class that owns one or more underlying implementations of a RecordStreamIFace. Each RecordStreamIFace implements the raw reading of records from the record store (which could be a file, hbase table or something else). In the future, we will support joining of two or more RecordStreamIFace's (which is why the streamDef accepts a list of 'stream' elements), but for now only 1 source is supported. The class also implements aggregation of the (in the future) joined records from the sources. This module parses the stream definition (as defined in /nupic/frameworks/opf/jsonschema/stream_def.json), creates the RecordStreamIFace for each source ('stream's element) defined in the stream def, performs aggregation, and returns each record in the correct format according to the desired column names specified in the streamDef. This class implements the RecordStreamIFace interface and thus can be used in place of a raw record stream. This is an example streamDef: { 'version': 1 'info': 'test_hotgym', 'streams': [ {'columns': [u'*'], 'info': u'hotGym.csv', 'last_record': 4000, 'source': u'file://extra/hotgym/hotgym.csv'}. ], 'timeField': 'timestamp', 'aggregation': { 'hours': 1, 'fields': [ ('timestamp', 'first'), ('gym', 'first'), ('consumption', 'sum') ], } } """ ############################################################################ def __init__(self, streamDef, bookmark=None, saveOutput=False, isBlocking=True, maxTimeout=0, eofOnTimeout=False): """ Base class constructor, performs common initialization Parameters: ---------------------------------------------------------------- streamDef: The stream definition, potentially containing multiple sources (not supported yet). See /nupic/frameworks/opf/jsonschema/stream_def.json for the format of this dict bookmark: Bookmark to start reading from. This overrides the first_record field of the streamDef if provided. saveOutput: If true, save the output to a csv file in a temp directory. The path to the generated file can be found in the log output. isBlocking: should read operation block *forever* if the next row of data is not available, but the stream is not marked as 'completed' yet? maxTimeout: if isBlocking is False, max seconds to wait for more data before timing out; ignored when isBlocking is True. eofOnTimeout: If True and we get a read timeout (isBlocking must be False to get read timeouts), assume we've reached the end of the input and produce the last aggregated record, if one can be completed. """ # Call superclass constructor super(StreamReader, self).__init__() loggerPrefix = 'com.numenta.nupic.data.StreamReader' self._logger = logging.getLogger(loggerPrefix) jsonhelpers.validate(streamDef, schemaPath=resource_filename( jsonschema.__name__, "stream_def.json")) assert len(streamDef['streams']) == 1, "Only 1 source stream is supported" # Save constructor args sourceDict = streamDef['streams'][0] self._recordCount = 0 self._eofOnTimeout = eofOnTimeout self._logger.debug('Reading stream with the def: %s', sourceDict) # Dictionary to store record statistics (min and max of scalars for now) self._stats = None # --------------------------------------------------------------------- # Get the stream definition params # Limiting window of the stream. It would not return any records until # 'first_record' ID is read (or very first with the ID above that). The # stream will return EOS once it reads record with ID 'last_record' or # above (NOTE: the name 'lastRecord' is misleading because it is NOT # inclusive). firstRecordIdx = sourceDict.get('first_record', None) self._sourceLastRecordIdx = sourceDict.get('last_record', None) # If a bookmark was given, then override first_record from the stream # definition. if bookmark is not None: firstRecordIdx = None # Column names must be provided in the streamdef json # Special case is ['*'], meaning all available names from the record stream self._streamFieldNames = sourceDict.get('columns', None) if self._streamFieldNames != None and self._streamFieldNames[0] == '*': self._needFieldsFiltering = False else: self._needFieldsFiltering = True # Types must be specified in streamdef json, or in case of the # file_recod_stream types could be implicit from the file streamFieldTypes = sourceDict.get('types', None) self._logger.debug('Types from the def: %s', streamFieldTypes) # Validate that all types are valid if streamFieldTypes != None: for dataType in streamFieldTypes: assert(dataType in TYPES) # Reset, sequence and time fields might be provided by streamdef json streamResetFieldName = streamDef.get('resetField', None) streamTimeFieldName = streamDef.get('timeField', None) streamSequenceFieldName = streamDef.get('sequenceIdField', None) self._logger.debug('r, t, s fields: %s, %s, %s', streamResetFieldName, streamTimeFieldName, streamSequenceFieldName) # ======================================================================= # Open up the underlying record store dataUrl = sourceDict.get('source', None) assert(dataUrl is not None) self._openStream(dataUrl, isBlocking, maxTimeout, bookmark, firstRecordIdx) assert(self._recordStore is not None) # ======================================================================= # Prepare the data structures we need for returning just the fields # the caller wants from each record self._recordStoreFields = self._recordStore.getFields() self._recordStoreFieldNames = self._recordStore.getFieldNames() if not self._needFieldsFiltering: self._streamFieldNames = self._recordStoreFieldNames # Build up the field definitions for each field. This is a list of tuples # of (name, type, special) self._streamFields = [] for dstIdx, name in enumerate(self._streamFieldNames): if name not in self._recordStoreFieldNames: raise RuntimeError("The column '%s' from the stream definition " "is not present in the underlying stream which has the following " "columns: %s" % (name, self._recordStoreFieldNames)) fieldIdx = self._recordStoreFieldNames.index(name) fieldType = self._recordStoreFields[fieldIdx][1] fieldSpecial = self._recordStoreFields[fieldIdx][2] # If the types or specials were defined in the stream definition, # then override what was found in the record store if streamFieldTypes is not None: fieldType = streamFieldTypes[dstIdx] if streamResetFieldName is not None and streamResetFieldName == name: fieldSpecial = 'R' if streamTimeFieldName is not None and streamTimeFieldName == name: fieldSpecial = 'T' if streamSequenceFieldName is not None and streamSequenceFieldName == name: fieldSpecial = 'S' self._streamFields.append(FieldMetaInfo(name, fieldType, fieldSpecial)) # ======================================================================== # Create the aggregator which will handle aggregation of records before # returning them. self._aggregator = Aggregator( aggregationInfo=streamDef.get('aggregation', None), inputFields=self._recordStoreFields, timeFieldName=streamDef.get('timeField', None), sequenceIdFieldName=streamDef.get('sequenceIdField', None), resetFieldName=streamDef.get('resetField', None)) # We rely on the aggregator to tell us the bookmark of the last raw input # that contributed to the aggregated record self._aggBookmark = None # Compute the aggregation period in terms of months and seconds if 'aggregation' in streamDef: self._aggMonthsAndSeconds = nupic.support.aggregationToMonthsSeconds( streamDef.get('aggregation')) else: self._aggMonthsAndSeconds = None # ======================================================================== # Are we saving the generated output to a csv? if saveOutput: tmpDir = tempfile.mkdtemp() outFilename = os.path.join(tmpDir, "generated_output.csv") self._logger.info("StreamReader: Saving generated records to: '%s'" % outFilename) self._writer = FileRecordStream(streamID=outFilename, write=True, fields=self._streamFields) else: self._writer = None ############################################################################## def _openStream(self, dataUrl, isBlocking, maxTimeout, bookmark, firstRecordIdx): """Open the underlying file stream. This only supports 'file://' prefixed paths. """ self._recordStoreName = findDataset(dataUrl[len(FILE_PREF):]) self._recordStore = FileRecordStream(streamID=self._recordStoreName, write=False, bookmark=bookmark, firstRecord=firstRecordIdx) ############################################################################## def close(self): """ Close the stream """ return self._recordStore.close() ############################################################################ def getNextRecord(self): """ Returns combined data from all sources (values only). Returns None on EOF; empty sequence on timeout. """ # Keep reading from the raw input till we get enough for an aggregated # record while True: # Reached EOF due to lastRow constraint? if self._sourceLastRecordIdx is not None and \ self._recordStore.getNextRecordIdx() >= self._sourceLastRecordIdx: preAggValues = None # indicates EOF bookmark = self._recordStore.getBookmark() else: # Get the raw record and bookmark preAggValues = self._recordStore.getNextRecord() bookmark = self._recordStore.getBookmark() if preAggValues == (): # means timeout error occurred if self._eofOnTimeout: preAggValues = None # act as if we got EOF else: return preAggValues # Timeout indicator self._logger.debug('Read source record #%d: %r', self._recordStore.getNextRecordIdx()-1, preAggValues) # Perform aggregation (fieldValues, aggBookmark) = self._aggregator.next(preAggValues, bookmark) # Update the aggregated record bookmark if we got a real record back if fieldValues is not None: self._aggBookmark = aggBookmark # Reached EOF? if preAggValues is None and fieldValues is None: return None # Return it if we have a record if fieldValues is not None: break # Do we need to re-order the fields in the record? if self._needFieldsFiltering: values = [] srcDict = dict(zip(self._recordStoreFieldNames, fieldValues)) for name in self._streamFieldNames: values.append(srcDict[name]) fieldValues = values # Write to debug output? if self._writer is not None: self._writer.appendRecord(fieldValues) self._recordCount += 1 self._logger.debug('Returning aggregated record #%d from getNextRecord(): ' '%r. Bookmark: %r', self._recordCount-1, fieldValues, self._aggBookmark) return fieldValues def getDataRowCount(self): """Iterates through stream to calculate total records after aggregation. This will alter the bookmark state. """ inputRowCountAfterAggregation = 0 while True: record = self.getNextRecord() if record is None: return inputRowCountAfterAggregation inputRowCountAfterAggregation += 1 if inputRowCountAfterAggregation > 10000: raise RuntimeError('No end of datastream found.') ############################################################################ def getLastRecords(self, numRecords): """Saves the record in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") ############################################################################# def getRecordsRange(self, bookmark=None, range=None): """ Returns a range of records, starting from the bookmark. If 'bookmark' is None, then records read from the first available. If 'range' is None, all available records will be returned (caution: this could be a lot of records and require a lot of memory). """ raise RuntimeError("Not implemented in StreamReader") ############################################################################# def getNextRecordIdx(self): """Returns the index of the record that will be read next from getNextRecord() """ return self._recordCount ############################################################################# def recordsExistAfter(self, bookmark): """Returns True iff there are records left after the bookmark.""" return self._recordStore.recordsExistAfter(bookmark) ############################################################################## def getAggregationMonthsAndSeconds(self): """ Returns the aggregation period of the record stream as a dict containing 'months' and 'seconds'. The months is always an integer and seconds is a floating point. Only one is allowed to be non-zero at a time. If there is no aggregation associated with the stream, returns None. Typically, a raw file or hbase stream will NOT have any aggregation info, but subclasses of RecordStreamIFace, like StreamReader, will and will return the aggregation period from this call. This call is used by the getNextRecordDict() method to assign a record number to a record given its timestamp and the aggregation interval Parameters: ------------------------------------------------------------------------ retval: aggregationPeriod (as a dict) or None 'months': number of months in aggregation period 'seconds': number of seconds in aggregation period (as a float) """ return self._aggMonthsAndSeconds ############################################################################ def appendRecord(self, record, inputRef=None): """Saves the record in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") ############################################################################ def appendRecords(self, records, inputRef=None, progressCB=None): """Saves multiple records in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") ############################################################################# def removeOldData(self): raise RuntimeError("Not implemented in StreamReader") ############################################################################# def seekFromEnd(self, numRecords): """Seeks to numRecords from the end and returns a bookmark to the new position. """ raise RuntimeError("Not implemented in StreamReader") ############################################################################ def getFieldNames(self): """ Returns all fields in all inputs (list of plain names). NOTE: currently, only one input is supported """ return [f[0] for f in self._streamFields] ############################################################################ def getFields(self): """ Returns a sequence of nupic.data.fieldmeta.FieldMetaInfo name/type/special tuples for each field in the stream. """ return self._streamFields ############################################################################ def getBookmark(self): """ Returns a bookmark to the current position """ return self._aggBookmark ############################################################################# def getResetFieldIdx(self): """ Index of the 'reset' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'R' or field[2] == 'r': return i return None ############################################################################# def getTimestampFieldIdx(self): """ Index of the 'timestamp' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'T' or field[2] == 't': return i return None ############################################################################# def getSequenceIdFieldIdx(self): """ Index of the 'sequenceId' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'S' or field[2] == 's': return i return None ############################################################################# def getCategoryFieldIdx(self): """ Index of the 'category' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'C' or field[2] == 'c': return i return None ############################################################################# def clearStats(self): """ Resets stats collected so far. """ self._recordStore.clearStats() ############################################################################# def getStats(self): """ Returns stats (like min and max values of the fields). TODO: This method needs to be enhanced to get the stats on the *aggregated* records. """ # The record store returns a dict of stats, each value in this dict is # a list with one item per field of the record store # { # 'min' : [f1_min, f2_min, f3_min], # 'max' : [f1_max, f2_max, f3_max] # } recordStoreStats = self._recordStore.getStats() # We need to convert each item to represent the fields of the *stream* streamStats = dict() for (key, values) in recordStoreStats.items(): fieldStats = dict(zip(self._recordStoreFieldNames, values)) streamValues = [] for name in self._streamFieldNames: streamValues.append(fieldStats[name]) streamStats[key] = streamValues return streamStats ############################################################################# def getError(self): """ Returns errors saved in the stream. """ return self._recordStore.getError() ############################################################################# def setError(self, error): """ Saves specified error in the stream. """ self._recordStore.setError(error) ############################################################################# def isCompleted(self): """ Returns True if all records have been read. """ return self._recordStore.isCompleted() ############################################################################# def setCompleted(self, completed=True): """ Marks the stream completed (True or False) """ # CSV file is always considered completed, nothing to do self._recordStore.setCompleted(completed) ############################################################################# def setTimeout(self, timeout): """ Set the read timeout """ self._recordStore.setTimeout(timeout) ############################################################################# def flush(self): """ Flush the file to disk """ raise RuntimeError("Not implemented in StreamReader")
def _generateOverlapping(filename="overlap.csv", numSequences=2, elementsPerSeq=3, numRepeats=10, hub=[0,1], hubOffset=1, resets=False): """ Generate a temporal dataset containing sequences that overlap one or more elements with other sequences. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output hub: sub-sequence to place within each other sequence hubOffset: where, within each sequence, to place the hub resets: if True, turn on reset at start of each sequence """ # Check for conflicts in arguments assert (hubOffset + len(hub) <= elementsPerSeq) # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print "Creating %s..." % (pathname) fields = [('reset', 'int', 'R'), ('category', 'int', 'C'), ('field1', 'string', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences with the hub in the middle sequences = [] nextElemIdx = max(hub)+1 for _ in range(numSequences): seq = [] for j in range(hubOffset): seq.append(nextElemIdx) nextElemIdx += 1 for j in hub: seq.append(j) j = hubOffset + len(hub) while j < elementsPerSeq: seq.append(nextElemIdx) nextElemIdx += 1 j += 1 sequences.append(seq) # Write out the sequences in random order seqIdxs = [] for _ in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) for seqIdx in seqIdxs: reset = int(resets) seq = sequences[seqIdx] for (x) in seq: outFile.appendRecord([reset, str(seqIdx), str(x)]) reset = 0 outFile.close()
class _BasicPredictionWriter(PredictionWriterIface): """ This class defines the basic (file-based) implementation of PredictionWriterIface, whose instances are returned by BasicPredictionWriterFactory """ def __init__(self, experimentDir, label, inferenceType, fields, metricNames=None, checkpointSource=None): """ Constructor experimentDir: experiment directory path that contains description.py label: A label string to incorporate into the filename. inferenceElements: inferenceType: An constant from opfutils.InferenceType for the requested prediction writer fields: a non-empty sequence of nupic.data.fieldmeta.FieldMetaInfo representing fields that will be emitted to this prediction writer metricNames: OPTIONAL - A list of metric names that well be emiited by this prediction writer checkpointSource: If not None, a File-like object containing the previously-checkpointed predictions for setting the initial contents of this PredictionOutputStream. Will be copied before returning, if needed. """ #assert len(fields) > 0 self.__experimentDir = experimentDir # opfutils.InferenceType kind value self.__inferenceType = inferenceType # A tuple of nupic.data.fieldmeta.FieldMetaInfo self.__inputFieldsMeta = tuple(copy.deepcopy(fields)) self.__numInputFields = len(self.__inputFieldsMeta) self.__label = label if metricNames is not None: metricNames.sort() self.__metricNames = metricNames # Define our output field meta info self.__outputFieldsMeta = [] # The list of inputs that we include in the prediction output self._rawInputNames = [] # Output dataset self.__datasetPath = None self.__dataset = None # Save checkpoint data until we're ready to create the output dataset self.__checkpointCache = None if checkpointSource is not None: checkpointSource.seek(0) self.__checkpointCache = StringIO.StringIO() shutil.copyfileobj(checkpointSource, self.__checkpointCache) return def __openDatafile(self, modelResult): """Open the data file and write the header row""" # Write reset bit resetFieldMeta = FieldMetaInfo( name="reset", type=FieldMetaType.integer, special = FieldMetaSpecial.reset) self.__outputFieldsMeta.append(resetFieldMeta) # ----------------------------------------------------------------------- # Write each of the raw inputs that go into the encoders rawInput = modelResult.rawInput rawFields = rawInput.keys() rawFields.sort() for field in rawFields: if field.startswith('_') or field == 'reset': continue value = rawInput[field] meta = FieldMetaInfo(name=field, type=FieldMetaType.string, special=FieldMetaSpecial.none) self.__outputFieldsMeta.append(meta) self._rawInputNames.append(field) # ----------------------------------------------------------------------- # Handle each of the inference elements for inferenceElement, value in modelResult.inferences.iteritems(): inferenceLabel = InferenceElement.getLabel(inferenceElement) # TODO: Right now we assume list inferences are associated with # The input field metadata if type(value) in (list, tuple): # Append input and prediction field meta-info self.__outputFieldsMeta.extend(self.__getListMetaInfo(inferenceElement)) elif isinstance(value, dict): self.__outputFieldsMeta.extend(self.__getDictMetaInfo(inferenceElement, value)) else: if InferenceElement.getInputElement(inferenceElement): self.__outputFieldsMeta.append(FieldMetaInfo(name=inferenceLabel+".actual", type=FieldMetaType.string, special = '')) self.__outputFieldsMeta.append(FieldMetaInfo(name=inferenceLabel, type=FieldMetaType.string, special = '')) if self.__metricNames: for metricName in self.__metricNames: metricField = FieldMetaInfo( name = metricName, type = FieldMetaType.float, special = FieldMetaSpecial.none) self.__outputFieldsMeta.append(metricField) # Create the inference directory for our experiment inferenceDir = _FileUtils.createExperimentInferenceDir(self.__experimentDir) # Consctruct the prediction dataset file path filename = (self.__label + "." + opfutils.InferenceType.getLabel(self.__inferenceType) + ".predictionLog.csv") self.__datasetPath = os.path.join(inferenceDir, filename) # Create the output dataset print "OPENING OUTPUT FOR PREDICTION WRITER AT: {0!r}".format(self.__datasetPath) print "Prediction field-meta: {0!r}".format([tuple(i) for i in self.__outputFieldsMeta]) self.__dataset = FileRecordStream(streamID=self.__datasetPath, write=True, fields=self.__outputFieldsMeta) # Copy data from checkpoint cache if self.__checkpointCache is not None: self.__checkpointCache.seek(0) reader = csv.reader(self.__checkpointCache, dialect='excel') # Skip header row try: header = reader.next() except StopIteration: print "Empty record checkpoint initializer for {0!r}".format(self.__datasetPath) else: assert tuple(self.__dataset.getFieldNames()) == tuple(header), \ "dataset.getFieldNames(): {0!r}; predictionCheckpointFieldNames: {1!r}".format( tuple(self.__dataset.getFieldNames()), tuple(header)) # Copy the rows from checkpoint numRowsCopied = 0 while True: try: row = reader.next() except StopIteration: break #print "DEBUG: restoring row from checkpoint: %r" % (row,) self.__dataset.appendRecord(row) numRowsCopied += 1 self.__dataset.flush() print "Restored {0:d} rows from checkpoint for {1!r}".format( numRowsCopied, self.__datasetPath) # Dispose of our checkpoint cache self.__checkpointCache.close() self.__checkpointCache = None return def setLoggedMetrics(self, metricNames): """ Tell the writer which metrics should be written Parameters: ----------------------------------------------------------------------- metricsNames: A list of metric lables to be written """ if metricNames is None: self.__metricNames = set([]) else: self.__metricNames = set(metricNames) def close(self): """ [virtual method override] Closes the writer (e.g., close the underlying file) """ if self.__dataset: self.__dataset.close() self.__dataset = None return def __getListMetaInfo(self, inferenceElement): """ Get field metadata information for inferences that are of list type TODO: Right now we assume list inferences are associated with the input field metadata """ fieldMetaInfo = [] inferenceLabel = InferenceElement.getLabel(inferenceElement) for inputFieldMeta in self.__inputFieldsMeta: if InferenceElement.getInputElement(inferenceElement): outputFieldMeta = FieldMetaInfo( name=inputFieldMeta.name + ".actual", type=inputFieldMeta.type, special=inputFieldMeta.special ) predictionField = FieldMetaInfo( name=inputFieldMeta.name + "." + inferenceLabel, type=inputFieldMeta.type, special=inputFieldMeta.special ) fieldMetaInfo.append(outputFieldMeta) fieldMetaInfo.append(predictionField) return fieldMetaInfo def __getDictMetaInfo(self, inferenceElement, inferenceDict): """Get field metadate information for inferences that are of dict type""" fieldMetaInfo = [] inferenceLabel = InferenceElement.getLabel(inferenceElement) if InferenceElement.getInputElement(inferenceElement): fieldMetaInfo.append(FieldMetaInfo(name=inferenceLabel+".actual", type=FieldMetaType.string, special = '')) keys = sorted(inferenceDict.keys()) for key in keys: fieldMetaInfo.append(FieldMetaInfo(name=inferenceLabel+"."+str(key), type=FieldMetaType.string, special='')) return fieldMetaInfo def append(self, modelResult): """ [virtual method override] Emits a single prediction as input versus predicted. modelResult: An opfutils.ModelResult object that contains the model input and output for the current timestep. """ #print "DEBUG: _BasicPredictionWriter: writing modelResult: %r" % (modelResult,) # If there are no inferences, don't write anything inferences = modelResult.inferences hasInferences = False if inferences is not None: for value in inferences.itervalues(): hasInferences = hasInferences or (value is not None) if not hasInferences: return if self.__dataset is None: self.__openDatafile(modelResult) inputData = modelResult.sensorInput sequenceReset = int(bool(inputData.sequenceReset)) outputRow = [sequenceReset] # ----------------------------------------------------------------------- # Write out the raw inputs rawInput = modelResult.rawInput for field in self._rawInputNames: outputRow.append(str(rawInput[field])) # ----------------------------------------------------------------------- # Write out the inference element info for inferenceElement, outputVal in inferences.iteritems(): inputElement = InferenceElement.getInputElement(inferenceElement) if inputElement: inputVal = getattr(inputData, inputElement) else: inputVal = None if type(outputVal) in (list, tuple): assert type(inputVal) in (list, tuple, None) for iv, ov in zip(inputVal, outputVal): # Write actual outputRow.append(str(iv)) # Write inferred outputRow.append(str(ov)) elif isinstance(outputVal, dict): if inputVal is not None: # If we have a predicted field, include only that in the actuals if modelResult.predictedFieldName is not None: outputRow.append(str(inputVal[modelResult.predictedFieldName])) else: outputRow.append(str(inputVal)) for key in sorted(outputVal.keys()): outputRow.append(str(outputVal[key])) else: if inputVal is not None: outputRow.append(str(inputVal)) outputRow.append(str(outputVal)) metrics = modelResult.metrics for metricName in self.__metricNames: outputRow.append(metrics.get(metricName, 0.0)) #print "DEBUG: _BasicPredictionWriter: writing outputRow: %r" % (outputRow,) self.__dataset.appendRecord(outputRow) self.__dataset.flush() return def checkpoint(self, checkpointSink, maxRows): """ [virtual method override] Save a checkpoint of the prediction output stream. The checkpoint comprises up to maxRows of the most recent inference records. Parameters: ---------------------------------------------------------------------- checkpointSink: A File-like object where predictions checkpoint data, if any, will be stored. maxRows: Maximum number of most recent inference rows to checkpoint. """ checkpointSink.truncate() if self.__dataset is None: if self.__checkpointCache is not None: self.__checkpointCache.seek(0) shutil.copyfileobj(self.__checkpointCache, checkpointSink) checkpointSink.flush() return else: # Nothing to checkpoint return self.__dataset.flush() totalDataRows = self.__dataset.getDataRowCount() if totalDataRows == 0: # Nothing to checkpoint return # Open reader of prediction file (suppress missingValues conversion) reader = FileRecordStream(self.__datasetPath, missingValues=[]) # Create CSV writer for writing checkpoint rows writer = csv.writer(checkpointSink) # Write the header row to checkpoint sink -- just field names writer.writerow(reader.getFieldNames()) # Determine number of rows to checkpoint numToWrite = min(maxRows, totalDataRows) # Skip initial rows to get to the rows that we actually need to checkpoint numRowsToSkip = totalDataRows - numToWrite for i in xrange(numRowsToSkip): reader.next() # Write the data rows to checkpoint sink numWritten = 0 while True: row = reader.getNextRecord() if row is None: break; row = [str(element) for element in row] #print "DEBUG: _BasicPredictionWriter: checkpointing row: %r" % (row,) writer.writerow(row) numWritten +=1 assert numWritten == numToWrite, \ "numWritten ({0!s}) != numToWrite ({1!s})".format(numWritten, numToWrite) checkpointSink.flush() return
def _generateOverlapping(filename="overlap.csv", numSequences=2, elementsPerSeq=3, numRepeats=10, hub=[0, 1], hubOffset=1, resets=False): """ Generate a temporal dataset containing sequences that overlap one or more elements with other sequences. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output hub: sub-sequence to place within each other sequence hubOffset: where, within each sequence, to place the hub resets: if True, turn on reset at start of each sequence """ # Check for conflicts in arguments assert (hubOffset + len(hub) <= elementsPerSeq) # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print "Creating %s..." % (pathname) fields = [('reset', 'int', 'R'), ('category', 'string', ''), ('field1', 'string', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences with the hub in the middle sequences = [] nextElemIdx = max(hub) + 1 for _ in range(numSequences): seq = [] for j in range(hubOffset): seq.append(nextElemIdx) nextElemIdx += 1 for j in hub: seq.append(j) j = hubOffset + len(hub) while j < elementsPerSeq: seq.append(nextElemIdx) nextElemIdx += 1 j += 1 sequences.append(seq) # Write out the sequences in random order seqIdxs = [] for _ in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) for seqIdx in seqIdxs: reset = int(resets) seq = sequences[seqIdx] for (x) in seq: outFile.appendRecord([reset, str(seqIdx), str(x)]) reset = 0 outFile.close()
def testSimpleMulticlassNetworkPY(self): # Setup data record stream of fake data (with three categories) filename = _getTempFileName() fields = [("timestamp", "datetime", "T"), ("value", "float", ""), ("reset", "int", "R"), ("sid", "int", "S"), ("categories", "list", "C")] records = ( [datetime(day=1, month=3, year=2010), 0.0, 1, 0, "0"], [datetime(day=2, month=3, year=2010), 1.0, 0, 0, "1"], [datetime(day=3, month=3, year=2010), 0.0, 0, 0, "0"], [datetime(day=4, month=3, year=2010), 1.0, 0, 0, "1"], [datetime(day=5, month=3, year=2010), 0.0, 0, 0, "0"], [datetime(day=6, month=3, year=2010), 1.0, 0, 0, "1"], [datetime(day=7, month=3, year=2010), 0.0, 0, 0, "0"], [datetime(day=8, month=3, year=2010), 1.0, 0, 0, "1"]) dataSource = FileRecordStream(streamID=filename, write=True, fields=fields) for r in records: dataSource.appendRecord(list(r)) # Create the network and get region instances. net = Network() net.addRegion("sensor", "py.RecordSensor", "{'numCategories': 3}") net.addRegion("classifier", "py.SDRClassifierRegion", "{steps: '0', alpha: 0.001, implementation: 'py'}") net.link("sensor", "classifier", "UniformLink", "", srcOutput="dataOut", destInput="bottomUpIn") net.link("sensor", "classifier", "UniformLink", "", srcOutput="categoryOut", destInput="categoryIn") sensor = net.regions["sensor"] classifier = net.regions["classifier"] # Setup sensor region encoder and data stream. dataSource.close() dataSource = FileRecordStream(filename) sensorRegion = sensor.getSelf() sensorRegion.encoder = MultiEncoder() sensorRegion.encoder.addEncoder( "value", ScalarEncoder(21, 0.0, 13.0, n=256, name="value")) sensorRegion.dataSource = dataSource # Get ready to run. net.initialize() # Train the network (by default learning is ON in the classifier, but assert # anyway) and then turn off learning and turn on inference mode. self.assertEqual(classifier.getParameter("learningMode"), 1) net.run(8) # Test the network on the same data as it trained on; should classify with # 100% accuracy. classifier.setParameter("inferenceMode", 1) classifier.setParameter("learningMode", 0) # Assert learning is OFF and that the classifier learned the dataset. self.assertEqual(classifier.getParameter("learningMode"), 0, "Learning mode is not turned off.") self.assertEqual(classifier.getParameter("inferenceMode"), 1, "Inference mode is not turned on.") # make sure we can access all the parameters with getParameter self.assertEqual(classifier.getParameter("maxCategoryCount"), 2000) self.assertAlmostEqual(float(classifier.getParameter("alpha")), 0.001) self.assertEqual(int(classifier.getParameter("steps")), 0) self.assertTrue(classifier.getParameter("implementation") == "py") self.assertEqual(classifier.getParameter("verbosity"), 0) expectedCats = ([0.0], [1.0], [0.0], [1.0], [0.0], [1.0], [0.0], [1.0],) dataSource.rewind() for i in xrange(8): net.run(1) inferredCats = classifier.getOutputData("categoriesOut") self.assertSequenceEqual(expectedCats[i], inferredCats.tolist(), "Classififer did not infer expected category " "for record number {}.".format(i)) # Close data stream, delete file. dataSource.close() os.remove(filename)
class StreamReader(RecordStreamIface): """ Implements a stream reader. This is a high level class that owns one or more underlying implementations of a RecordStreamIFace. Each RecordStreamIFace implements the raw reading of records from the record store (which could be a file, hbase table or something else). In the future, we will support joining of two or more RecordStreamIFace's (which is why the streamDef accepts a list of 'stream' elements), but for now only 1 source is supported. The class also implements aggregation of the (in the future) joined records from the sources. This module parses the stream definition (as defined in /nupic/frameworks/opf/jsonschema/stream_def.json), creates the RecordStreamIFace for each source ('stream's element) defined in the stream def, performs aggregation, and returns each record in the correct format according to the desired column names specified in the streamDef. This class implements the RecordStreamIFace interface and thus can be used in place of a raw record stream. This is an example streamDef: { 'version': 1 'info': 'test_hotgym', 'streams': [ {'columns': [u'*'], 'info': u'hotGym.csv', 'last_record': 4000, 'source': u'file://extra/hotgym/hotgym.csv'}. ], 'timeField': 'timestamp', 'aggregation': { 'hours': 1, 'fields': [ ('timestamp', 'first'), ('gym', 'first'), ('consumption', 'sum') ], } } """ def __init__(self, streamDef, bookmark=None, saveOutput=False, isBlocking=True, maxTimeout=0, eofOnTimeout=False): """ Base class constructor, performs common initialization Parameters: ---------------------------------------------------------------- streamDef: The stream definition, potentially containing multiple sources (not supported yet). See /nupic/frameworks/opf/jsonschema/stream_def.json for the format of this dict bookmark: Bookmark to start reading from. This overrides the first_record field of the streamDef if provided. saveOutput: If true, save the output to a csv file in a temp directory. The path to the generated file can be found in the log output. isBlocking: should read operation block *forever* if the next row of data is not available, but the stream is not marked as 'completed' yet? maxTimeout: if isBlocking is False, max seconds to wait for more data before timing out; ignored when isBlocking is True. eofOnTimeout: If True and we get a read timeout (isBlocking must be False to get read timeouts), assume we've reached the end of the input and produce the last aggregated record, if one can be completed. """ # Call superclass constructor super(StreamReader, self).__init__() loggerPrefix = 'com.numenta.nupic.data.StreamReader' self._logger = logging.getLogger(loggerPrefix) jsonhelpers.validate(streamDef, schemaPath=resource_filename( jsonschema.__name__, "stream_def.json")) assert len( streamDef['streams']) == 1, "Only 1 source stream is supported" # Save constructor args sourceDict = streamDef['streams'][0] self._recordCount = 0 self._eofOnTimeout = eofOnTimeout self._logger.debug('Reading stream with the def: %s', sourceDict) # Dictionary to store record statistics (min and max of scalars for now) self._stats = None # --------------------------------------------------------------------- # Get the stream definition params # Limiting window of the stream. It would not return any records until # 'first_record' ID is read (or very first with the ID above that). The # stream will return EOS once it reads record with ID 'last_record' or # above (NOTE: the name 'lastRecord' is misleading because it is NOT # inclusive). firstRecordIdx = sourceDict.get('first_record', None) self._sourceLastRecordIdx = sourceDict.get('last_record', None) # If a bookmark was given, then override first_record from the stream # definition. if bookmark is not None: firstRecordIdx = None # Column names must be provided in the streamdef json # Special case is ['*'], meaning all available names from the record stream self._streamFieldNames = sourceDict.get('columns', None) if self._streamFieldNames != None and self._streamFieldNames[0] == '*': self._needFieldsFiltering = False else: self._needFieldsFiltering = True # Types must be specified in streamdef json, or in case of the # file_recod_stream types could be implicit from the file streamFieldTypes = sourceDict.get('types', None) self._logger.debug('Types from the def: %s', streamFieldTypes) # Validate that all types are valid if streamFieldTypes != None: for dataType in streamFieldTypes: assert (dataType in TYPES) # Reset, sequence and time fields might be provided by streamdef json streamResetFieldName = streamDef.get('resetField', None) streamTimeFieldName = streamDef.get('timeField', None) streamSequenceFieldName = streamDef.get('sequenceIdField', None) self._logger.debug('r, t, s fields: %s, %s, %s', streamResetFieldName, streamTimeFieldName, streamSequenceFieldName) # ======================================================================= # Open up the underlying record store dataUrl = sourceDict.get('source', None) assert (dataUrl is not None) self._openStream(dataUrl, isBlocking, maxTimeout, bookmark, firstRecordIdx) assert (self._recordStore is not None) # ======================================================================= # Prepare the data structures we need for returning just the fields # the caller wants from each record self._recordStoreFields = self._recordStore.getFields() self._recordStoreFieldNames = self._recordStore.getFieldNames() if not self._needFieldsFiltering: self._streamFieldNames = self._recordStoreFieldNames # Build up the field definitions for each field. This is a list of tuples # of (name, type, special) self._streamFields = [] for dstIdx, name in enumerate(self._streamFieldNames): if name not in self._recordStoreFieldNames: raise RuntimeError( "The column '%s' from the stream definition " "is not present in the underlying stream which has the following " "columns: %s" % (name, self._recordStoreFieldNames)) fieldIdx = self._recordStoreFieldNames.index(name) fieldType = self._recordStoreFields[fieldIdx][1] fieldSpecial = self._recordStoreFields[fieldIdx][2] # If the types or specials were defined in the stream definition, # then override what was found in the record store if streamFieldTypes is not None: fieldType = streamFieldTypes[dstIdx] if streamResetFieldName is not None and streamResetFieldName == name: fieldSpecial = 'R' if streamTimeFieldName is not None and streamTimeFieldName == name: fieldSpecial = 'T' if streamSequenceFieldName is not None and streamSequenceFieldName == name: fieldSpecial = 'S' self._streamFields.append( FieldMetaInfo(name, fieldType, fieldSpecial)) # ======================================================================== # Create the aggregator which will handle aggregation of records before # returning them. self._aggregator = Aggregator( aggregationInfo=streamDef.get('aggregation', None), inputFields=self._recordStoreFields, timeFieldName=streamDef.get('timeField', None), sequenceIdFieldName=streamDef.get('sequenceIdField', None), resetFieldName=streamDef.get('resetField', None)) # We rely on the aggregator to tell us the bookmark of the last raw input # that contributed to the aggregated record self._aggBookmark = None # Compute the aggregation period in terms of months and seconds if 'aggregation' in streamDef: self._aggMonthsAndSeconds = nupic.support.aggregationToMonthsSeconds( streamDef.get('aggregation')) else: self._aggMonthsAndSeconds = None # ======================================================================== # Are we saving the generated output to a csv? if saveOutput: tmpDir = tempfile.mkdtemp() outFilename = os.path.join(tmpDir, "generated_output.csv") self._logger.info( "StreamReader: Saving generated records to: '%s'" % outFilename) self._writer = FileRecordStream(streamID=outFilename, write=True, fields=self._streamFields) else: self._writer = None def _openStream(self, dataUrl, isBlocking, maxTimeout, bookmark, firstRecordIdx): """Open the underlying file stream. This only supports 'file://' prefixed paths. """ filePath = dataUrl[len(FILE_PREF):] if not os.path.isabs(filePath): filePath = os.path.join(os.getcwd(), filePath) self._recordStoreName = filePath self._recordStore = FileRecordStream(streamID=self._recordStoreName, write=False, bookmark=bookmark, firstRecord=firstRecordIdx) def close(self): """ Close the stream """ return self._recordStore.close() def getNextRecord(self): """ Returns combined data from all sources (values only). Returns None on EOF; empty sequence on timeout. """ # Keep reading from the raw input till we get enough for an aggregated # record while True: # Reached EOF due to lastRow constraint? if self._sourceLastRecordIdx is not None and \ self._recordStore.getNextRecordIdx() >= self._sourceLastRecordIdx: preAggValues = None # indicates EOF bookmark = self._recordStore.getBookmark() else: # Get the raw record and bookmark preAggValues = self._recordStore.getNextRecord() bookmark = self._recordStore.getBookmark() if preAggValues == (): # means timeout error occurred if self._eofOnTimeout: preAggValues = None # act as if we got EOF else: return preAggValues # Timeout indicator self._logger.debug('Read source record #%d: %r', self._recordStore.getNextRecordIdx() - 1, preAggValues) # Perform aggregation (fieldValues, aggBookmark) = self._aggregator.next(preAggValues, bookmark) # Update the aggregated record bookmark if we got a real record back if fieldValues is not None: self._aggBookmark = aggBookmark # Reached EOF? if preAggValues is None and fieldValues is None: return None # Return it if we have a record if fieldValues is not None: break # Do we need to re-order the fields in the record? if self._needFieldsFiltering: values = [] srcDict = dict(zip(self._recordStoreFieldNames, fieldValues)) for name in self._streamFieldNames: values.append(srcDict[name]) fieldValues = values # Write to debug output? if self._writer is not None: self._writer.appendRecord(fieldValues) self._recordCount += 1 self._logger.debug( 'Returning aggregated record #%d from getNextRecord(): ' '%r. Bookmark: %r', self._recordCount - 1, fieldValues, self._aggBookmark) return fieldValues def getDataRowCount(self): """Iterates through stream to calculate total records after aggregation. This will alter the bookmark state. """ inputRowCountAfterAggregation = 0 while True: record = self.getNextRecord() if record is None: return inputRowCountAfterAggregation inputRowCountAfterAggregation += 1 if inputRowCountAfterAggregation > 10000: raise RuntimeError('No end of datastream found.') def getLastRecords(self, numRecords): """Saves the record in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") def getRecordsRange(self, bookmark=None, range=None): """ Returns a range of records, starting from the bookmark. If 'bookmark' is None, then records read from the first available. If 'range' is None, all available records will be returned (caution: this could be a lot of records and require a lot of memory). """ raise RuntimeError("Not implemented in StreamReader") def getNextRecordIdx(self): """Returns the index of the record that will be read next from getNextRecord() """ return self._recordCount def recordsExistAfter(self, bookmark): """Returns True iff there are records left after the bookmark.""" return self._recordStore.recordsExistAfter(bookmark) def getAggregationMonthsAndSeconds(self): """ Returns the aggregation period of the record stream as a dict containing 'months' and 'seconds'. The months is always an integer and seconds is a floating point. Only one is allowed to be non-zero at a time. If there is no aggregation associated with the stream, returns None. Typically, a raw file or hbase stream will NOT have any aggregation info, but subclasses of RecordStreamIFace, like StreamReader, will and will return the aggregation period from this call. This call is used by the getNextRecordDict() method to assign a record number to a record given its timestamp and the aggregation interval Parameters: ------------------------------------------------------------------------ retval: aggregationPeriod (as a dict) or None 'months': number of months in aggregation period 'seconds': number of seconds in aggregation period (as a float) """ return self._aggMonthsAndSeconds def appendRecord(self, record, inputRef=None): """Saves the record in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") def appendRecords(self, records, inputRef=None, progressCB=None): """Saves multiple records in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") def removeOldData(self): raise RuntimeError("Not implemented in StreamReader") def seekFromEnd(self, numRecords): """Seeks to numRecords from the end and returns a bookmark to the new position. """ raise RuntimeError("Not implemented in StreamReader") def getFieldNames(self): """ Returns all fields in all inputs (list of plain names). NOTE: currently, only one input is supported """ return [f[0] for f in self._streamFields] def getFields(self): """ Returns a sequence of nupic.data.fieldmeta.FieldMetaInfo name/type/special tuples for each field in the stream. """ return self._streamFields def getBookmark(self): """ Returns a bookmark to the current position """ return self._aggBookmark def getResetFieldIdx(self): """ Index of the 'reset' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'R' or field[2] == 'r': return i return None def getTimestampFieldIdx(self): """ Index of the 'timestamp' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'T' or field[2] == 't': return i return None def getSequenceIdFieldIdx(self): """ Index of the 'sequenceId' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'S' or field[2] == 's': return i return None def getCategoryFieldIdx(self): """ Index of the 'category' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'C' or field[2] == 'c': return i return None def clearStats(self): """ Resets stats collected so far. """ self._recordStore.clearStats() def getStats(self): """ Returns stats (like min and max values of the fields). TODO: This method needs to be enhanced to get the stats on the *aggregated* records. """ # The record store returns a dict of stats, each value in this dict is # a list with one item per field of the record store # { # 'min' : [f1_min, f2_min, f3_min], # 'max' : [f1_max, f2_max, f3_max] # } recordStoreStats = self._recordStore.getStats() # We need to convert each item to represent the fields of the *stream* streamStats = dict() for (key, values) in recordStoreStats.items(): fieldStats = dict(zip(self._recordStoreFieldNames, values)) streamValues = [] for name in self._streamFieldNames: streamValues.append(fieldStats[name]) streamStats[key] = streamValues return streamStats def getError(self): """ Returns errors saved in the stream. """ return self._recordStore.getError() def setError(self, error): """ Saves specified error in the stream. """ self._recordStore.setError(error) def isCompleted(self): """ Returns True if all records have been read. """ return self._recordStore.isCompleted() def setCompleted(self, completed=True): """ Marks the stream completed (True or False) """ # CSV file is always considered completed, nothing to do self._recordStore.setCompleted(completed) def setTimeout(self, timeout): """ Set the read timeout """ self._recordStore.setTimeout(timeout) def flush(self): """ Flush the file to disk """ raise RuntimeError("Not implemented in StreamReader")
def testMissingValues(self): print "Beginning Missing Data test..." filename = _getTempFileName() # Some values missing of each type # read dataset from disk, retrieve values # string should return empty string, numeric types sentinelValue print 'Creating tempfile:', filename # write dataset to disk with float, int, and string fields fields = [('timestamp', 'datetime', 'T'), ('name', 'string', ''), ('integer', 'int', ''), ('real', 'float', '')] s = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ( [datetime(day=1, month=3, year=2010), 'rec_1', 5, 6.5], [datetime(day=2, month=3, year=2010), '', 8, 7.5], [datetime(day=3, month=3, year=2010), 'rec_3', '', 8.5], [datetime(day=4, month=3, year=2010), 'rec_4', 12, ''], [datetime(day=5, month=3, year=2010), 'rec_5', -87657496599, 6.5], [datetime(day=6, month=3, year=2010), 'rec_6', 12, -87657496599], [datetime(day=6, month=3, year=2010), str(-87657496599), 12, 6.5]) for r in records: s.appendRecord(list(r)) s.close() # Read the standard file s = FileRecordStream(streamID=filename, write=False) fieldsRead = s.getFields() self.assertTrue(fields == fieldsRead) recordsRead = [] while True: r = s.getNextRecord() if r is None: break print 'Reading record ...' print r recordsRead.append(r) # sort the records by date, so we know for sure which is which sorted(recordsRead, key=lambda rec: rec[0]) # empty string self.assertTrue(recordsRead[1][1] == SENTINEL_VALUE_FOR_MISSING_DATA) # missing int self.assertTrue(recordsRead[2][2] == SENTINEL_VALUE_FOR_MISSING_DATA) # missing float self.assertTrue(recordsRead[3][3] == SENTINEL_VALUE_FOR_MISSING_DATA) # sentinel value in input handled correctly for int field self.assertTrue(recordsRead[4][2] != SENTINEL_VALUE_FOR_MISSING_DATA) # sentinel value in input handled correctly for float field self.assertTrue(recordsRead[5][3] != SENTINEL_VALUE_FOR_MISSING_DATA) # sentinel value in input handled correctly for string field # this should leave the string as-is, since a missing string # is encoded not with a sentinel value but with an empty string self.assertTrue(recordsRead[6][1] != SENTINEL_VALUE_FOR_MISSING_DATA)
def testSimpleMulticlassNetwork(self): # Setup data record stream of fake data (with three categories) filename = _getTempFileName() fields = [("timestamp", "datetime", "T"), ("value", "float", ""), ("reset", "int", "R"), ("sid", "int", "S"), ("categories", "list", "C")] records = ([datetime(day=1, month=3, year=2010), 0.0, 1, 0, ""], [ datetime(day=2, month=3, year=2010), 1.0, 0, 0, "1 2" ], [datetime(day=3, month=3, year=2010), 1.0, 0, 0, "1 2"], [datetime(day=4, month=3, year=2010), 2.0, 0, 0, "0"], [ datetime(day=5, month=3, year=2010), 3.0, 0, 0, "1 2" ], [datetime(day=6, month=3, year=2010), 5.0, 0, 0, "1 2"], [datetime(day=7, month=3, year=2010), 8.0, 0, 0, "0"], [datetime(day=8, month=3, year=2010), 13.0, 0, 0, "1 2"]) dataSource = FileRecordStream(streamID=filename, write=True, fields=fields) for r in records: dataSource.appendRecord(list(r)) # Create the network and get region instances. net = Network() net.addRegion("sensor", "py.RecordSensor", "{'numCategories': 3}") net.addRegion("classifier", "py.KNNClassifierRegion", "{'k': 2,'distThreshold': 0,'maxCategoryCount': 3}") net.link("sensor", "classifier", "UniformLink", "", srcOutput="dataOut", destInput="bottomUpIn") net.link("sensor", "classifier", "UniformLink", "", srcOutput="categoryOut", destInput="categoryIn") sensor = net.regions["sensor"] classifier = net.regions["classifier"] # Setup sensor region encoder and data stream. dataSource.close() dataSource = FileRecordStream(filename) sensorRegion = sensor.getSelf() sensorRegion.encoder = MultiEncoder() sensorRegion.encoder.addEncoder( "value", ScalarEncoder(21, 0.0, 13.0, n=256, name="value")) sensorRegion.dataSource = dataSource # Get ready to run. net.initialize() # Train the network (by default learning is ON in the classifier, but assert # anyway) and then turn off learning and turn on inference mode. self.assertEqual(classifier.getParameter("learningMode"), 1) net.run(8) classifier.setParameter("inferenceMode", 1) classifier.setParameter("learningMode", 0) # Assert learning is OFF and that the classifier learned the dataset. self.assertEqual(classifier.getParameter("learningMode"), 0, "Learning mode is not turned off.") self.assertEqual(classifier.getParameter("inferenceMode"), 1, "Inference mode is not turned on.") self.assertEqual( classifier.getParameter("categoryCount"), 3, "The classifier should count three total categories.") # classififer learns 12 patterns b/c there are 12 categories amongst the # records: self.assertEqual( classifier.getParameter("patternCount"), 12, "The classifier should've learned 12 samples in total.") # Test the network on the same data as it trained on; should classify with # 100% accuracy. expectedCats = ([0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.5, 0.0], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.5, 0.0], [0.0, 0.5, 0.5]) dataSource.rewind() for i in xrange(8): net.run(1) inferredCats = classifier.getOutputData("categoriesOut") self.assertSequenceEqual( expectedCats[i], inferredCats.tolist(), "Classififer did not infer expected category probabilites for record " "number {}.".format(i)) # Close data stream, delete file. dataSource.close() os.remove(filename)
def testBasic(self): """Runs basic FileRecordStream tests.""" filename = _getTempFileName() # Write a standard file fields = [('name', 'string', ''), ('timestamp', 'datetime', 'T'), ('integer', 'int', ''), ('real', 'float', ''), ('reset', 'int', 'R'), ('sid', 'string', 'S'), ('categoryField', 'int', 'C'),] fieldNames = ['name', 'timestamp', 'integer', 'real', 'reset', 'sid', 'categoryField'] print 'Creating temp file:', filename s = FileRecordStream(streamID=filename, write=True, fields=fields) self.assertTrue(s.getDataRowCount() == 0) # Records records = ( ['rec_1', datetime(day=1, month=3, year=2010), 5, 6.5, 1, 'seq-1', 10], ['rec_2', datetime(day=2, month=3, year=2010), 8, 7.5, 0, 'seq-1', 11], ['rec_3', datetime(day=3, month=3, year=2010), 12, 8.5, 0, 'seq-1', 12]) self.assertTrue(s.getFields() == fields) self.assertTrue(s.getNextRecordIdx() == 0) print 'Writing records ...' for r in records: print list(r) s.appendRecord(list(r)) self.assertTrue(s.getDataRowCount() == 3) recordsBatch = ( ['rec_4', datetime(day=4, month=3, year=2010), 2, 9.5, 1, 'seq-1', 13], ['rec_5', datetime(day=5, month=3, year=2010), 6, 10.5, 0, 'seq-1', 14], ['rec_6', datetime(day=6, month=3, year=2010), 11, 11.5, 0, 'seq-1', 15]) print 'Adding batch of records...' for rec in recordsBatch: print rec s.appendRecords(recordsBatch) self.assertTrue(s.getDataRowCount() == 6) s.close() # Read the standard file s = FileRecordStream(filename) self.assertTrue(s.getDataRowCount() == 6) self.assertTrue(s.getFieldNames() == fieldNames) # Note! this is the number of records read so far self.assertTrue(s.getNextRecordIdx() == 0) readStats = s.getStats() print 'Got stats:', readStats expectedStats = { 'max': [None, None, 12, 11.5, 1, None, 15], 'min': [None, None, 2, 6.5, 0, None, 10] } self.assertTrue(readStats == expectedStats) readRecords = [] print 'Reading records ...' while True: r = s.getNextRecord() print r if r is None: break readRecords.append(r) allRecords = records + recordsBatch for r1, r2 in zip(allRecords, readRecords): print 'Expected:', r1 print 'Read :', r2 self.assertTrue(r1 == r2) s.close()
def testSimpleMulticlassNetworkPY(self): # Setup data record stream of fake data (with three categories) filename = _getTempFileName() fields = [("timestamp", "datetime", "T"), ("value", "float", ""), ("reset", "int", "R"), ("sid", "int", "S"), ("categories", "list", "C")] records = ([datetime(day=1, month=3, year=2010), 0.0, 1, 0, "0"], [ datetime(day=2, month=3, year=2010), 1.0, 0, 0, "1" ], [datetime(day=3, month=3, year=2010), 0.0, 0, 0, "0"], [datetime(day=4, month=3, year=2010), 1.0, 0, 0, "1"], [datetime(day=5, month=3, year=2010), 0.0, 0, 0, "0"], [datetime(day=6, month=3, year=2010), 1.0, 0, 0, "1" ], [datetime(day=7, month=3, year=2010), 0.0, 0, 0, "0"], [datetime(day=8, month=3, year=2010), 1.0, 0, 0, "1"]) dataSource = FileRecordStream(streamID=filename, write=True, fields=fields) for r in records: dataSource.appendRecord(list(r)) # Create the network and get region instances. net = Network() net.addRegion("sensor", "py.RecordSensor", "{'numCategories': 3}") net.addRegion("classifier", "py.SDRClassifierRegion", "{steps: '0', alpha: 0.001, implementation: 'py'}") net.link("sensor", "classifier", "UniformLink", "", srcOutput="dataOut", destInput="bottomUpIn") net.link("sensor", "classifier", "UniformLink", "", srcOutput="categoryOut", destInput="categoryIn") sensor = net.regions["sensor"] classifier = net.regions["classifier"] # Setup sensor region encoder and data stream. dataSource.close() dataSource = FileRecordStream(filename) sensorRegion = sensor.getSelf() sensorRegion.encoder = MultiEncoder() sensorRegion.encoder.addEncoder( "value", ScalarEncoder(21, 0.0, 13.0, n=256, name="value")) sensorRegion.dataSource = dataSource # Get ready to run. net.initialize() # Train the network (by default learning is ON in the classifier, but assert # anyway) and then turn off learning and turn on inference mode. self.assertEqual(classifier.getParameter("learningMode"), 1) net.run(8) # Test the network on the same data as it trained on; should classify with # 100% accuracy. classifier.setParameter("inferenceMode", 1) classifier.setParameter("learningMode", 0) # Assert learning is OFF and that the classifier learned the dataset. self.assertEqual(classifier.getParameter("learningMode"), 0, "Learning mode is not turned off.") self.assertEqual(classifier.getParameter("inferenceMode"), 1, "Inference mode is not turned on.") # make sure we can access all the parameters with getParameter self.assertEqual(classifier.getParameter("maxCategoryCount"), 2000) self.assertAlmostEqual(float(classifier.getParameter("alpha")), 0.001) self.assertEqual(int(classifier.getParameter("steps")), 0) self.assertTrue(classifier.getParameter("implementation") == "py") self.assertEqual(classifier.getParameter("verbosity"), 0) expectedCats = ( [0.0], [1.0], [0.0], [1.0], [0.0], [1.0], [0.0], [1.0], ) dataSource.rewind() for i in xrange(8): net.run(1) inferredCats = classifier.getOutputData("categoriesOut") self.assertSequenceEqual( expectedCats[i], inferredCats.tolist(), "Classififer did not infer expected category " "for record number {}.".format(i)) # Close data stream, delete file. dataSource.close() os.remove(filename)
def _generateSimple(filename="simple.csv", numSequences=1, elementsPerSeq=3, numRepeats=10): """ Generate a simple dataset. This contains a bunch of non-overlapping sequences. At the end of the dataset, we introduce missing records so that test code can insure that the model didn't get confused by them. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output """ # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print "Creating %s..." % (pathname) fields = [('timestamp', 'datetime', 'T'), ('field1', 'string', ''), ('field2', 'float', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences sequences = [] for i in range(numSequences): seq = [x for x in range(i*elementsPerSeq, (i+1)*elementsPerSeq)] sequences.append(seq) # Write out the sequences in random order seqIdxs = [] for i in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) # Put 1 hour between each record timestamp = datetime.datetime(year=2012, month=1, day=1, hour=0, minute=0, second=0) timeDelta = datetime.timedelta(hours=1) # Write out the sequences without missing records for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta # Now, write some out with missing records for seqIdx in seqIdxs: seq = sequences[seqIdx] for i,x in enumerate(seq): if i != 1: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta for seqIdx in seqIdxs: seq = sequences[seqIdx] for i,x in enumerate(seq): if i != 1: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta # Write out some more of the sequences *without* missing records for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta outFile.close()
def _generateSimple(filename="simple.csv", numSequences=1, elementsPerSeq=3, numRepeats=10): """ Generate a simple dataset. This contains a bunch of non-overlapping sequences. At the end of the dataset, we introduce missing records so that test code can insure that the model didn't get confused by them. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output """ # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print "Creating %s..." % (pathname) fields = [('timestamp', 'datetime', 'T'), ('field1', 'string', ''), ('field2', 'float', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences sequences = [] for i in range(numSequences): seq = [x for x in range(i * elementsPerSeq, (i + 1) * elementsPerSeq)] sequences.append(seq) # Write out the sequences in random order seqIdxs = [] for i in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) # Put 1 hour between each record timestamp = datetime.datetime(year=2012, month=1, day=1, hour=0, minute=0, second=0) timeDelta = datetime.timedelta(hours=1) # Write out the sequences without missing records for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta # Now, write some out with missing records for seqIdx in seqIdxs: seq = sequences[seqIdx] for i, x in enumerate(seq): if i != 1: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta for seqIdx in seqIdxs: seq = sequences[seqIdx] for i, x in enumerate(seq): if i != 1: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta # Write out some more of the sequences *without* missing records for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta outFile.close()
def testMissingValues(self): print "Beginning Missing Data test..." filename = _getTempFileName() # Some values missing of each type # read dataset from disk, retrieve values # string should return empty string, numeric types sentinelValue print "Creating tempfile:", filename # write dataset to disk with float, int, and string fields fields = [("timestamp", "datetime", "T"), ("name", "string", ""), ("integer", "int", ""), ("real", "float", "")] s = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ( [datetime(day=1, month=3, year=2010), "rec_1", 5, 6.5], [datetime(day=2, month=3, year=2010), "", 8, 7.5], [datetime(day=3, month=3, year=2010), "rec_3", "", 8.5], [datetime(day=4, month=3, year=2010), "rec_4", 12, ""], [datetime(day=5, month=3, year=2010), "rec_5", -87657496599, 6.5], [datetime(day=6, month=3, year=2010), "rec_6", 12, -87657496599], [datetime(day=6, month=3, year=2010), str(-87657496599), 12, 6.5], ) for r in records: s.appendRecord(list(r)) s.close() # Read the standard file s = FileRecordStream(streamID=filename, write=False) fieldsRead = s.getFields() self.assertEqual(fields, fieldsRead) recordsRead = [] while True: r = s.getNextRecord() if r is None: break print "Reading record ..." print r recordsRead.append(r) # sort the records by date, so we know for sure which is which sorted(recordsRead, key=lambda rec: rec[0]) # empty string self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[1][1]) # missing int self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[2][2]) # missing float self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[3][3]) # sentinel value in input handled correctly for int field self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[4][2]) # sentinel value in input handled correctly for float field self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[5][3]) # sentinel value in input handled correctly for string field # this should leave the string as-is, since a missing string # is encoded not with a sentinel value but with an empty string self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[6][1])