Search is not available for this dataset
text
stringlengths
75
104k
def save_vocab(count=None, name='vocab.txt'): """Save the vocabulary to a file so the model can be reloaded. Parameters ---------- count : a list of tuple and list count[0] is a list : the number of rare words, count[1:] are tuples : the number of occurrence of each word, e.g. [['UNK', 418391], (b'the', 1061396), (b'of', 593677), (b'and', 416629), (b'one', 411764)] Examples --------- >>> words = tl.files.load_matt_mahoney_text8_dataset() >>> vocabulary_size = 50000 >>> data, count, dictionary, reverse_dictionary = tl.nlp.build_words_dataset(words, vocabulary_size, True) >>> tl.nlp.save_vocab(count, name='vocab_text8.txt') >>> vocab_text8.txt UNK 418391 the 1061396 of 593677 and 416629 one 411764 in 372201 a 325873 to 316376 """ if count is None: count = [] pwd = os.getcwd() vocabulary_size = len(count) with open(os.path.join(pwd, name), "w") as f: for i in xrange(vocabulary_size): f.write("%s %d\n" % (tf.compat.as_text(count[i][0]), count[i][1])) tl.logging.info("%d vocab saved to %s in %s" % (vocabulary_size, name, pwd))
def basic_tokenizer(sentence, _WORD_SPLIT=re.compile(b"([.,!?\"':;)(])")): """Very basic tokenizer: split the sentence into a list of tokens. Parameters ----------- sentence : tensorflow.python.platform.gfile.GFile Object _WORD_SPLIT : regular expression for word spliting. Examples -------- >>> see create_vocabulary >>> from tensorflow.python.platform import gfile >>> train_path = "wmt/giga-fren.release2" >>> with gfile.GFile(train_path + ".en", mode="rb") as f: >>> for line in f: >>> tokens = tl.nlp.basic_tokenizer(line) >>> tl.logging.info(tokens) >>> exit() [b'Changing', b'Lives', b'|', b'Changing', b'Society', b'|', b'How', b'It', b'Works', b'|', b'Technology', b'Drives', b'Change', b'Home', b'|', b'Concepts', b'|', b'Teachers', b'|', b'Search', b'|', b'Overview', b'|', b'Credits', b'|', b'HHCC', b'Web', b'|', b'Reference', b'|', b'Feedback', b'Virtual', b'Museum', b'of', b'Canada', b'Home', b'Page'] References ---------- - Code from ``/tensorflow/models/rnn/translation/data_utils.py`` """ words = [] sentence = tf.compat.as_bytes(sentence) for space_separated_fragment in sentence.strip().split(): words.extend(re.split(_WORD_SPLIT, space_separated_fragment)) return [w for w in words if w]
def create_vocabulary( vocabulary_path, data_path, max_vocabulary_size, tokenizer=None, normalize_digits=True, _DIGIT_RE=re.compile(br"\d"), _START_VOCAB=None ): r"""Create vocabulary file (if it does not exist yet) from data file. Data file is assumed to contain one sentence per line. Each sentence is tokenized and digits are normalized (if normalize_digits is set). Vocabulary contains the most-frequent tokens up to max_vocabulary_size. We write it to vocabulary_path in a one-token-per-line format, so that later token in the first line gets id=0, second line gets id=1, and so on. Parameters ----------- vocabulary_path : str Path where the vocabulary will be created. data_path : str Data file that will be used to create vocabulary. max_vocabulary_size : int Limit on the size of the created vocabulary. tokenizer : function A function to use to tokenize each data sentence. If None, basic_tokenizer will be used. normalize_digits : boolean If true, all digits are replaced by `0`. _DIGIT_RE : regular expression function Default is ``re.compile(br"\d")``. _START_VOCAB : list of str The pad, go, eos and unk token, default is ``[b"_PAD", b"_GO", b"_EOS", b"_UNK"]``. References ---------- - Code from ``/tensorflow/models/rnn/translation/data_utils.py`` """ if _START_VOCAB is None: _START_VOCAB = [b"_PAD", b"_GO", b"_EOS", b"_UNK"] if not gfile.Exists(vocabulary_path): tl.logging.info("Creating vocabulary %s from data %s" % (vocabulary_path, data_path)) vocab = {} with gfile.GFile(data_path, mode="rb") as f: counter = 0 for line in f: counter += 1 if counter % 100000 == 0: tl.logging.info(" processing line %d" % counter) tokens = tokenizer(line) if tokenizer else basic_tokenizer(line) for w in tokens: word = re.sub(_DIGIT_RE, b"0", w) if normalize_digits else w if word in vocab: vocab[word] += 1 else: vocab[word] = 1 vocab_list = _START_VOCAB + sorted(vocab, key=vocab.get, reverse=True) if len(vocab_list) > max_vocabulary_size: vocab_list = vocab_list[:max_vocabulary_size] with gfile.GFile(vocabulary_path, mode="wb") as vocab_file: for w in vocab_list: vocab_file.write(w + b"\n") else: tl.logging.info("Vocabulary %s from data %s exists" % (vocabulary_path, data_path))
def initialize_vocabulary(vocabulary_path): """Initialize vocabulary from file, return the `word_to_id` (dictionary) and `id_to_word` (list). We assume the vocabulary is stored one-item-per-line, so a file will result in a vocabulary {"dog": 0, "cat": 1}, and this function will also return the reversed-vocabulary ["dog", "cat"]. Parameters ----------- vocabulary_path : str Path to the file containing the vocabulary. Returns -------- vocab : dictionary a dictionary that maps word to ID. rev_vocab : list of int a list that maps ID to word. Examples --------- >>> Assume 'test' contains dog cat bird >>> vocab, rev_vocab = tl.nlp.initialize_vocabulary("test") >>> print(vocab) >>> {b'cat': 1, b'dog': 0, b'bird': 2} >>> print(rev_vocab) >>> [b'dog', b'cat', b'bird'] Raises ------- ValueError : if the provided vocabulary_path does not exist. """ if gfile.Exists(vocabulary_path): rev_vocab = [] with gfile.GFile(vocabulary_path, mode="rb") as f: rev_vocab.extend(f.readlines()) rev_vocab = [tf.compat.as_bytes(line.strip()) for line in rev_vocab] vocab = dict([(x, y) for (y, x) in enumerate(rev_vocab)]) return vocab, rev_vocab else: raise ValueError("Vocabulary file %s not found.", vocabulary_path)
def sentence_to_token_ids( sentence, vocabulary, tokenizer=None, normalize_digits=True, UNK_ID=3, _DIGIT_RE=re.compile(br"\d") ): """Convert a string to list of integers representing token-ids. For example, a sentence "I have a dog" may become tokenized into ["I", "have", "a", "dog"] and with vocabulary {"I": 1, "have": 2, "a": 4, "dog": 7"} this function will return [1, 2, 4, 7]. Parameters ----------- sentence : tensorflow.python.platform.gfile.GFile Object The sentence in bytes format to convert to token-ids, see ``basic_tokenizer()`` and ``data_to_token_ids()``. vocabulary : dictionary Mmapping tokens to integers. tokenizer : function A function to use to tokenize each sentence. If None, ``basic_tokenizer`` will be used. normalize_digits : boolean If true, all digits are replaced by 0. Returns -------- list of int The token-ids for the sentence. """ if tokenizer: words = tokenizer(sentence) else: words = basic_tokenizer(sentence) if not normalize_digits: return [vocabulary.get(w, UNK_ID) for w in words] # Normalize digits by 0 before looking words up in the vocabulary. return [vocabulary.get(re.sub(_DIGIT_RE, b"0", w), UNK_ID) for w in words]
def data_to_token_ids( data_path, target_path, vocabulary_path, tokenizer=None, normalize_digits=True, UNK_ID=3, _DIGIT_RE=re.compile(br"\d") ): """Tokenize data file and turn into token-ids using given vocabulary file. This function loads data line-by-line from data_path, calls the above sentence_to_token_ids, and saves the result to target_path. See comment for sentence_to_token_ids on the details of token-ids format. Parameters ----------- data_path : str Path to the data file in one-sentence-per-line format. target_path : str Path where the file with token-ids will be created. vocabulary_path : str Path to the vocabulary file. tokenizer : function A function to use to tokenize each sentence. If None, ``basic_tokenizer`` will be used. normalize_digits : boolean If true, all digits are replaced by 0. References ---------- - Code from ``/tensorflow/models/rnn/translation/data_utils.py`` """ if not gfile.Exists(target_path): tl.logging.info("Tokenizing data in %s" % data_path) vocab, _ = initialize_vocabulary(vocabulary_path) with gfile.GFile(data_path, mode="rb") as data_file: with gfile.GFile(target_path, mode="w") as tokens_file: counter = 0 for line in data_file: counter += 1 if counter % 100000 == 0: tl.logging.info(" tokenizing line %d" % counter) token_ids = sentence_to_token_ids( line, vocab, tokenizer, normalize_digits, UNK_ID=UNK_ID, _DIGIT_RE=_DIGIT_RE ) tokens_file.write(" ".join([str(tok) for tok in token_ids]) + "\n") else: tl.logging.info("Target path %s exists" % target_path)
def moses_multi_bleu(hypotheses, references, lowercase=False): """Calculate the bleu score for hypotheses and references using the MOSES ulti-bleu.perl script. Parameters ------------ hypotheses : numpy.array.string A numpy array of strings where each string is a single example. references : numpy.array.string A numpy array of strings where each string is a single example. lowercase : boolean If True, pass the "-lc" flag to the multi-bleu script Examples --------- >>> hypotheses = ["a bird is flying on the sky"] >>> references = ["two birds are flying on the sky", "a bird is on the top of the tree", "an airplane is on the sky",] >>> score = tl.nlp.moses_multi_bleu(hypotheses, references) Returns -------- float The BLEU score References ---------- - `Google/seq2seq/metric/bleu <https://github.com/google/seq2seq>`__ """ if np.size(hypotheses) == 0: return np.float32(0.0) # Get MOSES multi-bleu script try: multi_bleu_path, _ = urllib.request.urlretrieve( "https://raw.githubusercontent.com/moses-smt/mosesdecoder/" "master/scripts/generic/multi-bleu.perl" ) os.chmod(multi_bleu_path, 0o755) except Exception: # pylint: disable=W0702 tl.logging.info("Unable to fetch multi-bleu.perl script, using local.") metrics_dir = os.path.dirname(os.path.realpath(__file__)) bin_dir = os.path.abspath(os.path.join(metrics_dir, "..", "..", "bin")) multi_bleu_path = os.path.join(bin_dir, "tools/multi-bleu.perl") # Dump hypotheses and references to tempfiles hypothesis_file = tempfile.NamedTemporaryFile() hypothesis_file.write("\n".join(hypotheses).encode("utf-8")) hypothesis_file.write(b"\n") hypothesis_file.flush() reference_file = tempfile.NamedTemporaryFile() reference_file.write("\n".join(references).encode("utf-8")) reference_file.write(b"\n") reference_file.flush() # Calculate BLEU using multi-bleu script with open(hypothesis_file.name, "r") as read_pred: bleu_cmd = [multi_bleu_path] if lowercase: bleu_cmd += ["-lc"] bleu_cmd += [reference_file.name] try: bleu_out = subprocess.check_output(bleu_cmd, stdin=read_pred, stderr=subprocess.STDOUT) bleu_out = bleu_out.decode("utf-8") bleu_score = re.search(r"BLEU = (.+?),", bleu_out).group(1) bleu_score = float(bleu_score) except subprocess.CalledProcessError as error: if error.output is not None: tl.logging.warning("multi-bleu.perl script returned non-zero exit code") tl.logging.warning(error.output) bleu_score = np.float32(0.0) # Close temp files hypothesis_file.close() reference_file.close() return np.float32(bleu_score)
def word_to_id(self, word): """Returns the integer id of a word string.""" if word in self._vocab: return self._vocab[word] else: return self._unk_id
def word_to_id(self, word): """Returns the integer word id of a word string.""" if word in self.vocab: return self.vocab[word] else: return self.unk_id
def id_to_word(self, word_id): """Returns the word string of an integer word id.""" if word_id >= len(self.reverse_vocab): return self.reverse_vocab[self.unk_id] else: return self.reverse_vocab[word_id]
def basic_clean_str(string): """Tokenization/string cleaning for a datasets.""" string = re.sub(r"\n", " ", string) # '\n' --> ' ' string = re.sub(r"\'s", " \'s", string) # it's --> it 's string = re.sub(r"\’s", " \'s", string) string = re.sub(r"\'ve", " have", string) # they've --> they have string = re.sub(r"\’ve", " have", string) string = re.sub(r"\'t", " not", string) # can't --> can not string = re.sub(r"\’t", " not", string) string = re.sub(r"\'re", " are", string) # they're --> they are string = re.sub(r"\’re", " are", string) string = re.sub(r"\'d", "", string) # I'd (I had, I would) --> I string = re.sub(r"\’d", "", string) string = re.sub(r"\'ll", " will", string) # I'll --> I will string = re.sub(r"\’ll", " will", string) string = re.sub(r"\“", " ", string) # “a” --> “ a ” string = re.sub(r"\”", " ", string) string = re.sub(r"\"", " ", string) # "a" --> " a " string = re.sub(r"\'", " ", string) # they' --> they ' string = re.sub(r"\’", " ", string) # they’ --> they ’ string = re.sub(r"\.", " . ", string) # they. --> they . string = re.sub(r"\,", " , ", string) # they, --> they , string = re.sub(r"\!", " ! ", string) string = re.sub(r"\-", " ", string) # "low-cost"--> lost cost string = re.sub(r"\(", " ", string) # (they) --> ( they) string = re.sub(r"\)", " ", string) # ( they) --> ( they ) string = re.sub(r"\]", " ", string) # they] --> they ] string = re.sub(r"\[", " ", string) # they[ --> they [ string = re.sub(r"\?", " ", string) # they? --> they ? string = re.sub(r"\>", " ", string) # they> --> they > string = re.sub(r"\<", " ", string) # they< --> they < string = re.sub(r"\=", " ", string) # easier= --> easier = string = re.sub(r"\;", " ", string) # easier; --> easier ; string = re.sub(r"\;", " ", string) string = re.sub(r"\:", " ", string) # easier: --> easier : string = re.sub(r"\"", " ", string) # easier" --> easier " string = re.sub(r"\$", " ", string) # $380 --> $ 380 string = re.sub(r"\_", " ", string) # _100 --> _ 100 string = re.sub(r"\s{2,}", " ", string) # Akara is handsome --> Akara is handsome return string.strip().lower()
def main_restore_embedding_layer(): """How to use Embedding layer, and how to convert IDs to vector, IDs to words, etc. """ # Step 1: Build the embedding matrix and load the existing embedding matrix. vocabulary_size = 50000 embedding_size = 128 model_file_name = "model_word2vec_50k_128" batch_size = None print("Load existing embedding matrix and dictionaries") all_var = tl.files.load_npy_to_any(name=model_file_name + '.npy') data = all_var['data'] count = all_var['count'] dictionary = all_var['dictionary'] reverse_dictionary = all_var['reverse_dictionary'] tl.nlp.save_vocab(count, name='vocab_' + model_file_name + '.txt') del all_var, data, count load_params = tl.files.load_npz(name=model_file_name + '.npz') x = tf.placeholder(tf.int32, shape=[batch_size]) emb_net = tl.layers.EmbeddingInputlayer(x, vocabulary_size, embedding_size, name='emb') # sess.run(tf.global_variables_initializer()) sess.run(tf.global_variables_initializer()) tl.files.assign_params(sess, [load_params[0]], emb_net) emb_net.print_params() emb_net.print_layers() # Step 2: Input word(s), output the word vector(s). word = b'hello' word_id = dictionary[word] print('word_id:', word_id) words = [b'i', b'am', b'tensor', b'layer'] word_ids = tl.nlp.words_to_word_ids(words, dictionary, _UNK) context = tl.nlp.word_ids_to_words(word_ids, reverse_dictionary) print('word_ids:', word_ids) print('context:', context) vector = sess.run(emb_net.outputs, feed_dict={x: [word_id]}) print('vector:', vector.shape) vectors = sess.run(emb_net.outputs, feed_dict={x: word_ids}) print('vectors:', vectors.shape)
def main_lstm_generate_text(): """Generate text by Synced sequence input and output.""" # rnn model and update (describtion: see tutorial_ptb_lstm.py) init_scale = 0.1 learning_rate = 1.0 max_grad_norm = 5 sequence_length = 20 hidden_size = 200 max_epoch = 4 max_max_epoch = 100 lr_decay = 0.9 batch_size = 20 top_k_list = [1, 3, 5, 10] print_length = 30 model_file_name = "model_generate_text.npz" # ===== Prepare Data words = customized_read_words(input_fpath="data/trump/trump_text.txt") vocab = tl.nlp.create_vocab([words], word_counts_output_file='vocab.txt', min_word_count=1) vocab = tl.nlp.Vocabulary('vocab.txt', unk_word="<UNK>") vocab_size = vocab.unk_id + 1 train_data = [vocab.word_to_id(word) for word in words] # Set the seed to generate sentence. seed = "it is a" # seed = basic_clean_str(seed).split() seed = nltk.tokenize.word_tokenize(seed) print('seed : %s' % seed) sess = tf.InteractiveSession() # ===== Define model input_data = tf.placeholder(tf.int32, [batch_size, sequence_length]) targets = tf.placeholder(tf.int32, [batch_size, sequence_length]) # Testing (Evaluation), for generate text input_data_test = tf.placeholder(tf.int32, [1, 1]) def inference(x, is_train, sequence_length, reuse=None): """If reuse is True, the inferences use the existing parameters, then different inferences share the same parameters. """ print("\nsequence_length: %d, is_train: %s, reuse: %s" % (sequence_length, is_train, reuse)) rnn_init = tf.random_uniform_initializer(-init_scale, init_scale) with tf.variable_scope("model", reuse=reuse): network = EmbeddingInputlayer(x, vocab_size, hidden_size, rnn_init, name='embedding') network = RNNLayer( network, cell_fn=tf.contrib.rnn.BasicLSTMCell, cell_init_args={ 'forget_bias': 0.0, 'state_is_tuple': True }, n_hidden=hidden_size, initializer=rnn_init, n_steps=sequence_length, return_last=False, return_seq_2d=True, name='lstm1' ) lstm1 = network network = DenseLayer(network, vocab_size, W_init=rnn_init, b_init=rnn_init, act=None, name='output') return network, lstm1 # Inference for Training network, lstm1 = inference(input_data, is_train=True, sequence_length=sequence_length, reuse=None) # Inference for generate text, sequence_length=1 network_test, lstm1_test = inference(input_data_test, is_train=False, sequence_length=1, reuse=True) y_linear = network_test.outputs y_soft = tf.nn.softmax(y_linear) # y_id = tf.argmax(tf.nn.softmax(y), 1) # ===== Define train ops def loss_fn(outputs, targets, batch_size, sequence_length): # Returns the cost function of Cross-entropy of two sequences, implement # softmax internally. # outputs : 2D tensor [n_examples, n_outputs] # targets : 2D tensor [n_examples, n_outputs] # n_examples = batch_size * sequence_length # so # cost is the averaged cost of each mini-batch (concurrent process). loss = tf.contrib.legacy_seq2seq.sequence_loss_by_example( [outputs], [tf.reshape(targets, [-1])], [tf.ones([batch_size * sequence_length])] ) cost = tf.reduce_sum(loss) / batch_size return cost # Cost for Training cost = loss_fn(network.outputs, targets, batch_size, sequence_length) # Truncated Backpropagation for training with tf.variable_scope('learning_rate'): lr = tf.Variable(0.0, trainable=False) # You can get all trainable parameters as follow. # tvars = tf.trainable_variables() # Alternatively, you can specify the parameters for training as follw. # tvars = network.all_params $ all parameters # tvars = network.all_params[1:] $ parameters except embedding matrix # Train the whole network. tvars = network.all_params grads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars), max_grad_norm) optimizer = tf.train.GradientDescentOptimizer(lr) train_op = optimizer.apply_gradients(zip(grads, tvars)) # ===== Training sess.run(tf.global_variables_initializer()) print("\nStart learning a model to generate text") for i in range(max_max_epoch): # decrease the learning_rate after ``max_epoch``, by multipling lr_decay. new_lr_decay = lr_decay**max(i - max_epoch, 0.0) sess.run(tf.assign(lr, learning_rate * new_lr_decay)) print("Epoch: %d/%d Learning rate: %.8f" % (i + 1, max_max_epoch, sess.run(lr))) epoch_size = ((len(train_data) // batch_size) - 1) // sequence_length start_time = time.time() costs = 0.0 iters = 0 # reset all states at the begining of every epoch state1 = tl.layers.initialize_rnn_state(lstm1.initial_state) for step, (x, y) in enumerate(tl.iterate.ptb_iterator(train_data, batch_size, sequence_length)): _cost, state1, _ = sess.run( [cost, lstm1.final_state, train_op], feed_dict={ input_data: x, targets: y, lstm1.initial_state: state1 } ) costs += _cost iters += sequence_length if step % (epoch_size // 10) == 1: print( "%.3f perplexity: %.3f speed: %.0f wps" % (step * 1.0 / epoch_size, np.exp(costs / iters), iters * batch_size / (time.time() - start_time)) ) train_perplexity = np.exp(costs / iters) # print("Epoch: %d Train Perplexity: %.3f" % (i + 1, train_perplexity)) print("Epoch: %d/%d Train Perplexity: %.3f" % (i + 1, max_max_epoch, train_perplexity)) # for diversity in diversity_list: # testing: sample from top k words for top_k in top_k_list: # Testing, generate some text from a given seed. state1 = tl.layers.initialize_rnn_state(lstm1_test.initial_state) # state2 = tl.layers.initialize_rnn_state(lstm2_test.initial_state) outs_id = [vocab.word_to_id(w) for w in seed] # feed the seed to initialize the state for generation. for ids in outs_id[:-1]: a_id = np.asarray(ids).reshape(1, 1) state1 = sess.run( [lstm1_test.final_state], feed_dict={ input_data_test: a_id, lstm1_test.initial_state: state1 } ) # feed the last word in seed, and start to generate sentence. a_id = outs_id[-1] for _ in range(print_length): a_id = np.asarray(a_id).reshape(1, 1) out, state1 = sess.run( [y_soft, lstm1_test.final_state], feed_dict={ input_data_test: a_id, lstm1_test.initial_state: state1 } ) # Without sampling # a_id = np.argmax(out[0]) # Sample from all words, if vocab_size is large, # this may have numeric error. # a_id = tl.nlp.sample(out[0], diversity) # Sample from the top k words. a_id = tl.nlp.sample_top(out[0], top_k=top_k) outs_id.append(a_id) sentence = [vocab.id_to_word(w) for w in outs_id] sentence = " ".join(sentence) # print(diversity, ':', sentence) print(top_k, ':', sentence) print("Save model") tl.files.save_npz(network_test.all_params, name=model_file_name)
def createAndStartSwarm(client, clientInfo="", clientKey="", params="", minimumWorkers=None, maximumWorkers=None, alreadyRunning=False): """Create and start a swarm job. Args: client - A string identifying the calling client. There is a small limit for the length of the value. See ClientJobsDAO.CLIENT_MAX_LEN. clientInfo - JSON encoded dict of client specific information. clientKey - Foreign key. Limited in length, see ClientJobsDAO._initTables. params - JSON encoded dict of the parameters for the job. This can be fetched out of the database by the worker processes based on the jobID. minimumWorkers - The minimum workers to allocate to the swarm. Set to None to use the default. maximumWorkers - The maximum workers to allocate to the swarm. Set to None to use the swarm default. Set to 0 to use the maximum scheduler value. alreadyRunning - Insert a job record for an already running process. Used for testing. """ if minimumWorkers is None: minimumWorkers = Configuration.getInt( "nupic.hypersearch.minWorkersPerSwarm") if maximumWorkers is None: maximumWorkers = Configuration.getInt( "nupic.hypersearch.maxWorkersPerSwarm") return ClientJobsDAO.get().jobInsert( client=client, cmdLine="$HYPERSEARCH", clientInfo=clientInfo, clientKey=clientKey, alreadyRunning=alreadyRunning, params=params, minimumWorkers=minimumWorkers, maximumWorkers=maximumWorkers, jobType=ClientJobsDAO.JOB_TYPE_HS)
def getSwarmModelParams(modelID): """Retrieve the Engine-level model params from a Swarm model Args: modelID - Engine-level model ID of the Swarm model Returns: JSON-encoded string containing Model Params """ # TODO: the use of nupic.frameworks.opf.helpers.loadExperimentDescriptionScriptFromDir when # retrieving module params results in a leakage of pf_base_descriptionNN and # pf_descriptionNN module imports for every call to getSwarmModelParams, so # the leakage is unlimited when getSwarmModelParams is called by a # long-running process. An alternate solution is to execute the guts of # this function's logic in a seprate process (via multiprocessing module). cjDAO = ClientJobsDAO.get() (jobID, description) = cjDAO.modelsGetFields( modelID, ["jobId", "genDescription"]) (baseDescription,) = cjDAO.jobGetFields(jobID, ["genBaseDescription"]) # Construct a directory with base.py and description.py for loading model # params, and use nupic.frameworks.opf.helpers to extract model params from # those files descriptionDirectory = tempfile.mkdtemp() try: baseDescriptionFilePath = os.path.join(descriptionDirectory, "base.py") with open(baseDescriptionFilePath, mode="wb") as f: f.write(baseDescription) descriptionFilePath = os.path.join(descriptionDirectory, "description.py") with open(descriptionFilePath, mode="wb") as f: f.write(description) expIface = helpers.getExperimentDescriptionInterfaceFromModule( helpers.loadExperimentDescriptionScriptFromDir(descriptionDirectory)) return json.dumps( dict( modelConfig=expIface.getModelDescription(), inferenceArgs=expIface.getModelControl().get("inferenceArgs", None))) finally: shutil.rmtree(descriptionDirectory, ignore_errors=True)
def enableConcurrencyChecks(maxConcurrency, raiseException=True): """ Enable the diagnostic feature for debugging unexpected concurrency in acquiring ConnectionWrapper instances. NOTE: This MUST be done early in your application's execution, BEFORE any accesses to ConnectionFactory or connection policies from your application (including imports and sub-imports of your app). Parameters: ---------------------------------------------------------------- maxConcurrency: A non-negative integer that represents the maximum expected number of outstanding connections. When this value is exceeded, useful information will be logged and, depending on the value of the raiseException arg, ConcurrencyExceededError may be raised. raiseException: If true, ConcurrencyExceededError will be raised when maxConcurrency is exceeded. """ global g_max_concurrency, g_max_concurrency_raise_exception assert maxConcurrency >= 0 g_max_concurrency = maxConcurrency g_max_concurrency_raise_exception = raiseException return
def _getCommonSteadyDBArgsDict(): """ Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection constructor. """ return dict( creator = pymysql, host = Configuration.get('nupic.cluster.database.host'), port = int(Configuration.get('nupic.cluster.database.port')), user = Configuration.get('nupic.cluster.database.user'), passwd = Configuration.get('nupic.cluster.database.passwd'), charset = 'utf8', use_unicode = True, setsession = ['SET AUTOCOMMIT = 1'])
def _getLogger(cls, logLevel=None): """ Gets a logger for the given class in this module """ logger = logging.getLogger( ".".join(['com.numenta', _MODULE_NAME, cls.__name__])) if logLevel is not None: logger.setLevel(logLevel) return logger
def get(cls): """ Acquire a ConnectionWrapper instance that represents a connection to the SQL server per nupic.cluster.database.* configuration settings. NOTE: caller is responsible for calling the ConnectionWrapper instance's release() method after using the connection in order to release resources. Better yet, use the returned ConnectionWrapper instance in a Context Manager statement for automatic invocation of release(): Example: # If using Jython 2.5.x, first import with_statement at the very top of your script (don't need this import for Jython/Python 2.6.x and later): from __future__ import with_statement # Then: from nupic.database.Connection import ConnectionFactory # Then use it like this with ConnectionFactory.get() as conn: conn.cursor.execute("SELECT ...") conn.cursor.fetchall() conn.cursor.execute("INSERT ...") WARNING: DO NOT close the underlying connection or cursor as it may be shared by other modules in your process. ConnectionWrapper's release() method will do the right thing. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for releasing resources as described above. """ if cls._connectionPolicy is None: logger = _getLogger(cls) logger.info("Creating db connection policy via provider %r", cls._connectionPolicyInstanceProvider) cls._connectionPolicy = cls._connectionPolicyInstanceProvider() logger.debug("Created connection policy: %r", cls._connectionPolicy) return cls._connectionPolicy.acquireConnection()
def _createDefaultPolicy(cls): """ [private] Create the default database connection policy instance Parameters: ---------------------------------------------------------------- retval: The default database connection policy instance """ logger = _getLogger(cls) logger.debug( "Creating database connection policy: platform=%r; pymysql.VERSION=%r", platform.system(), pymysql.VERSION) if platform.system() == "Java": # NOTE: PooledDB doesn't seem to work under Jython # NOTE: not appropriate for multi-threaded applications. # TODO: this was fixed in Webware DBUtils r8228, so once # we pick up a realease with this fix, we should use # PooledConnectionPolicy for both Jython and Python. policy = SingleSharedConnectionPolicy() else: policy = PooledConnectionPolicy() return policy
def release(self): """ Release the database connection and cursor The receiver of the Connection instance MUST call this method in order to reclaim resources """ self._logger.debug("Releasing: %r", self) # Discard self from set of outstanding instances if self._addedToInstanceSet: try: self._clsOutstandingInstances.remove(self) except: self._logger.exception( "Failed to remove self from _clsOutstandingInstances: %r;", self) raise self._releaser(dbConn=self.dbConn, cursor=self.cursor) self.__class__._clsNumOutstanding -= 1 assert self._clsNumOutstanding >= 0, \ "_clsNumOutstanding=%r" % (self._clsNumOutstanding,) self._releaser = None self.cursor = None self.dbConn = None self._creationTracebackString = None self._addedToInstanceSet = False self._logger = None return
def _trackInstanceAndCheckForConcurrencyViolation(self): """ Check for concurrency violation and add self to _clsOutstandingInstances. ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is incremented """ global g_max_concurrency, g_max_concurrency_raise_exception assert g_max_concurrency is not None assert self not in self._clsOutstandingInstances, repr(self) # Populate diagnostic info self._creationTracebackString = traceback.format_stack() # Check for concurrency violation if self._clsNumOutstanding >= g_max_concurrency: # NOTE: It's possible for _clsNumOutstanding to be greater than # len(_clsOutstandingInstances) if concurrency check was enabled after # unrelease allocations. errorMsg = ("With numOutstanding=%r, exceeded concurrency limit=%r " "when requesting %r. OTHER TRACKED UNRELEASED " "INSTANCES (%s): %r") % ( self._clsNumOutstanding, g_max_concurrency, self, len(self._clsOutstandingInstances), self._clsOutstandingInstances,) self._logger.error(errorMsg) if g_max_concurrency_raise_exception: raise ConcurrencyExceededError(errorMsg) # Add self to tracked instance set self._clsOutstandingInstances.add(self) self._addedToInstanceSet = True return
def close(self): """ Close the policy instance and its shared database connection. """ self._logger.info("Closing") if self._conn is not None: self._conn.close() self._conn = None else: self._logger.warning( "close() called, but connection policy was alredy closed") return
def acquireConnection(self): """ Get a Connection instance. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's release() method or use it in a context manager expression (with ... as:) to release resources. """ self._logger.debug("Acquiring connection") # Check connection and attempt to re-establish it if it died (this is # what PooledDB does) self._conn._ping_check() connWrap = ConnectionWrapper(dbConn=self._conn, cursor=self._conn.cursor(), releaser=self._releaseConnection, logger=self._logger) return connWrap
def close(self): """ Close the policy instance and its database connection pool. """ self._logger.info("Closing") if self._pool is not None: self._pool.close() self._pool = None else: self._logger.warning( "close() called, but connection policy was alredy closed") return
def acquireConnection(self): """ Get a connection from the pool. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's release() method or use it in a context manager expression (with ... as:) to release resources. """ self._logger.debug("Acquiring connection") dbConn = self._pool.connection(shareable=False) connWrap = ConnectionWrapper(dbConn=dbConn, cursor=dbConn.cursor(), releaser=self._releaseConnection, logger=self._logger) return connWrap
def close(self): """ Close the policy instance. """ self._logger.info("Closing") if self._opened: self._opened = False else: self._logger.warning( "close() called, but connection policy was alredy closed") return
def acquireConnection(self): """ Create a Connection instance. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's release() method or use it in a context manager expression (with ... as:) to release resources. """ self._logger.debug("Acquiring connection") dbConn = SteadyDB.connect(** _getCommonSteadyDBArgsDict()) connWrap = ConnectionWrapper(dbConn=dbConn, cursor=dbConn.cursor(), releaser=self._releaseConnection, logger=self._logger) return connWrap
def _releaseConnection(self, dbConn, cursor): """ Release database connection and cursor; passed as a callback to ConnectionWrapper """ self._logger.debug("Releasing connection") # Close the cursor cursor.close() # ... then close the database connection dbConn.close() return
def getSpec(cls): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getSpec`. """ ns = dict( description=KNNAnomalyClassifierRegion.__doc__, singleNodeOnly=True, inputs=dict( spBottomUpOut=dict( description="""The output signal generated from the bottom-up inputs from lower levels.""", dataType='Real32', count=0, required=True, regionLevel=False, isDefaultInput=True, requireSplitterMap=False), tpTopDownOut=dict( description="""The top-down inputsignal, generated from feedback from upper levels""", dataType='Real32', count=0, required=True, regionLevel=False, isDefaultInput=True, requireSplitterMap=False), tpLrnActiveStateT=dict( description="""Active cells in the learn state at time T from TM. This is used to classify on.""", dataType='Real32', count=0, required=True, regionLevel=False, isDefaultInput=True, requireSplitterMap=False), sequenceIdIn=dict( description="Sequence ID", dataType='UInt64', count=1, required=False, regionLevel=True, isDefaultInput=False, requireSplitterMap=False), ), outputs=dict( ), parameters=dict( trainRecords=dict( description='Number of records to wait for training', dataType='UInt32', count=1, constraints='', defaultValue=0, accessMode='Create'), anomalyThreshold=dict( description='Threshold used to classify anomalies.', dataType='Real32', count=1, constraints='', defaultValue=0, accessMode='Create'), cacheSize=dict( description='Number of records to store in cache.', dataType='UInt32', count=1, constraints='', defaultValue=0, accessMode='Create'), classificationVectorType=dict( description="""Vector type to use when classifying. 1 - Vector Column with Difference (TM and SP) """, dataType='UInt32', count=1, constraints='', defaultValue=1, accessMode='ReadWrite'), activeColumnCount=dict( description="""Number of active columns in a given step. Typically equivalent to SP.numActiveColumnsPerInhArea""", dataType='UInt32', count=1, constraints='', defaultValue=40, accessMode='ReadWrite'), classificationMaxDist=dict( description="""Maximum distance a sample can be from an anomaly in the classifier to be labeled as an anomaly. Ex: With rawOverlap distance, a value of 0.65 means that the points must be at most a distance 0.65 apart from each other. This translates to they must be at least 35% similar.""", dataType='Real32', count=1, constraints='', defaultValue=0.65, accessMode='Create' ) ), commands=dict( getLabels=dict(description= "Returns a list of label dicts with properties ROWID and labels." "ROWID corresponds to the records id and labels is a list of " "strings representing the records labels. Takes additional " "integer properties start and end representing the range that " "will be returned."), addLabel=dict(description= "Takes parameters start, end and labelName. Adds the label " "labelName to the records from start to end. This will recalculate " "labels from end to the most recent record."), removeLabels=dict(description= "Takes additional parameters start, end, labelFilter. Start and " "end correspond to range to remove the label. Remove labels from " "each record with record ROWID in range from start to end, " "noninclusive of end. Removes all records if labelFilter is None, " "otherwise only removes the labels eqaul to labelFilter.") ) ) ns['parameters'].update(KNNClassifierRegion.getSpec()['parameters']) return ns
def getParameter(self, name, index=-1): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getParameter`. """ if name == "trainRecords": return self.trainRecords elif name == "anomalyThreshold": return self.anomalyThreshold elif name == "activeColumnCount": return self._activeColumnCount elif name == "classificationMaxDist": return self._classificationMaxDist else: # If any spec parameter name is the same as an attribute, this call # will get it automatically, e.g. self.learningMode return PyRegion.getParameter(self, name, index)
def setParameter(self, name, index, value): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`. """ if name == "trainRecords": # Ensure that the trainRecords can only be set to minimum of the ROWID in # the saved states if not (isinstance(value, float) or isinstance(value, int)): raise HTMPredictionModelInvalidArgument("Invalid argument type \'%s\'. threshold " "must be a number." % (type(value))) if len(self._recordsCache) > 0 and value < self._recordsCache[0].ROWID: raise HTMPredictionModelInvalidArgument("Invalid value. autoDetectWaitRecord " "value must be valid record within output stream. Current minimum " " ROWID in output stream is %d." % (self._recordsCache[0].ROWID)) self.trainRecords = value # Remove any labels before the first cached record (wont be used anymore) self._deleteRangeFromKNN(0, self._recordsCache[0].ROWID) # Reclassify all states self._classifyStates() elif name == "anomalyThreshold": if not (isinstance(value, float) or isinstance(value, int)): raise HTMPredictionModelInvalidArgument("Invalid argument type \'%s\'. threshold " "must be a number." % (type(value))) self.anomalyThreshold = value self._classifyStates() elif name == "classificationMaxDist": if not (isinstance(value, float) or isinstance(value, int)): raise HTMPredictionModelInvalidArgument("Invalid argument type \'%s\'. " "classificationMaxDist must be a number." % (type(value))) self._classificationMaxDist = value self._classifyStates() elif name == "activeColumnCount": self._activeColumnCount = value else: return PyRegion.setParameter(self, name, index, value)
def compute(self, inputs, outputs): """ Process one input sample. This method is called by the runtime engine. """ record = self._constructClassificationRecord(inputs) #Classify this point after waiting the classification delay if record.ROWID >= self.getParameter('trainRecords'): self._classifyState(record) #Save new classification record and keep history as moving window self._recordsCache.append(record) while len(self._recordsCache) > self.cacheSize: self._recordsCache.pop(0) self.labelResults = record.anomalyLabel self._iteration += 1
def _classifyState(self, state): """ Reclassifies given state. """ # Record is before wait period do not classifiy if state.ROWID < self.getParameter('trainRecords'): if not state.setByUser: state.anomalyLabel = [] self._deleteRecordsFromKNN([state]) return label = KNNAnomalyClassifierRegion.AUTO_THRESHOLD_CLASSIFIED_LABEL autoLabel = label + KNNAnomalyClassifierRegion.AUTO_TAG # Update the label based on classifications newCategory = self._recomputeRecordFromKNN(state) labelList = self._categoryToLabelList(newCategory) if state.setByUser: if label in state.anomalyLabel: state.anomalyLabel.remove(label) if autoLabel in state.anomalyLabel: state.anomalyLabel.remove(autoLabel) labelList.extend(state.anomalyLabel) # Add threshold classification label if above threshold, else if # classified to add the auto threshold classification. if state.anomalyScore >= self.getParameter('anomalyThreshold'): labelList.append(label) elif label in labelList: ind = labelList.index(label) labelList[ind] = autoLabel # Make all entries unique labelList = list(set(labelList)) # If both above threshold and auto classified above - remove auto label if label in labelList and autoLabel in labelList: labelList.remove(autoLabel) if state.anomalyLabel == labelList: return # Update state's labeling state.anomalyLabel = labelList # Update KNN Classifier with new labeling if state.anomalyLabel == []: self._deleteRecordsFromKNN([state]) else: self._addRecordToKNN(state)
def _constructClassificationRecord(self, inputs): """ Construct a _HTMClassificationRecord based on the state of the model passed in through the inputs. Types for self.classificationVectorType: 1 - TM active cells in learn state 2 - SP columns concatenated with error from TM column predictions and SP """ # Count the number of unpredicted columns allSPColumns = inputs["spBottomUpOut"] activeSPColumns = allSPColumns.nonzero()[0] score = anomaly.computeRawAnomalyScore(activeSPColumns, self._prevPredictedColumns) spSize = len(allSPColumns) allTPCells = inputs['tpTopDownOut'] tpSize = len(inputs['tpLrnActiveStateT']) classificationVector = numpy.array([]) if self.classificationVectorType == 1: # Classification Vector: [---TM Cells---] classificationVector = numpy.zeros(tpSize) activeCellMatrix = inputs["tpLrnActiveStateT"].reshape(tpSize, 1) activeCellIdx = numpy.where(activeCellMatrix > 0)[0] if activeCellIdx.shape[0] > 0: classificationVector[numpy.array(activeCellIdx, dtype=numpy.uint16)] = 1 elif self.classificationVectorType == 2: # Classification Vecotr: [---SP---|---(TM-SP)----] classificationVector = numpy.zeros(spSize+spSize) if activeSPColumns.shape[0] > 0: classificationVector[activeSPColumns] = 1.0 errorColumns = numpy.setdiff1d(self._prevPredictedColumns, activeSPColumns) if errorColumns.shape[0] > 0: errorColumnIndexes = ( numpy.array(errorColumns, dtype=numpy.uint16) + spSize ) classificationVector[errorColumnIndexes] = 1.0 else: raise TypeError("Classification vector type must be either 'tpc' or" " 'sp_tpe', current value is %s" % (self.classificationVectorType)) # Store the state for next time step numPredictedCols = len(self._prevPredictedColumns) predictedColumns = allTPCells.nonzero()[0] self._prevPredictedColumns = copy.deepcopy(predictedColumns) if self._anomalyVectorLength is None: self._anomalyVectorLength = len(classificationVector) result = _CLAClassificationRecord( ROWID=self._iteration, #__numRunCalls called #at beginning of model.run anomalyScore=score, anomalyVector=classificationVector.nonzero()[0].tolist(), anomalyLabel=[] ) return result
def _addRecordToKNN(self, record): """ Adds the record to the KNN classifier. """ knn = self._knnclassifier._knn prototype_idx = self._knnclassifier.getParameter('categoryRecencyList') category = self._labelListToCategoryNumber(record.anomalyLabel) # If record is already in the classifier, overwrite its labeling if record.ROWID in prototype_idx: knn.prototypeSetCategory(record.ROWID, category) return # Learn this pattern in the knn pattern = self._getStateAnomalyVector(record) rowID = record.ROWID knn.learn(pattern, category, rowID=rowID)
def _deleteRecordsFromKNN(self, recordsToDelete): """ Removes the given records from the classifier. parameters ------------ recordsToDelete - list of records to delete from the classififier """ prototype_idx = self._knnclassifier.getParameter('categoryRecencyList') idsToDelete = ([r.ROWID for r in recordsToDelete if not r.setByUser and r.ROWID in prototype_idx]) nProtos = self._knnclassifier._knn._numPatterns self._knnclassifier._knn.removeIds(idsToDelete) assert self._knnclassifier._knn._numPatterns == nProtos - len(idsToDelete)
def _deleteRangeFromKNN(self, start=0, end=None): """ Removes any stored records within the range from start to end. Noninclusive of end. parameters ------------ start - integer representing the ROWID of the start of the deletion range, end - integer representing the ROWID of the end of the deletion range, if None, it will default to end. """ prototype_idx = numpy.array( self._knnclassifier.getParameter('categoryRecencyList')) if end is None: end = prototype_idx.max() + 1 idsIdxToDelete = numpy.logical_and(prototype_idx >= start, prototype_idx < end) idsToDelete = prototype_idx[idsIdxToDelete] nProtos = self._knnclassifier._knn._numPatterns self._knnclassifier._knn.removeIds(idsToDelete.tolist()) assert self._knnclassifier._knn._numPatterns == nProtos - len(idsToDelete)
def _recomputeRecordFromKNN(self, record): """ returns the classified labeling of record """ inputs = { "categoryIn": [None], "bottomUpIn": self._getStateAnomalyVector(record), } outputs = {"categoriesOut": numpy.zeros((1,)), "bestPrototypeIndices":numpy.zeros((1,)), "categoryProbabilitiesOut":numpy.zeros((1,))} # Only use points before record to classify and after the wait period. classifier_indexes = numpy.array( self._knnclassifier.getParameter('categoryRecencyList')) valid_idx = numpy.where( (classifier_indexes >= self.getParameter('trainRecords')) & (classifier_indexes < record.ROWID) )[0].tolist() if len(valid_idx) == 0: return None self._knnclassifier.setParameter('inferenceMode', None, True) self._knnclassifier.setParameter('learningMode', None, False) self._knnclassifier.compute(inputs, outputs) self._knnclassifier.setParameter('learningMode', None, True) classifier_distances = self._knnclassifier.getLatestDistances() valid_distances = classifier_distances[valid_idx] if valid_distances.min() <= self._classificationMaxDist: classifier_indexes_prev = classifier_indexes[valid_idx] rowID = classifier_indexes_prev[valid_distances.argmin()] indexID = numpy.where(classifier_indexes == rowID)[0][0] category = self._knnclassifier.getCategoryList()[indexID] return category return None
def _labelToCategoryNumber(self, label): """ Since the KNN Classifier stores categories as numbers, we must store each label as a number. This method converts from a label to a unique number. Each label is assigned a unique bit so multiple labels may be assigned to a single record. """ if label not in self.saved_categories: self.saved_categories.append(label) return pow(2, self.saved_categories.index(label))
def _labelListToCategoryNumber(self, labelList): """ This method takes a list of labels and returns a unique category number. This enables this class to store a list of categories for each point since the KNN classifier only stores a single number category for each record. """ categoryNumber = 0 for label in labelList: categoryNumber += self._labelToCategoryNumber(label) return categoryNumber
def _categoryToLabelList(self, category): """ Converts a category number into a list of labels """ if category is None: return [] labelList = [] labelNum = 0 while category > 0: if category % 2 == 1: labelList.append(self.saved_categories[labelNum]) labelNum += 1 category = category >> 1 return labelList
def _getStateAnomalyVector(self, state): """ Returns a state's anomaly vertor converting it from spare to dense """ vector = numpy.zeros(self._anomalyVectorLength) vector[state.anomalyVector] = 1 return vector
def getLabels(self, start=None, end=None): """ Get the labels on classified points within range start to end. Not inclusive of end. :returns: (dict) with format: :: { 'isProcessing': boolean, 'recordLabels': list of results } ``isProcessing`` - currently always false as recalculation blocks; used if reprocessing of records is still being performed; Each item in ``recordLabels`` is of format: :: { 'ROWID': id of the row, 'labels': list of strings } """ if len(self._recordsCache) == 0: return { 'isProcessing': False, 'recordLabels': [] } try: start = int(start) except Exception: start = 0 try: end = int(end) except Exception: end = self._recordsCache[-1].ROWID if end <= start: raise HTMPredictionModelInvalidRangeError("Invalid supplied range for 'getLabels'.", debugInfo={ 'requestRange': { 'startRecordID': start, 'endRecordID': end }, 'numRecordsStored': len(self._recordsCache) }) results = { 'isProcessing': False, 'recordLabels': [] } ROWIDX = numpy.array( self._knnclassifier.getParameter('categoryRecencyList')) validIdx = numpy.where((ROWIDX >= start) & (ROWIDX < end))[0].tolist() categories = self._knnclassifier.getCategoryList() for idx in validIdx: row = dict( ROWID=int(ROWIDX[idx]), labels=self._categoryToLabelList(categories[idx])) results['recordLabels'].append(row) return results
def addLabel(self, start, end, labelName): """ Add the label labelName to each record with record ROWID in range from ``start`` to ``end``, noninclusive of end. This will recalculate all points from end to the last record stored in the internal cache of this classifier. :param start: (int) start index :param end: (int) end index (noninclusive) :param labelName: (string) label name """ if len(self._recordsCache) == 0: raise HTMPredictionModelInvalidRangeError("Invalid supplied range for 'addLabel'. " "Model has no saved records.") try: start = int(start) except Exception: start = 0 try: end = int(end) except Exception: end = int(self._recordsCache[-1].ROWID) startID = self._recordsCache[0].ROWID clippedStart = max(0, start - startID) clippedEnd = max(0, min( len( self._recordsCache) , end - startID)) if clippedEnd <= clippedStart: raise HTMPredictionModelInvalidRangeError("Invalid supplied range for 'addLabel'.", debugInfo={ 'requestRange': { 'startRecordID': start, 'endRecordID': end }, 'clippedRequestRange': { 'startRecordID': clippedStart, 'endRecordID': clippedEnd }, 'validRange': { 'startRecordID': startID, 'endRecordID': self._recordsCache[len(self._recordsCache)-1].ROWID }, 'numRecordsStored': len(self._recordsCache) }) # Add label to range [clippedStart, clippedEnd) for state in self._recordsCache[clippedStart:clippedEnd]: if labelName not in state.anomalyLabel: state.anomalyLabel.append(labelName) state.setByUser = True self._addRecordToKNN(state) assert len(self.saved_categories) > 0 # Recompute [end, ...) for state in self._recordsCache[clippedEnd:]: self._classifyState(state)
def removeLabels(self, start=None, end=None, labelFilter=None): """ Remove labels from each record with record ROWID in range from ``start`` to ``end``, noninclusive of end. Removes all records if ``labelFilter`` is None, otherwise only removes the labels equal to ``labelFilter``. This will recalculate all points from end to the last record stored in the internal cache of this classifier. :param start: (int) start index :param end: (int) end index (noninclusive) :param labelFilter: (string) label filter """ if len(self._recordsCache) == 0: raise HTMPredictionModelInvalidRangeError("Invalid supplied range for " "'removeLabels'. Model has no saved records.") try: start = int(start) except Exception: start = 0 try: end = int(end) except Exception: end = self._recordsCache[-1].ROWID startID = self._recordsCache[0].ROWID clippedStart = 0 if start is None else max(0, start - startID) clippedEnd = len(self._recordsCache) if end is None else \ max(0, min( len( self._recordsCache) , end - startID)) if clippedEnd <= clippedStart: raise HTMPredictionModelInvalidRangeError("Invalid supplied range for " "'removeLabels'.", debugInfo={ 'requestRange': { 'startRecordID': start, 'endRecordID': end }, 'clippedRequestRange': { 'startRecordID': clippedStart, 'endRecordID': clippedEnd }, 'validRange': { 'startRecordID': startID, 'endRecordID': self._recordsCache[len(self._recordsCache)-1].ROWID }, 'numRecordsStored': len(self._recordsCache) }) # Remove records within the cache recordsToDelete = [] for state in self._recordsCache[clippedStart:clippedEnd]: if labelFilter is not None: if labelFilter in state.anomalyLabel: state.anomalyLabel.remove(labelFilter) else: state.anomalyLabel = [] state.setByUser = False recordsToDelete.append(state) self._deleteRecordsFromKNN(recordsToDelete) # Remove records not in cache self._deleteRangeFromKNN(start, end) # Recompute [clippedEnd, ...) for state in self._recordsCache[clippedEnd:]: self._classifyState(state)
def match(self, record): ''' Returns True if the record matches any of the provided filters ''' for field, meta in self.filterDict.iteritems(): index = meta['index'] categories = meta['categories'] for category in categories: # Record might be blank, handle this if not record: continue if record[index].find(category) != -1: ''' This field contains the string we're searching for so we'll keep the records ''' return True # None of the categories were found in this record return False
def replace(self, columnIndex, bitmap): """ Wraps replaceSparseRow()""" return super(_SparseMatrixCorticalColumnAdapter, self).replaceSparseRow( columnIndex, bitmap )
def update(self, columnIndex, vector): """ Wraps setRowFromDense()""" return super(_SparseMatrixCorticalColumnAdapter, self).setRowFromDense( columnIndex, vector )
def setLocalAreaDensity(self, localAreaDensity): """ Sets the local area density. Invalidates the 'numActiveColumnsPerInhArea' parameter :param localAreaDensity: (float) value to set """ assert(localAreaDensity > 0 and localAreaDensity <= 1) self._localAreaDensity = localAreaDensity self._numActiveColumnsPerInhArea = 0
def getPotential(self, columnIndex, potential): """ :param columnIndex: (int) column index to get potential for. :param potential: (list) will be overwritten with column potentials. Must match the number of inputs. """ assert(columnIndex < self._numColumns) potential[:] = self._potentialPools[columnIndex]
def setPotential(self, columnIndex, potential): """ Sets the potential mapping for a given column. ``potential`` size must match the number of inputs, and must be greater than ``stimulusThreshold``. :param columnIndex: (int) column index to set potential for. :param potential: (list) value to set. """ assert(columnIndex < self._numColumns) potentialSparse = numpy.where(potential > 0)[0] if len(potentialSparse) < self._stimulusThreshold: raise Exception("This is likely due to a " + "value of stimulusThreshold that is too large relative " + "to the input size.") self._potentialPools.replace(columnIndex, potentialSparse)
def getPermanence(self, columnIndex, permanence): """ Returns the permanence values for a given column. ``permanence`` size must match the number of inputs. :param columnIndex: (int) column index to get permanence for. :param permanence: (list) will be overwritten with permanences. """ assert(columnIndex < self._numColumns) permanence[:] = self._permanences[columnIndex]
def setPermanence(self, columnIndex, permanence): """ Sets the permanence values for a given column. ``permanence`` size must match the number of inputs. :param columnIndex: (int) column index to set permanence for. :param permanence: (list) value to set. """ assert(columnIndex < self._numColumns) self._updatePermanencesForColumn(permanence, columnIndex, raisePerm=False)
def getConnectedSynapses(self, columnIndex, connectedSynapses): """ :param connectedSynapses: (list) will be overwritten :returns: (iter) the connected synapses for a given column. ``connectedSynapses`` size must match the number of inputs""" assert(columnIndex < self._numColumns) connectedSynapses[:] = self._connectedSynapses[columnIndex]
def stripUnlearnedColumns(self, activeArray): """ Removes the set of columns who have never been active from the set of active columns selected in the inhibition round. Such columns cannot represent learned pattern and are therefore meaningless if only inference is required. This should not be done when using a random, unlearned SP since you would end up with no active columns. :param activeArray: An array whose size is equal to the number of columns. Any columns marked as active with an activeDutyCycle of 0 have never been activated before and therefore are not active due to learning. Any of these (unlearned) columns will be disabled (set to 0). """ neverLearned = numpy.where(self._activeDutyCycles == 0)[0] activeArray[neverLearned] = 0
def _updateMinDutyCycles(self): """ Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted. """ if self._globalInhibition or self._inhibitionRadius > self._numInputs: self._updateMinDutyCyclesGlobal() else: self._updateMinDutyCyclesLocal()
def _updateMinDutyCyclesGlobal(self): """ Updates the minimum duty cycles in a global fashion. Sets the minimum duty cycles for the overlap all columns to be a percent of the maximum in the region, specified by minPctOverlapDutyCycle. Functionality it is equivalent to _updateMinDutyCyclesLocal, but this function exploits the globality of the computation to perform it in a straightforward, and efficient manner. """ self._minOverlapDutyCycles.fill( self._minPctOverlapDutyCycles * self._overlapDutyCycles.max() )
def _updateMinDutyCyclesLocal(self): """ Updates the minimum duty cycles. The minimum duty cycles are determined locally. Each column's minimum duty cycles are set to be a percent of the maximum duty cycles in the column's neighborhood. Unlike _updateMinDutyCyclesGlobal, here the values can be quite different for different columns. """ for column in xrange(self._numColumns): neighborhood = self._getColumnNeighborhood(column) maxActiveDuty = self._activeDutyCycles[neighborhood].max() maxOverlapDuty = self._overlapDutyCycles[neighborhood].max() self._minOverlapDutyCycles[column] = (maxOverlapDuty * self._minPctOverlapDutyCycles)
def _updateDutyCycles(self, overlaps, activeColumns): """ Updates the duty cycles for each column. The OVERLAP duty cycle is a moving average of the number of inputs which overlapped with the each column. The ACTIVITY duty cycles is a moving average of the frequency of activation for each column. Parameters: ---------------------------- :param overlaps: An array containing the overlap score for each column. The overlap score for a column is defined as the number of synapses in a "connected state" (connected synapses) that are connected to input bits which are turned on. :param activeColumns: An array containing the indices of the active columns, the sparse set of columns which survived inhibition """ overlapArray = numpy.zeros(self._numColumns, dtype=realDType) activeArray = numpy.zeros(self._numColumns, dtype=realDType) overlapArray[overlaps > 0] = 1 activeArray[activeColumns] = 1 period = self._dutyCyclePeriod if (period > self._iterationNum): period = self._iterationNum self._overlapDutyCycles = self._updateDutyCyclesHelper( self._overlapDutyCycles, overlapArray, period ) self._activeDutyCycles = self._updateDutyCyclesHelper( self._activeDutyCycles, activeArray, period )
def _updateInhibitionRadius(self): """ Update the inhibition radius. The inhibition radius is a measure of the square (or hypersquare) of columns that each a column is "connected to" on average. Since columns are are not connected to each other directly, we determine this quantity by first figuring out how many *inputs* a column is connected to, and then multiplying it by the total number of columns that exist for each input. For multiple dimension the aforementioned calculations are averaged over all dimensions of inputs and columns. This value is meaningless if global inhibition is enabled. """ if self._globalInhibition: self._inhibitionRadius = int(self._columnDimensions.max()) return avgConnectedSpan = numpy.average( [self._avgConnectedSpanForColumnND(i) for i in xrange(self._numColumns)] ) columnsPerInput = self._avgColumnsPerInput() diameter = avgConnectedSpan * columnsPerInput radius = (diameter - 1) / 2.0 radius = max(1.0, radius) self._inhibitionRadius = int(radius + 0.5)
def _avgColumnsPerInput(self): """ The average number of columns per input, taking into account the topology of the inputs and columns. This value is used to calculate the inhibition radius. This function supports an arbitrary number of dimensions. If the number of column dimensions does not match the number of input dimensions, we treat the missing, or phantom dimensions as 'ones'. """ #TODO: extend to support different number of dimensions for inputs and # columns numDim = max(self._columnDimensions.size, self._inputDimensions.size) colDim = numpy.ones(numDim) colDim[:self._columnDimensions.size] = self._columnDimensions inputDim = numpy.ones(numDim) inputDim[:self._inputDimensions.size] = self._inputDimensions columnsPerInput = colDim.astype(realDType) / inputDim return numpy.average(columnsPerInput)
def _avgConnectedSpanForColumn1D(self, columnIndex): """ The range of connected synapses for column. This is used to calculate the inhibition radius. This variation of the function only supports a 1 dimensional column topology. Parameters: ---------------------------- :param columnIndex: The index identifying a column in the permanence, potential and connectivity matrices """ assert(self._inputDimensions.size == 1) connected = self._connectedSynapses[columnIndex].nonzero()[0] if connected.size == 0: return 0 else: return max(connected) - min(connected) + 1
def _avgConnectedSpanForColumn2D(self, columnIndex): """ The range of connectedSynapses per column, averaged for each dimension. This value is used to calculate the inhibition radius. This variation of the function only supports a 2 dimensional column topology. Parameters: ---------------------------- :param columnIndex: The index identifying a column in the permanence, potential and connectivity matrices """ assert(self._inputDimensions.size == 2) connected = self._connectedSynapses[columnIndex] (rows, cols) = connected.reshape(self._inputDimensions).nonzero() if rows.size == 0 and cols.size == 0: return 0 rowSpan = rows.max() - rows.min() + 1 colSpan = cols.max() - cols.min() + 1 return numpy.average([rowSpan, colSpan])
def _bumpUpWeakColumns(self): """ This method increases the permanence values of synapses of columns whose activity level has been too low. Such columns are identified by having an overlap duty cycle that drops too much below those of their peers. The permanence values for such columns are increased. """ weakColumns = numpy.where(self._overlapDutyCycles < self._minOverlapDutyCycles)[0] for columnIndex in weakColumns: perm = self._permanences[columnIndex].astype(realDType) maskPotential = numpy.where(self._potentialPools[columnIndex] > 0)[0] perm[maskPotential] += self._synPermBelowStimulusInc self._updatePermanencesForColumn(perm, columnIndex, raisePerm=False)
def _raisePermanenceToThreshold(self, perm, mask): """ This method ensures that each column has enough connections to input bits to allow it to become active. Since a column must have at least 'self._stimulusThreshold' overlaps in order to be considered during the inhibition phase, columns without such minimal number of connections, even if all the input bits they are connected to turn on, have no chance of obtaining the minimum threshold. For such columns, the permanence values are increased until the minimum number of connections are formed. Parameters: ---------------------------- :param perm: An array of permanence values for a column. The array is "dense", i.e. it contains an entry for each input bit, even if the permanence value is 0. :param mask: the indices of the columns whose permanences need to be raised. """ if len(mask) < self._stimulusThreshold: raise Exception("This is likely due to a " + "value of stimulusThreshold that is too large relative " + "to the input size. [len(mask) < self._stimulusThreshold]") numpy.clip(perm, self._synPermMin, self._synPermMax, out=perm) while True: numConnected = numpy.nonzero( perm > self._synPermConnected - PERMANENCE_EPSILON)[0].size if numConnected >= self._stimulusThreshold: return perm[mask] += self._synPermBelowStimulusInc
def _updatePermanencesForColumn(self, perm, columnIndex, raisePerm=True): """ This method updates the permanence matrix with a column's new permanence values. The column is identified by its index, which reflects the row in the matrix, and the permanence is given in 'dense' form, i.e. a full array containing all the zeros as well as the non-zero values. It is in charge of implementing 'clipping' - ensuring that the permanence values are always between 0 and 1 - and 'trimming' - enforcing sparsity by zeroing out all permanence values below '_synPermTrimThreshold'. It also maintains the consistency between 'self._permanences' (the matrix storing the permanence values), 'self._connectedSynapses', (the matrix storing the bits each column is connected to), and 'self._connectedCounts' (an array storing the number of input bits each column is connected to). Every method wishing to modify the permanence matrix should do so through this method. Parameters: ---------------------------- :param perm: An array of permanence values for a column. The array is "dense", i.e. it contains an entry for each input bit, even if the permanence value is 0. :param index: The index identifying a column in the permanence, potential and connectivity matrices :param raisePerm: A boolean value indicating whether the permanence values should be raised until a minimum number are synapses are in a connected state. Should be set to 'false' when a direct assignment is required. """ maskPotential = numpy.where(self._potentialPools[columnIndex] > 0)[0] if raisePerm: self._raisePermanenceToThreshold(perm, maskPotential) perm[perm < self._synPermTrimThreshold] = 0 numpy.clip(perm, self._synPermMin, self._synPermMax, out=perm) newConnected = numpy.where(perm >= self._synPermConnected - PERMANENCE_EPSILON)[0] self._permanences.update(columnIndex, perm) self._connectedSynapses.replace(columnIndex, newConnected) self._connectedCounts[columnIndex] = newConnected.size
def _initPermConnected(self): """ Returns a randomly generated permanence value for a synapses that is initialized in a connected state. The basic idea here is to initialize permanence values very close to synPermConnected so that a small number of learning steps could make it disconnected or connected. Note: experimentation was done a long time ago on the best way to initialize permanence values, but the history for this particular scheme has been lost. """ p = self._synPermConnected + ( self._synPermMax - self._synPermConnected)*self._random.getReal64() # Ensure we don't have too much unnecessary precision. A full 64 bits of # precision causes numerical stability issues across platforms and across # implementations p = int(p*100000) / 100000.0 return p
def _initPermNonConnected(self): """ Returns a randomly generated permanence value for a synapses that is to be initialized in a non-connected state. """ p = self._synPermConnected * self._random.getReal64() # Ensure we don't have too much unnecessary precision. A full 64 bits of # precision causes numerical stability issues across platforms and across # implementations p = int(p*100000) / 100000.0 return p
def _initPermanence(self, potential, connectedPct): """ Initializes the permanences of a column. The method returns a 1-D array the size of the input, where each entry in the array represents the initial permanence value between the input bit at the particular index in the array, and the column represented by the 'index' parameter. Parameters: ---------------------------- :param potential: A numpy array specifying the potential pool of the column. Permanence values will only be generated for input bits corresponding to indices for which the mask value is 1. :param connectedPct: A value between 0 or 1 governing the chance, for each permanence, that the initial permanence value will be a value that is considered connected. """ # Determine which inputs bits will start out as connected # to the inputs. Initially a subset of the input bits in a # column's potential pool will be connected. This number is # given by the parameter "connectedPct" perm = numpy.zeros(self._numInputs, dtype=realDType) for i in xrange(self._numInputs): if (potential[i] < 1): continue if (self._random.getReal64() <= connectedPct): perm[i] = self._initPermConnected() else: perm[i] = self._initPermNonConnected() # Clip off low values. Since we use a sparse representation # to store the permanence values this helps reduce memory # requirements. perm[perm < self._synPermTrimThreshold] = 0 return perm
def _mapColumn(self, index): """ Maps a column to its respective input index, keeping to the topology of the region. It takes the index of the column as an argument and determines what is the index of the flattened input vector that is to be the center of the column's potential pool. It distributes the columns over the inputs uniformly. The return value is an integer representing the index of the input bit. Examples of the expected output of this method: * If the topology is one dimensional, and the column index is 0, this method will return the input index 0. If the column index is 1, and there are 3 columns over 7 inputs, this method will return the input index 3. * If the topology is two dimensional, with column dimensions [3, 5] and input dimensions [7, 11], and the column index is 3, the method returns input index 8. Parameters: ---------------------------- :param index: The index identifying a column in the permanence, potential and connectivity matrices. :param wrapAround: A boolean value indicating that boundaries should be ignored. """ columnCoords = numpy.unravel_index(index, self._columnDimensions) columnCoords = numpy.array(columnCoords, dtype=realDType) ratios = columnCoords / self._columnDimensions inputCoords = self._inputDimensions * ratios inputCoords += 0.5 * self._inputDimensions / self._columnDimensions inputCoords = inputCoords.astype(int) inputIndex = numpy.ravel_multi_index(inputCoords, self._inputDimensions) return inputIndex
def _mapPotential(self, index): """ Maps a column to its input bits. This method encapsulates the topology of the region. It takes the index of the column as an argument and determines what are the indices of the input vector that are located within the column's potential pool. The return value is a list containing the indices of the input bits. The current implementation of the base class only supports a 1 dimensional topology of columns with a 1 dimensional topology of inputs. To extend this class to support 2-D topology you will need to override this method. Examples of the expected output of this method: * If the potentialRadius is greater than or equal to the largest input dimension then each column connects to all of the inputs. * If the topology is one dimensional, the input space is divided up evenly among the columns and each column is centered over its share of the inputs. If the potentialRadius is 5, then each column connects to the input it is centered above as well as the 5 inputs to the left of that input and the five inputs to the right of that input, wrapping around if wrapAround=True. * If the topology is two dimensional, the input space is again divided up evenly among the columns and each column is centered above its share of the inputs. If the potentialRadius is 5, the column connects to a square that has 11 inputs on a side and is centered on the input that the column is centered above. Parameters: ---------------------------- :param index: The index identifying a column in the permanence, potential and connectivity matrices. """ centerInput = self._mapColumn(index) columnInputs = self._getInputNeighborhood(centerInput).astype(uintType) # Select a subset of the receptive field to serve as the # the potential pool numPotential = int(columnInputs.size * self._potentialPct + 0.5) selectedInputs = numpy.empty(numPotential, dtype=uintType) self._random.sample(columnInputs, selectedInputs) potential = numpy.zeros(self._numInputs, dtype=uintType) potential[selectedInputs] = 1 return potential
def _updateBoostFactorsGlobal(self): """ Update boost factors when global inhibition is used """ # When global inhibition is enabled, the target activation level is # the sparsity of the spatial pooler if (self._localAreaDensity > 0): targetDensity = self._localAreaDensity else: inhibitionArea = ((2 * self._inhibitionRadius + 1) ** self._columnDimensions.size) inhibitionArea = min(self._numColumns, inhibitionArea) targetDensity = float(self._numActiveColumnsPerInhArea) / inhibitionArea targetDensity = min(targetDensity, 0.5) self._boostFactors = numpy.exp( (targetDensity - self._activeDutyCycles) * self._boostStrength)
def _updateBoostFactorsLocal(self): """ Update boost factors when local inhibition is used """ # Determine the target activation level for each column # The targetDensity is the average activeDutyCycles of the neighboring # columns of each column. targetDensity = numpy.zeros(self._numColumns, dtype=realDType) for i in xrange(self._numColumns): maskNeighbors = self._getColumnNeighborhood(i) targetDensity[i] = numpy.mean(self._activeDutyCycles[maskNeighbors]) self._boostFactors = numpy.exp( (targetDensity - self._activeDutyCycles) * self._boostStrength)
def _calculateOverlap(self, inputVector): """ This function determines each column's overlap with the current input vector. The overlap of a column is the number of synapses for that column that are connected (permanence value is greater than '_synPermConnected') to input bits which are turned on. The implementation takes advantage of the SparseBinaryMatrix class to perform this calculation efficiently. Parameters: ---------------------------- :param inputVector: a numpy array of 0's and 1's that comprises the input to the spatial pooler. """ overlaps = numpy.zeros(self._numColumns, dtype=realDType) self._connectedSynapses.rightVecSumAtNZ_fast(inputVector.astype(realDType), overlaps) return overlaps
def _inhibitColumns(self, overlaps): """ Performs inhibition. This method calculates the necessary values needed to actually perform inhibition and then delegates the task of picking the active columns to helper functions. Parameters: ---------------------------- :param overlaps: an array containing the overlap score for each column. The overlap score for a column is defined as the number of synapses in a "connected state" (connected synapses) that are connected to input bits which are turned on. """ # determine how many columns should be selected in the inhibition phase. # This can be specified by either setting the 'numActiveColumnsPerInhArea' # parameter or the 'localAreaDensity' parameter when initializing the class if (self._localAreaDensity > 0): density = self._localAreaDensity else: inhibitionArea = ((2*self._inhibitionRadius + 1) ** self._columnDimensions.size) inhibitionArea = min(self._numColumns, inhibitionArea) density = float(self._numActiveColumnsPerInhArea) / inhibitionArea density = min(density, 0.5) if self._globalInhibition or \ self._inhibitionRadius > max(self._columnDimensions): return self._inhibitColumnsGlobal(overlaps, density) else: return self._inhibitColumnsLocal(overlaps, density)
def _inhibitColumnsGlobal(self, overlaps, density): """ Perform global inhibition. Performing global inhibition entails picking the top 'numActive' columns with the highest overlap score in the entire region. At most half of the columns in a local neighborhood are allowed to be active. Columns with an overlap score below the 'stimulusThreshold' are always inhibited. :param overlaps: an array containing the overlap score for each column. The overlap score for a column is defined as the number of synapses in a "connected state" (connected synapses) that are connected to input bits which are turned on. :param density: The fraction of columns to survive inhibition. @return list with indices of the winning columns """ #calculate num active per inhibition area numActive = int(density * self._numColumns) # Calculate winners using stable sort algorithm (mergesort) # for compatibility with C++ sortedWinnerIndices = numpy.argsort(overlaps, kind='mergesort') # Enforce the stimulus threshold start = len(sortedWinnerIndices) - numActive while start < len(sortedWinnerIndices): i = sortedWinnerIndices[start] if overlaps[i] >= self._stimulusThreshold: break else: start += 1 return sortedWinnerIndices[start:][::-1]
def _inhibitColumnsLocal(self, overlaps, density): """ Performs local inhibition. Local inhibition is performed on a column by column basis. Each column observes the overlaps of its neighbors and is selected if its overlap score is within the top 'numActive' in its local neighborhood. At most half of the columns in a local neighborhood are allowed to be active. Columns with an overlap score below the 'stimulusThreshold' are always inhibited. :param overlaps: an array containing the overlap score for each column. The overlap score for a column is defined as the number of synapses in a "connected state" (connected synapses) that are connected to input bits which are turned on. :param density: The fraction of columns to survive inhibition. This value is only an intended target. Since the surviving columns are picked in a local fashion, the exact fraction of surviving columns is likely to vary. @return list with indices of the winning columns """ activeArray = numpy.zeros(self._numColumns, dtype="bool") for column, overlap in enumerate(overlaps): if overlap >= self._stimulusThreshold: neighborhood = self._getColumnNeighborhood(column) neighborhoodOverlaps = overlaps[neighborhood] numBigger = numpy.count_nonzero(neighborhoodOverlaps > overlap) # When there is a tie, favor neighbors that are already selected as # active. ties = numpy.where(neighborhoodOverlaps == overlap) tiedNeighbors = neighborhood[ties] numTiesLost = numpy.count_nonzero(activeArray[tiedNeighbors]) numActive = int(0.5 + density * len(neighborhood)) if numBigger + numTiesLost < numActive: activeArray[column] = True return activeArray.nonzero()[0]
def _getColumnNeighborhood(self, centerColumn): """ Gets a neighborhood of columns. Simply calls topology.neighborhood or topology.wrappingNeighborhood A subclass can insert different topology behavior by overriding this method. :param centerColumn (int) The center of the neighborhood. @returns (1D numpy array of integers) The columns in the neighborhood. """ if self._wrapAround: return topology.wrappingNeighborhood(centerColumn, self._inhibitionRadius, self._columnDimensions) else: return topology.neighborhood(centerColumn, self._inhibitionRadius, self._columnDimensions)
def _getInputNeighborhood(self, centerInput): """ Gets a neighborhood of inputs. Simply calls topology.wrappingNeighborhood or topology.neighborhood. A subclass can insert different topology behavior by overriding this method. :param centerInput (int) The center of the neighborhood. @returns (1D numpy array of integers) The inputs in the neighborhood. """ if self._wrapAround: return topology.wrappingNeighborhood(centerInput, self._potentialRadius, self._inputDimensions) else: return topology.neighborhood(centerInput, self._potentialRadius, self._inputDimensions)
def _seed(self, seed=-1): """ Initialize the random seed """ if seed != -1: self._random = NupicRandom(seed) else: self._random = NupicRandom()
def handleGetValue(self, topContainer): """ This method overrides ValueGetterBase's "pure virtual" method. It returns the referenced value. The derived class is NOT responsible for fully resolving the reference'd value in the event the value resolves to another ValueGetterBase-based instance -- this is handled automatically within ValueGetterBase implementation. topContainer: The top-level container (dict, tuple, or list [sub-]instance) within whose context the value-getter is applied. If self.__referenceDict is None, then topContainer will be used as the reference dictionary for resolving our dictionary key chain. Returns: The value referenced by this instance (which may be another value-getter instance) """ value = self.__referenceDict if self.__referenceDict is not None else topContainer for key in self.__dictKeyChain: value = value[key] return value
def Array(dtype, size=None, ref=False): """Factory function that creates typed Array or ArrayRef objects dtype - the data type of the array (as string). Supported types are: Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Real32, Real64 size - the size of the array. Must be positive integer. """ def getArrayType(self): """A little function to replace the getType() method of arrays It returns a string representation of the array element type instead of the integer value (NTA_BasicType enum) returned by the origianl array """ return self._dtype # ArrayRef can't be allocated if ref: assert size is None index = basicTypes.index(dtype) if index == -1: raise Exception('Invalid data type: ' + dtype) if size and size <= 0: raise Exception('Array size must be positive') suffix = 'ArrayRef' if ref else 'Array' arrayFactory = getattr(engine_internal, dtype + suffix) arrayFactory.getType = getArrayType if size: a = arrayFactory(size) else: a = arrayFactory() a._dtype = basicTypes[index] return a
def getInputNames(self): """ Returns list of input names in spec. """ inputs = self.getSpec().inputs return [inputs.getByIndex(i)[0] for i in xrange(inputs.getCount())]
def getOutputNames(self): """ Returns list of output names in spec. """ outputs = self.getSpec().outputs return [outputs.getByIndex(i)[0] for i in xrange(outputs.getCount())]
def _getParameterMethods(self, paramName): """Returns functions to set/get the parameter. These are the strongly typed functions get/setParameterUInt32, etc. The return value is a pair: setfunc, getfunc If the parameter is not available on this region, setfunc/getfunc are None. """ if paramName in self._paramTypeCache: return self._paramTypeCache[paramName] try: # Catch the error here. We will re-throw in getParameter or # setParameter with a better error message than we could generate here paramSpec = self.getSpec().parameters.getByName(paramName) except: return (None, None) dataType = paramSpec.dataType dataTypeName = basicTypes[dataType] count = paramSpec.count if count == 1: # Dynamically generate the proper typed get/setParameter<dataType> x = 'etParameter' + dataTypeName try: g = getattr(self, 'g' + x) # get the typed getParameter method s = getattr(self, 's' + x) # get the typed setParameter method except AttributeError: raise Exception("Internal error: unknown parameter type %s" % dataTypeName) info = (s, g) else: if dataTypeName == "Byte": info = (self.setParameterString, self.getParameterString) else: helper = _ArrayParameterHelper(self, dataType) info = (self.setParameterArray, helper.getParameterArray) self._paramTypeCache[paramName] = info return info
def getParameter(self, paramName): """Get parameter value""" (setter, getter) = self._getParameterMethods(paramName) if getter is None: import exceptions raise exceptions.Exception( "getParameter -- parameter name '%s' does not exist in region %s of type %s" % (paramName, self.name, self.type)) return getter(paramName)
def setParameter(self, paramName, value): """Set parameter value""" (setter, getter) = self._getParameterMethods(paramName) if setter is None: import exceptions raise exceptions.Exception( "setParameter -- parameter name '%s' does not exist in region %s of type %s" % (paramName, self.name, self.type)) setter(paramName, value)
def _getRegions(self): """Get the collection of regions in a network This is a tricky one. The collection of regions returned from from the internal network is a collection of internal regions. The desired collection is a collelcion of net.Region objects that also points to this network (net.network) and not to the internal network. To achieve that a CollectionWrapper class is used with a custom makeRegion() function (see bellow) as a value wrapper. The CollectionWrapper class wraps each value in the original collection with the result of the valueWrapper. """ def makeRegion(name, r): """Wrap a engine region with a nupic.engine_internal.Region Also passes the containing nupic.engine_internal.Network network in _network. This function is passed a value wrapper to the CollectionWrapper """ r = Region(r, self) #r._network = self return r regions = CollectionWrapper(engine_internal.Network.getRegions(self), makeRegion) return regions
def getRegionsByType(self, regionClass): """ Gets all region instances of a given class (for example, nupic.regions.sp_region.SPRegion). """ regions = [] for region in self.regions.values(): if type(region.getSelf()) is regionClass: regions.append(region) return regions
def getSpec(cls): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getSpec`. """ ns = dict( description=SDRClassifierRegion.__doc__, singleNodeOnly=True, inputs=dict( actValueIn=dict( description="Actual value of the field to predict. Only taken " "into account if the input has no category field.", dataType="Real32", count=0, required=False, regionLevel=False, isDefaultInput=False, requireSplitterMap=False), bucketIdxIn=dict( description="Active index of the encoder bucket for the " "actual value of the field to predict. Only taken " "into account if the input has no category field.", dataType="UInt64", count=0, required=False, regionLevel=False, isDefaultInput=False, requireSplitterMap=False), categoryIn=dict( description='Vector of categories of the input sample', dataType='Real32', count=0, required=True, regionLevel=True, isDefaultInput=False, requireSplitterMap=False), bottomUpIn=dict( description='Belief values over children\'s groups', dataType='Real32', count=0, required=True, regionLevel=False, isDefaultInput=True, requireSplitterMap=False), predictedActiveCells=dict( description="The cells that are active and predicted", dataType='Real32', count=0, required=True, regionLevel=True, isDefaultInput=False, requireSplitterMap=False), sequenceIdIn=dict( description="Sequence ID", dataType='UInt64', count=1, required=False, regionLevel=True, isDefaultInput=False, requireSplitterMap=False), ), outputs=dict( categoriesOut=dict( description='Classification results', dataType='Real32', count=0, regionLevel=True, isDefaultOutput=False, requireSplitterMap=False), actualValues=dict( description='Classification results', dataType='Real32', count=0, regionLevel=True, isDefaultOutput=False, requireSplitterMap=False), probabilities=dict( description='Classification results', dataType='Real32', count=0, regionLevel=True, isDefaultOutput=False, requireSplitterMap=False), ), parameters=dict( learningMode=dict( description='Boolean (0/1) indicating whether or not a region ' 'is in learning mode.', dataType='UInt32', count=1, constraints='bool', defaultValue=1, accessMode='ReadWrite'), inferenceMode=dict( description='Boolean (0/1) indicating whether or not a region ' 'is in inference mode.', dataType='UInt32', count=1, constraints='bool', defaultValue=0, accessMode='ReadWrite'), maxCategoryCount=dict( description='The maximal number of categories the ' 'classifier will distinguish between.', dataType='UInt32', required=True, count=1, constraints='', # arbitrarily large value defaultValue=2000, accessMode='Create'), steps=dict( description='Comma separated list of the desired steps of ' 'prediction that the classifier should learn', dataType="Byte", count=0, constraints='', defaultValue='0', accessMode='Create'), alpha=dict( description='The alpha is the learning rate of the classifier.' 'lower alpha results in longer term memory and slower ' 'learning', dataType="Real32", count=1, constraints='', defaultValue=0.001, accessMode='Create'), implementation=dict( description='The classifier implementation to use.', accessMode='ReadWrite', dataType='Byte', count=0, constraints='enum: py, cpp'), verbosity=dict( description='An integer that controls the verbosity level, ' '0 means no verbose output, increasing integers ' 'provide more verbosity.', dataType='UInt32', count=1, constraints='', defaultValue=0, accessMode='ReadWrite'), ), commands=dict() ) return ns
def initialize(self): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.initialize`. Is called once by NuPIC before the first call to compute(). Initializes self._sdrClassifier if it is not already initialized. """ if self._sdrClassifier is None: self._sdrClassifier = SDRClassifierFactory.create( steps=self.stepsList, alpha=self.alpha, verbosity=self.verbosity, implementation=self.implementation, )
def setParameter(self, name, index, value): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`. """ if name == "learningMode": self.learningMode = bool(int(value)) elif name == "inferenceMode": self.inferenceMode = bool(int(value)) else: return PyRegion.setParameter(self, name, index, value)
def writeToProto(self, proto): """ Write state to proto object. :param proto: SDRClassifierRegionProto capnproto object """ proto.implementation = self.implementation proto.steps = self.steps proto.alpha = self.alpha proto.verbosity = self.verbosity proto.maxCategoryCount = self.maxCategoryCount proto.learningMode = self.learningMode proto.inferenceMode = self.inferenceMode proto.recordNum = self.recordNum self._sdrClassifier.write(proto.sdrClassifier)
def readFromProto(cls, proto): """ Read state from proto object. :param proto: SDRClassifierRegionProto capnproto object """ instance = cls() instance.implementation = proto.implementation instance.steps = proto.steps instance.stepsList = [int(i) for i in proto.steps.split(",")] instance.alpha = proto.alpha instance.verbosity = proto.verbosity instance.maxCategoryCount = proto.maxCategoryCount instance._sdrClassifier = SDRClassifierFactory.read(proto) instance.learningMode = proto.learningMode instance.inferenceMode = proto.inferenceMode instance.recordNum = proto.recordNum return instance
def compute(self, inputs, outputs): """ Process one input sample. This method is called by the runtime engine. :param inputs: (dict) mapping region input names to numpy.array values :param outputs: (dict) mapping region output names to numpy.arrays that should be populated with output values by this method """ # This flag helps to prevent double-computation, in case the deprecated # customCompute() method is being called in addition to compute() called # when network.run() is called self._computeFlag = True patternNZ = inputs["bottomUpIn"].nonzero()[0] if self.learningMode: # An input can potentially belong to multiple categories. # If a category value is < 0, it means that the input does not belong to # that category. categories = [category for category in inputs["categoryIn"] if category >= 0] if len(categories) > 0: # Allow to train on multiple input categories. bucketIdxList = [] actValueList = [] for category in categories: bucketIdxList.append(int(category)) if "actValueIn" not in inputs: actValueList.append(int(category)) else: actValueList.append(float(inputs["actValueIn"])) classificationIn = {"bucketIdx": bucketIdxList, "actValue": actValueList} else: # If the input does not belong to a category, i.e. len(categories) == 0, # then look for bucketIdx and actValueIn. if "bucketIdxIn" not in inputs: raise KeyError("Network link missing: bucketIdxOut -> bucketIdxIn") if "actValueIn" not in inputs: raise KeyError("Network link missing: actValueOut -> actValueIn") classificationIn = {"bucketIdx": int(inputs["bucketIdxIn"]), "actValue": float(inputs["actValueIn"])} else: # Use Dummy classification input, because this param is required even for # inference mode. Because learning is off, the classifier is not learning # this dummy input. Inference only here. classificationIn = {"actValue": 0, "bucketIdx": 0} # Perform inference if self.inferenceMode is True # Train classifier if self.learningMode is True clResults = self._sdrClassifier.compute(recordNum=self.recordNum, patternNZ=patternNZ, classification=classificationIn, learn=self.learningMode, infer=self.inferenceMode) # fill outputs with clResults if clResults is not None and len(clResults) > 0: outputs['actualValues'][:len(clResults["actualValues"])] = \ clResults["actualValues"] for step in self.stepsList: stepIndex = self.stepsList.index(step) categoryOut = clResults["actualValues"][clResults[step].argmax()] outputs['categoriesOut'][stepIndex] = categoryOut # Flatten the rest of the output. For example: # Original dict {1 : [0.1, 0.3, 0.2, 0.7] # 4 : [0.2, 0.4, 0.3, 0.5]} # becomes: [0.1, 0.3, 0.2, 0.7, 0.2, 0.4, 0.3, 0.5] stepProbabilities = clResults[step] for categoryIndex in xrange(self.maxCategoryCount): flatIndex = categoryIndex + stepIndex * self.maxCategoryCount if categoryIndex < len(stepProbabilities): outputs['probabilities'][flatIndex] = \ stepProbabilities[categoryIndex] else: outputs['probabilities'][flatIndex] = 0.0 self.recordNum += 1
def customCompute(self, recordNum, patternNZ, classification): """ Just return the inference value from one input sample. The actual learning happens in compute() -- if, and only if learning is enabled -- which is called when you run the network. .. warning:: This method is deprecated and exists only to maintain backward compatibility. This method is deprecated, and will be removed. Use :meth:`nupic.engine.Network.run` instead, which will call :meth:`~nupic.regions.sdr_classifier_region.compute`. :param recordNum: (int) Record number of the input sample. :param patternNZ: (list) of the active indices from the output below :param classification: (dict) of the classification information: * ``bucketIdx``: index of the encoder bucket * ``actValue``: actual value going into the encoder :returns: (dict) containing inference results, one entry for each step in ``self.steps``. The key is the number of steps, the value is an array containing the relative likelihood for each ``bucketIdx`` starting from 0. For example: :: {'actualValues': [0.0, 1.0, 2.0, 3.0] 1 : [0.1, 0.3, 0.2, 0.7] 4 : [0.2, 0.4, 0.3, 0.5]} """ # If the compute flag has not been initialized (for example if we # restored a model from an old checkpoint) initialize it to False. if not hasattr(self, "_computeFlag"): self._computeFlag = False if self._computeFlag: # Will raise an exception if the deprecated method customCompute() is # being used at the same time as the compute function. warnings.simplefilter('error', DeprecationWarning) warnings.warn("The customCompute() method should not be " "called at the same time as the compute() " "method. The compute() method is called " "whenever network.run() is called.", DeprecationWarning) return self._sdrClassifier.compute(recordNum, patternNZ, classification, self.learningMode, self.inferenceMode)
def getOutputElementCount(self, outputName): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`. """ if outputName == "categoriesOut": return len(self.stepsList) elif outputName == "probabilities": return len(self.stepsList) * self.maxCategoryCount elif outputName == "actualValues": return self.maxCategoryCount else: raise ValueError("Unknown output {}.".format(outputName))
def run(self): """ Runs the OPF Model Parameters: ------------------------------------------------------------------------- retval: (completionReason, completionMsg) where completionReason is one of the ClientJobsDAO.CMPL_REASON_XXX equates. """ # ----------------------------------------------------------------------- # Load the experiment's description.py module descriptionPyModule = helpers.loadExperimentDescriptionScriptFromDir( self._experimentDir) expIface = helpers.getExperimentDescriptionInterfaceFromModule( descriptionPyModule) expIface.normalizeStreamSources() modelDescription = expIface.getModelDescription() self._modelControl = expIface.getModelControl() # ----------------------------------------------------------------------- # Create the input data stream for this task streamDef = self._modelControl['dataset'] from nupic.data.stream_reader import StreamReader readTimeout = 0 self._inputSource = StreamReader(streamDef, isBlocking=False, maxTimeout=readTimeout) # ----------------------------------------------------------------------- #Get field statistics from the input source fieldStats = self._getFieldStats() # ----------------------------------------------------------------------- # Construct the model instance self._model = ModelFactory.create(modelDescription) self._model.setFieldStatistics(fieldStats) self._model.enableLearning() self._model.enableInference(self._modelControl.get("inferenceArgs", None)) # ----------------------------------------------------------------------- # Instantiate the metrics self.__metricMgr = MetricsManager(self._modelControl.get('metrics',None), self._model.getFieldInfo(), self._model.getInferenceType()) self.__loggedMetricPatterns = self._modelControl.get("loggedMetrics", []) self._optimizedMetricLabel = self.__getOptimizedMetricLabel() self._reportMetricLabels = matchPatterns(self._reportKeyPatterns, self._getMetricLabels()) # ----------------------------------------------------------------------- # Initialize periodic activities (e.g., for model result updates) self._periodic = self._initPeriodicActivities() # ----------------------------------------------------------------------- # Create our top-level loop-control iterator numIters = self._modelControl.get('iterationCount', -1) # Are we asked to turn off learning for a certain # of iterations near the # end? learningOffAt = None iterationCountInferOnly = self._modelControl.get('iterationCountInferOnly', 0) if iterationCountInferOnly == -1: self._model.disableLearning() elif iterationCountInferOnly > 0: assert numIters > iterationCountInferOnly, "when iterationCountInferOnly " \ "is specified, iterationCount must be greater than " \ "iterationCountInferOnly." learningOffAt = numIters - iterationCountInferOnly self.__runTaskMainLoop(numIters, learningOffAt=learningOffAt) # ----------------------------------------------------------------------- # Perform final operations for model self._finalize() return (self._cmpReason, None)
def __runTaskMainLoop(self, numIters, learningOffAt=None): """ Main loop of the OPF Model Runner. Parameters: ----------------------------------------------------------------------- recordIterator: Iterator for counting number of records (see _runTask) learningOffAt: If not None, learning is turned off when we reach this iteration number """ ## Reset sequence states in the model, so it starts looking for a new ## sequence self._model.resetSequenceStates() self._currentRecordIndex = -1 while True: # If killed by a terminator, stop running if self._isKilled: break # If job stops or hypersearch ends, stop running if self._isCanceled: break # If the process is about to be killed, set as orphaned if self._isInterrupted.isSet(): self.__setAsOrphaned() break # If model is mature, stop running ONLY IF we are not the best model # for the job. Otherwise, keep running so we can keep returning # predictions to the user if self._isMature: if not self._isBestModel: self._cmpReason = self._jobsDAO.CMPL_REASON_STOPPED break else: self._cmpReason = self._jobsDAO.CMPL_REASON_EOF # Turn off learning? if learningOffAt is not None \ and self._currentRecordIndex == learningOffAt: self._model.disableLearning() # Read input record. Note that any failure here is a critical JOB failure # and results in the job being immediately canceled and marked as # failed. The runModelXXX code in hypesearch.utils, if it sees an # exception of type utils.JobFailException, will cancel the job and # copy the error message into the job record. try: inputRecord = self._inputSource.getNextRecordDict() if self._currentRecordIndex < 0: self._inputSource.setTimeout(10) except Exception, e: raise utils.JobFailException(ErrorCodes.streamReading, str(e.args), traceback.format_exc()) if inputRecord is None: # EOF self._cmpReason = self._jobsDAO.CMPL_REASON_EOF break if inputRecord: # Process input record self._currentRecordIndex += 1 result = self._model.run(inputRecord=inputRecord) # Compute metrics. result.metrics = self.__metricMgr.update(result) # If there are None, use defaults. see MetricsManager.getMetrics() # TODO remove this when JAVA API server is gone if not result.metrics: result.metrics = self.__metricMgr.getMetrics() # Write the result to the output cache. Don't write encodings, if they # were computed if InferenceElement.encodings in result.inferences: result.inferences.pop(InferenceElement.encodings) result.sensorInput.dataEncodings = None self._writePrediction(result) # Run periodic activities self._periodic.tick() if numIters >= 0 and self._currentRecordIndex >= numIters-1: break else: # Input source returned an empty record. # # NOTE: This is okay with Stream-based Source (when it times out # waiting for next record), but not okay with FileSource, which should # always return either with a valid record or None for EOF. raise ValueError("Got an empty record from FileSource: %r" % inputRecord)