desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Apply preprocessing to a single text document. This should perform tokenization in addition to any other desired preprocessing steps. Args: text (str): document text read from plain-text file. Returns: iterable of str: tokens produced from `text` as a result of preprocessing.'
def preprocess_text(self, text):
for character_filter in self.character_filters: text = character_filter(text) tokens = self.tokenizer(text) for token_filter in self.token_filters: tokens = token_filter(tokens) return tokens
'Yield tuples of functions and their output for each stage of preprocessing. This is useful for debugging issues with the corpus preprocessing pipeline.'
def step_through_preprocess(self, text):
for character_filter in self.character_filters: text = character_filter(text) (yield (character_filter, text)) tokens = self.tokenizer(text) (yield (self.tokenizer, tokens)) for token_filter in self.token_filters: tokens = token_filter(tokens) (yield (token_filter, tokens...
'Iterate over the collection, yielding one document at a time. A document is a sequence of words (strings) that can be fed into `Dictionary.doc2bow`. Each document will be fed through `preprocess_text`. That method should be overridden to provide different preprocessing steps. This method will need to be overridden if ...
def get_texts(self):
lines = self.getstream() if self.metadata: for (lineno, line) in enumerate(lines): (yield (self.preprocess_text(line), (lineno,))) else: for line in lines: (yield self.preprocess_text(line))
'Yield n random documents from the corpus without replacement. Given the number of remaining documents in a corpus, we need to choose n elements. The probability for the current element to be chosen is n/remaining. If we choose it, we just decrease the n and move to the next element. Computing the corpus length may be ...
def sample_texts(self, n, seed=None, length=None):
random_generator = (random if (seed is None) else random.Random(seed)) if (length is None): length = len(self) if (not (n <= length)): raise ValueError('n is larger than length of corpus.') if (not (0 <= n)): raise ValueError('Negative sample size.') f...
'Args: min_depth (int): minimum depth in directory tree at which to begin searching for files. The default is 0, which means files starting in the top-level directory `input` will be considered. max_depth (int): max depth in directory tree at which files will no longer be considered. The default is None, which means re...
def __init__(self, input, dictionary=None, metadata=False, min_depth=0, max_depth=None, pattern=None, exclude_pattern=None, lines_are_documents=False, **kwargs):
self._min_depth = min_depth self._max_depth = (sys.maxsize if (max_depth is None) else max_depth) self.pattern = pattern self.exclude_pattern = exclude_pattern self.lines_are_documents = lines_are_documents super(TextDirectoryCorpus, self).__init__(input, dictionary, metadata, **kwargs)
'Lazily yield paths to each file in the directory structure within the specified range of depths. If a filename pattern to match was given, further filter to only those filenames that match.'
def iter_filepaths(self):
for (depth, dirpath, dirnames, filenames) in walk(self.input): if (self.min_depth <= depth <= self.max_depth): if (self.pattern is not None): filenames = (n for n in filenames if (self.pattern.match(n) is not None)) if (self.exclude_pattern is not None): ...
'Yield documents from the underlying plain text collection (of one or more files). Each item yielded from this method will be considered a document by subsequent preprocessing methods. If `lines_are_documents` was set to True, items will be lines from files. Otherwise there will be one item per file, containing the ent...
def getstream(self):
num_texts = 0 for path in self.iter_filepaths(): with open(path, 'rt') as f: if self.lines_are_documents: for line in f: (yield line.strip()) num_texts += 1 else: (yield f.read().strip()) num_...
'Initialize the corpus. Unless a dictionary is provided, this scans the corpus once, to determine its vocabulary. If `pattern` package is installed, use fancier shallow parsing to get token lemmas. Otherwise, use simple regexp tokenization. You can override this automatic logic by forcing the `lemmatize` parameter expl...
def __init__(self, fname, processes=None, lemmatize=utils.has_pattern(), dictionary=None, filter_namespaces=('0',)):
self.fname = fname self.filter_namespaces = filter_namespaces self.metadata = False if (processes is None): processes = max(1, (multiprocessing.cpu_count() - 1)) self.processes = processes self.lemmatize = lemmatize if (dictionary is None): self.dictionary = Dictionary(self.g...
'Iterate over the dump, returning text version of each article as a list of tokens. Only articles of sufficient length are returned (short articles & redirects etc are ignored). Note that this iterates over the **texts**; if you want vectors, just use the standard corpus interface instead of this function:: >>> for vec...
def get_texts(self):
(articles, articles_all) = (0, 0) (positions, positions_all) = (0, 0) texts = ((text, self.lemmatize, title, pageid) for (title, text, pageid) in extract_pages(bz2.BZ2File(self.fname), self.filter_namespaces)) pool = multiprocessing.Pool(self.processes, init_to_ignore_interrupt) try: for gro...
'Initialize the corpus from a file. `fname_vocab` is the file with vocabulary; if not specified, it defaults to `fname.vocab`.'
def __init__(self, fname, fname_vocab=None):
IndexedCorpus.__init__(self, fname) logger.info(('loading corpus from %s' % fname)) if (fname_vocab is None): (fname_base, _) = path.splitext(fname) fname_dir = path.dirname(fname) for fname_vocab in [utils.smart_extension(fname, '.vocab'), utils.smart_extension(fname, '/voc...
'Iterate over the corpus, returning one sparse vector at a time.'
def __iter__(self):
lineno = (-1) with utils.smart_open(self.fname) as fin: for (lineno, line) in enumerate(fin): (yield self.line2doc(line)) self.length = (lineno + 1)
'Save a corpus in the LDA-C format. There are actually two files saved: `fname` and `fname.vocab`, where `fname.vocab` is the vocabulary file. This function is automatically called by `BleiCorpus.serialize`; don\'t call it directly, call `serialize` instead.'
@staticmethod def save_corpus(fname, corpus, id2word=None, metadata=False):
if (id2word is None): logger.info('no word id mapping provided; initializing from corpus') id2word = utils.dict_from_corpus(corpus) num_terms = len(id2word) else: num_terms = (1 + max(([(-1)] + id2word.keys()))) logger.info(("storing corpus in Bl...
'Return the document stored at file position `offset`.'
def docbyoffset(self, offset):
with utils.smart_open(self.fname) as f: f.seek(offset) return self.line2doc(f.readline())
'Iterate over the corpus at the given filename. Yields a bag-of-words, a.k.a list of tuples of (word id, word count), based on the given id2word dictionary.'
def __iter__(self):
with utils.smart_open(self.fname) as f: for line in f: (yield self.line2doc(line))
'Save a corpus in the Mallet format. The document id will be generated by enumerating the corpus. That is, it will range between 0 and number of documents in the corpus. Since Mallet has a language field in the format, this defaults to the string \'__unknown__\'. If the language needs to be saved, post-processing will ...
@staticmethod def save_corpus(fname, corpus, id2word=None, metadata=False):
if (id2word is None): logger.info('no word id mapping provided; initializing from corpus') id2word = utils.dict_from_corpus(corpus) logger.info(('storing corpus in Mallet format into %s' % fname)) truncated = 0 offsets = [] with utils.smart_open...
'Return the document stored at file position `offset`.'
def docbyoffset(self, offset):
with utils.smart_open(self.fname) as f: f.seek(offset) return self.line2doc(f.readline())
'Initialize the corpus from a file. Although vector labels (~SVM target class) are not used in gensim in any way, they are parsed and stored in `self.labels` for convenience. Set `store_labels=False` to skip storing these labels (e.g. if there are too many vectors to store the self.labels array in memory).'
def __init__(self, fname, store_labels=True):
IndexedCorpus.__init__(self, fname) logger.info(('loading corpus from %s' % fname)) self.fname = fname self.length = None self.store_labels = store_labels self.labels = []
'Iterate over the corpus, returning one sparse vector at a time.'
def __iter__(self):
lineno = (-1) self.labels = [] with utils.smart_open(self.fname) as fin: for (lineno, line) in enumerate(fin): doc = self.line2doc(line) if (doc is not None): if self.store_labels: self.labels.append(doc[1]) (yield doc[0]) ...
'Save a corpus in the SVMlight format. The SVMlight `<target>` class tag is taken from the `labels` array, or set to 0 for all documents if `labels` is not supplied. This function is automatically called by `SvmLightCorpus.serialize`; don\'t call it directly, call `serialize` instead.'
@staticmethod def save_corpus(fname, corpus, id2word=None, labels=False, metadata=False):
logger.info(('converting corpus to SVMlight format: %s' % fname)) offsets = [] with utils.smart_open(fname, 'wb') as fout: for (docno, doc) in enumerate(corpus): label = (labels[docno] if labels else 0) offsets.append(fout.tell()) fout.write(utils.t...
'Return the document stored at file position `offset`.'
def docbyoffset(self, offset):
with utils.smart_open(self.fname) as f: f.seek(offset) return self.line2doc(f.readline())[0]
'Create a document from a single line (string) in SVMlight format'
def line2doc(self, line):
line = utils.to_unicode(line) line = line[:line.find('#')].strip() if (not line): return None parts = line.split() if (not parts): raise ValueError(('invalid line format in %s' % self.fname)) (target, fields) = (parts[0], [part.rsplit(':', 1) for part in parts[1:]]) ...
'Output the document in SVMlight format, as a string. Inverse function to `line2doc`.'
@staticmethod def doc2line(doc, label=0):
pairs = ' '.join((('%i:%s' % ((termid + 1), termval)) for (termid, termval) in doc)) return ('%s %s\n' % (label, pairs))
'If given, start training from the iterable `corpus` straight away. If not given, the model is left untrained (presumably because you want to call `update()` manually). `num_topics` is the number of requested latent topics to be extracted from the training corpus. `id2word` is a mapping from word ids (integers) to word...
def __init__(self, corpus=None, num_topics=100, id2word=None, workers=None, chunksize=2000, passes=1, batch=False, alpha='symmetric', eta=None, decay=0.5, offset=1.0, eval_every=10, iterations=50, gamma_threshold=0.001, random_state=None, minimum_probability=0.01, minimum_phi_value=0.01, per_word_topics=False):
self.workers = (max(1, (cpu_count() - 1)) if (workers is None) else workers) self.batch = batch if (isinstance(alpha, six.string_types) and (alpha == 'auto')): raise NotImplementedError('auto-tuning alpha not implemented in multicore LDA; use plain LdaModel.') super(Ld...
'Train the model with new documents, by EM-iterating over `corpus` until the topics converge (or until the maximum number of allowed iterations is reached). `corpus` must be an iterable (repeatable stream of documents), The E-step is distributed into the several processes. This update also supports updating an already ...
def update(self, corpus, chunks_as_numpy=False):
try: lencorpus = len(corpus) except: logger.warning('input corpus stream has no len(); counting documents') lencorpus = sum((1 for _ in corpus)) if (lencorpus == 0): logger.warning('LdaMulticore.update() called with an empty corpus') ...
'Args: model : Pre-trained topic model. Should be provided if topics is not provided. Currently supports LdaModel, LdaMallet wrapper and LdaVowpalWabbit wrapper. Use \'topics\' parameter to plug in an as yet unsupported model. topics : List of tokenized topics. If this is preferred over model, dictionary should be prov...
def __init__(self, model=None, topics=None, texts=None, corpus=None, dictionary=None, window_size=None, coherence='c_v', topn=10, processes=(-1)):
if ((model is None) and (topics is None)): raise ValueError('One of model or topics has to be provided.') elif ((topics is not None) and (dictionary is None)): raise ValueError('dictionary has to be provided if topics are to be used.') if...
'Internal helper function to return topics from a trained topic model.'
def _get_topics(self):
topics = [] if isinstance(self.model, LdaModel): for topic in self.model.state.get_lambda(): bestn = argsort(topic, topn=self.topn, reverse=True) topics.append(bestn) elif isinstance(self.model, LdaVowpalWabbit): for topic in self.model._get_topics(): best...
'Accumulate word occurrences and co-occurrences from texts or corpus using the optimal method for the chosen coherence metric. This operation may take quite some time for the sliding window based coherence methods.'
def estimate_probabilities(self, segmented_topics=None):
if (segmented_topics is None): segmented_topics = self.segment_topics() if (self.coherence in boolean_document_based): self._accumulator = self.measure.prob(self.corpus, segmented_topics) else: self._accumulator = self.measure.prob(texts=self.texts, segmented_topics=segmented_topics,...
'Return list of coherence values for each topic based on pipeline parameters.'
def get_coherence_per_topic(self, segmented_topics=None):
measure = self.measure if (segmented_topics is None): segmented_topics = measure.seg(self.topics) if (self._accumulator is None): self.estimate_probabilities(segmented_topics) if (self.coherence in boolean_document_based): kwargs = {} elif (self.coherence == 'c_v'): k...
'Aggregate the individual topic coherence measures using the pipeline\'s aggregation function.'
def aggregate_measures(self, topic_coherences):
return self.measure.aggr(topic_coherences)
'Return coherence value based on pipeline parameters.'
def get_coherence(self):
confirmed_measures = self.get_coherence_per_topic() return self.aggregate_measures(confirmed_measures)
'Return a single topic as a formatted string. See `show_topic()` for parameters. >>> lsimodel.print_topic(10, topn=5) \'-0.340 * "category" + 0.298 * "$M$" + 0.183 * "algebra" + -0.174 * "functor" + -0.168 * "operator"\''
def print_topic(self, topicno, topn=10):
return ' + '.join([('%.3f*"%s"' % (v, k)) for (k, v) in self.show_topic(topicno, topn)])
'Alias for `show_topics()` that prints the `num_words` most probable words for `topics` number of topics to log. Set `topics=-1` to print all topics.'
def print_topics(self, num_topics=20, num_words=10):
return self.show_topics(num_topics=num_topics, num_words=num_words, log=True)
'`vw_path` is the path to Vowpal Wabbit\'s \'vw\' executable. `corpus` is an iterable training corpus. If given, training will start immediately, otherwise the model is left untrained (presumably because you want to call `update()` manually). `num_topics` is the number of requested latent topics to be extracted from th...
def __init__(self, vw_path, corpus=None, num_topics=100, id2word=None, chunksize=256, passes=1, alpha=0.1, eta=0.1, decay=0.5, offset=1, gamma_threshold=0.001, random_seed=None, cleanup_files=True, tmp_prefix=u'tmp'):
self.vw_path = vw_path self.id2word = id2word if (self.id2word is None): if (corpus is None): raise ValueError(u'at least one of corpus/id2word must be specified, to establish input space dimensionality') LOG.warning(u'no word id mappi...
'Clear any existing model state, and train on given corpus.'
def train(self, corpus):
LOG.debug(u'Training new model from corpus') self.offset = self._initial_offset self._topics = None corpus_size = write_corpus_as_vw(corpus, self._corpus_filename) cmd = self._get_vw_train_command(corpus_size) _run_vw_command(cmd) self.offset += corpus_size
'Update existing model (if any) on corpus.'
def update(self, corpus):
if (not os.path.exists(self._model_filename)): return self.train(corpus) LOG.debug(u'Updating exiting model from corpus') self._topics = None corpus_size = write_corpus_as_vw(corpus, self._corpus_filename) cmd = self._get_vw_update_command(corpus_size) _run_vw_command(cmd) ...
'Return per-word lower bound on log perplexity. Also logs this and perplexity at INFO level.'
def log_perplexity(self, chunk):
vw_data = self._predict(chunk)[1] corpus_words = sum((cnt for document in chunk for (_, cnt) in document)) bound = (- vw_data[u'average_loss']) LOG.info(u'%.3f per-word bound, %.1f perplexity estimate based on a held-out corpus of %i documents with %i word...
'Serialise this model to file with given name.'
def save(self, fname, *args, **kwargs):
if os.path.exists(self._model_filename): LOG.debug(u"Reading model bytes from '%s'", self._model_filename) with utils.smart_open(self._model_filename, u'rb') as fhandle: self._model_data = fhandle.read() if os.path.exists(self._topics_filename): LOG.debug(u"Readin...
'Load LDA model from file with given name.'
@classmethod def load(cls, fname, *args, **kwargs):
lda_vw = super(LdaVowpalWabbit, cls).load(fname, *args, **kwargs) lda_vw._init_temp_dir(prefix=lda_vw.tmp_prefix) if lda_vw._model_data: LOG.debug(u"Writing model bytes to '%s'", lda_vw._model_filename) with utils.smart_open(lda_vw._model_filename, u'wb') as fhandle: ...
'Cleanup the temporary directory used by this wrapper.'
def __del__(self):
if (self.cleanup_files and self.tmp_dir): LOG.debug(u'Recursively deleting: %s', self.tmp_dir) shutil.rmtree(self.tmp_dir)
'Create a working temporary directory with given prefix.'
def _init_temp_dir(self, prefix=u'tmp'):
self.tmp_dir = tempfile.mkdtemp(prefix=prefix) LOG.info(u'using %s as temp dir', self.tmp_dir)
'Get list of command line arguments for running prediction.'
def _get_vw_predict_command(self, corpus_size):
cmd = [self.vw_path, u'--testonly', u'--lda_D', str(corpus_size), u'-i', self._model_filename, u'-d', self._corpus_filename, u'--learning_rate', u'0', u'-p', self._predict_filename] if (self.random_seed is not None): cmd.extend([u'--random_seed', str(self.random_seed)]) return cmd
'Get list of command line arguments for running model training. If \'update\' is set to True, this specifies that we\'re further training an existing model.'
def _get_vw_train_command(self, corpus_size, update=False):
cmd = [self.vw_path, u'-d', self._corpus_filename, u'--power_t', str(self.decay), u'--initial_t', str(self.offset), u'--minibatch', str(self.chunksize), u'--lda_D', str(corpus_size), u'--passes', str(self.passes), u'--cache_file', self._cache_filename, u'--lda_epsilon', str(self.gamma_threshold), u'--readable_model...
'Get list of command line arguments to update a model.'
def _get_vw_update_command(self, corpus_size):
return self._get_vw_train_command(corpus_size, update=True)
'Read topics file generated by Vowpal Wabbit, convert to numpy array. Output consists of many header lines, followed by a number of lines of: <word_id> <topic_1_gamma> <topic_2_gamma> ...'
def _load_vw_topics(self):
topics = numpy.zeros((self.num_topics, self.num_terms), dtype=numpy.float32) with utils.smart_open(self._topics_filename) as topics_file: found_data = False for line in topics_file: if (not found_data): if (line.startswith('0 ') and (':' not in line)): ...
'Get topics matrix, load from file if necessary.'
def _get_topics(self):
if (self._topics is None): self._load_vw_topics() return self._topics
'Run given chunk of documents against currently trained model. Returns a tuple of prediction matrix and Vowpal Wabbit data.'
def _predict(self, chunk):
corpus_size = write_corpus_as_vw(chunk, self._corpus_filename) cmd = self._get_vw_predict_command(corpus_size) vw_data = _parse_vw_output(_run_vw_command(cmd)) vw_data[u'corpus_size'] = corpus_size predictions = numpy.zeros((corpus_size, self.num_topics), dtype=numpy.float32) with utils.smart_op...
'Get path to given filename in temp directory.'
def _get_filename(self, name):
return os.path.join(self.tmp_dir, name)
'Get path to file to write Vowpal Wabbit model to.'
@property def _model_filename(self):
return self._get_filename(u'model.vw')
'Get path to file to write Vowpal Wabbit cache to.'
@property def _cache_filename(self):
return self._get_filename(u'cache.vw')
'Get path to file to write Vowpal Wabbit corpus to.'
@property def _corpus_filename(self):
return self._get_filename(u'corpus.vw')
'Get path to file to write Vowpal Wabbit topics to.'
@property def _topics_filename(self):
return self._get_filename(u'topics.vw')
'Get path to file to write Vowpal Wabbit predictions to.'
@property def _predict_filename(self):
return self._get_filename(u'predict.vw')
'The word and context embedding files are generated by wordrank binary and are saved in "out_name" directory which is created inside wordrank directory. The vocab and cooccurence files are generated using glove code available inside the wordrank directory. These files are used by the wordrank binary for training. `wr_p...
@classmethod def train(cls, wr_path, corpus_file, out_name, size=100, window=15, symmetric=1, min_count=5, max_vocab_size=0, sgd_num=100, lrate=0.001, period=10, iter=90, epsilon=0.75, dump_period=10, reg=0, alpha=100, beta=99, loss='hinge', memory=4.0, np=1, cleanup_files=False, sorted_vocab=1, ensemble=0):
model_dir = os.path.join(wr_path, out_name) meta_dir = os.path.join(model_dir, 'meta') os.makedirs(meta_dir) logger.info("Dumped data will be stored in '%s'", model_dir) copyfile(corpus_file, os.path.join(meta_dir, corpus_file.split('/')[(-1)])) vocab_file = os.path.join(meta_d...
'Sort embeddings according to word frequency.'
def sort_embeddings(self, vocab_file):
counts = {} vocab_size = len(self.vocab) prev_syn0 = copy.deepcopy(self.syn0) prev_vocab = copy.deepcopy(self.vocab) self.index2word = [] with utils.smart_open(vocab_file) as fin: for (index, line) in enumerate(fin): (word, count) = (utils.to_unicode(line).strip(), (vocab_siz...
'Replace syn0 with the sum of context and word embeddings.'
def ensemble_embedding(self, word_embedding, context_embedding):
glove2word2vec(context_embedding, (context_embedding + '.w2vformat')) w_emb = KeyedVectors.load_word2vec_format(('%s.w2vformat' % word_embedding)) c_emb = KeyedVectors.load_word2vec_format(('%s.w2vformat' % context_embedding)) assert (set(w_emb.vocab) == set(c_emb.vocab)), 'Vocabs are not same ...
'Accept a single word as input. Returns the word\'s representations in vector space, as a 1D numpy array. The word can be out-of-vocabulary as long as ngrams for the word are present. For words with all ngrams absent, a KeyError is raised. Example:: >>> trained_model[\'office\'] array([ -1.40128313e-02, ...])'
def word_vec(self, word, use_norm=False):
if (word in self.vocab): return super(FastTextKeyedVectors, self).word_vec(word, use_norm) else: word_vec = np.zeros(self.syn0_all.shape[1]) ngrams = FastText.compute_ngrams(word, self.min_n, self.max_n) ngrams = [ng for ng in ngrams if (ng in self.ngrams)] if use_norm: ...
'Precompute L2-normalized vectors. If `replace` is set, forget the original vectors and only keep the normalized ones = saves lots of memory! Note that you **cannot continue training** after doing a replace. The model becomes effectively read-only = you can only call `most_similar`, `similarity` etc.'
def init_sims(self, replace=False):
super(FastTextKeyedVectors, self).init_sims(replace) if ((getattr(self, 'syn0_all_norm', None) is None) or replace): logger.info('precomputing L2-norms of ngram weight vectors') if replace: for i in xrange(self.syn0_all.shape[0]): self.syn0_all[i, :] /=...
'Check if word is present in the vocabulary, or if any word ngrams are present. A vector for the word is guaranteed to exist if `__contains__` returns True.'
def __contains__(self, word):
if (word in self.vocab): return True else: word_ngrams = set(FastText.compute_ngrams(word, self.min_n, self.max_n)) if len((word_ngrams & set(self.ngrams.keys()))): return True else: return False
'`ft_path` is the path to the FastText executable, e.g. `/home/kofola/fastText/fasttext`. `corpus_file` is the filename of the text file to be used for training the FastText model. Expects file to contain utf-8 encoded text. `model` defines the training algorithm. By default, cbow is used. Accepted values are \'cbow\',...
@classmethod def train(cls, ft_path, corpus_file, output_file=None, model='cbow', size=100, alpha=0.025, window=5, min_count=5, word_ngrams=1, loss='ns', sample=0.001, negative=5, iter=5, min_n=3, max_n=6, sorted_vocab=1, threads=12):
ft_path = ft_path output_file = (output_file or os.path.join(tempfile.gettempdir(), 'ft_model')) ft_args = {'input': corpus_file, 'output': output_file, 'lr': alpha, 'dim': size, 'ws': window, 'epoch': iter, 'minCount': min_count, 'wordNgrams': word_ngrams, 'neg': negative, 'loss': loss, 'minn': min_n, 'max...
'Load the input-hidden weight matrix from the fast text output files. Note that due to limitations in the FastText API, you cannot continue training with a model loaded this way, though you can query for word similarity etc. `model_file` is the path to the FastText output files. FastText outputs two model files - `/pat...
@classmethod def load_fasttext_format(cls, model_file, encoding='utf8'):
model = cls() if (not model_file.endswith('.bin')): model_file += '.bin' model.file_name = model_file model.load_binary_data(encoding=encoding) return model
'Deletes the files created by FastText training'
@classmethod def delete_training_files(cls, model_file):
try: os.remove(('%s.vec' % model_file)) os.remove(('%s.bin' % model_file)) except FileNotFoundError: logger.debug('Training files %s not found when attempting to delete', model_file) pass
'Loads data from the output binary file created by FastText training'
def load_binary_data(self, encoding='utf8'):
with utils.smart_open(self.file_name, 'rb') as f: self.load_model_params(f) self.load_dict(f, encoding=encoding) self.load_vectors(f)
'Computes ngrams of all words present in vocabulary and stores vectors for only those ngrams. Vectors for other ngrams are initialized with a random uniform distribution in FastText. These vectors are discarded here to save space.'
def init_ngrams(self):
self.wv.ngrams = {} all_ngrams = [] self.wv.syn0 = np.zeros((len(self.wv.vocab), self.vector_size), dtype=REAL) for (w, vocab) in self.wv.vocab.items(): all_ngrams += self.compute_ngrams(w, self.wv.min_n, self.wv.max_n) self.wv.syn0[vocab.index] += np.array(self.wv.syn0_all[vocab.index])...
'Reproduces [hash method](https://github.com/facebookresearch/fastText/blob/master/src/dictionary.cc) used in fastText.'
@staticmethod def ft_hash(string):
old_settings = np.seterr(all='ignore') h = np.uint32(2166136261) for c in string: h = (h ^ np.uint32(ord(c))) h = (h * np.uint32(16777619)) np.seterr(**old_settings) return h
'Load the word vectors into matrix from the varembed output vector files. Using morphemes requires Python 2.7 version or above. \'vectors\' is the pickle file containing the word vectors. \'morfessor_model\' is the path to the trained morfessor model. \'use_morphemes\' False(default) use of morpheme embeddings in outpu...
@classmethod def load_varembed_format(cls, vectors, morfessor_model=None):
result = cls() if (vectors is None): raise Exception('Please provide vectors binary to load varembed model') D = utils.unpickle(vectors) word_to_ix = D['word_to_ix'] morpho_to_ix = D['morpho_to_ix'] word_embeddings = D['word_embeddings'] morpho_embeddings = D['mo...
'Loads the word embeddings'
def load_word_embeddings(self, word_embeddings, word_to_ix):
logger.info('Loading the vocabulary') self.vocab = {} self.index2word = [] counts = {} for word in word_to_ix: counts[word] = (counts.get(word, 0) + 1) self.vocab_size = len(counts) self.vector_size = word_embeddings.shape[1] self.syn0 = np.zeros((self.vocab_size, self.vect...
'Method to include morpheme embeddings into varembed vectors Allowed only in Python versions 2.7 and above.'
def add_morphemes_to_embeddings(self, morfessor_model, morpho_embeddings, morpho_to_ix):
for word in self.vocab: morpheme_embedding = np.array([morpho_embeddings[morpho_to_ix.get(m, (-1))] for m in morfessor_model.viterbi_segment(word)[0]]).sum(axis=0) self.syn0[self.vocab[word].index] += morpheme_embedding logger.info('Added morphemes to word vectors')
'`dtm_path` is path to the dtm executable, e.g. `C:/dtm/dtm-win64.exe`. `corpus` is a gensim corpus, aka a stream of sparse document vectors. `id2word` is a mapping between tokens ids and token. `mode` controls the mode of the mode: \'fit\' is for training, \'time\' for analyzing documents through time according to a D...
def __init__(self, dtm_path, corpus=None, time_slices=None, mode='fit', model='dtm', num_topics=100, id2word=None, prefix=None, lda_sequence_min_iter=6, lda_sequence_max_iter=20, lda_max_em_iter=10, alpha=0.01, top_chain_var=0.005, rng_seed=0, initialize_lda=True):
if (not os.path.isfile(dtm_path)): raise ValueError('dtm_path must point to the binary file, not to a folder') self.dtm_path = dtm_path self.id2word = id2word if (self.id2word is None): logger.warning('no word id mapping provided; initializing...
'Serialize documents in LDA-C format to a temporary text file,.'
def convert_input(self, corpus, time_slices):
logger.info(('serializing temporary corpus to %s' % self.fcorpustxt())) corpora.BleiCorpus.save_corpus(self.fcorpustxt(), corpus) with utils.smart_open(self.ftimeslices(), 'wb') as fout: fout.write(utils.to_utf8((str(len(self.time_slices)) + '\n'))) for sl in time_slices: ...
'Train DTM model using specified corpus and time slices.'
def train(self, corpus, time_slices, mode, model):
self.convert_input(corpus, time_slices) arguments = '--ntopics={p0} --model={mofrl} --mode={p1} --initialize_lda={p2} --corpus_prefix={p3} --outname={p4} --alpha={p5}'.format(p0=self.num_topics, mofrl=model, p1=mode, p2=self.initialize_lda, p3=self.fcorpus(), p4=self.foutname(), p5=self.al...
'Print the `num_words` most probable words for `num_topics` number of topics at \'times\' time slices. Set `topics=-1` to print all topics. Set `formatted=True` to return the topics as a list of strings, or `False` as lists of (weight, word) pairs.'
def show_topics(self, num_topics=10, times=5, num_words=10, log=False, formatted=True):
if ((num_topics < 0) or (num_topics >= self.num_topics)): num_topics = self.num_topics chosen_topics = range(num_topics) else: num_topics = min(num_topics, self.num_topics) chosen_topics = range(num_topics) if ((times < 0) or (times >= len(self.time_slices))): times =...
'Return `num_words` most probable words for the given `topicid`, as a list of `(word_probability, word)` 2-tuples.'
def show_topic(self, topicid, time, topn=50, num_words=None):
if (num_words is not None): logger.warning('The parameter num_words for show_topic() would be deprecated in the updated version.') logger.warning('Please use topn instead.') topn = num_words topics = self.lambda_[:, :, time] topic = topics[to...
'Return the given topic, formatted as a string.'
def print_topic(self, topicid, time, topn=10, num_words=None):
if (num_words is not None): warnings.warn('The parameter num_words for print_topic() would be deprecated in the updated version. Please use topn instead.') topn = num_words return ' + '.join([('%.3f*%s' % v) for v in self.show_topic(topicid, tim...
'returns term_frequency, vocab, doc_lengths, topic-term distributions and doc_topic distributions, specified by pyLDAvis format. all of these are needed to visualise topics for DTM for a particular time-slice via pyLDAvis. input parameter is the year to do the visualisation.'
def dtm_vis(self, corpus, time):
topic_term = (np.exp(self.lambda_[:, :, time]) / np.exp(self.lambda_[:, :, time]).sum()) topic_term = (topic_term * self.num_topics) doc_topic = self.gamma_ doc_lengths = [len(doc) for (doc_no, doc) in enumerate(corpus)] term_frequency = np.zeros(len(self.id2word)) for (doc_no, doc) in enumerate...
'returns all topics of a particular time-slice without probabilitiy values for it to be used for either "u_mass" or "c_v" coherence. TODO: because of print format right now can only return for 1st time-slice. should we fix the coherence printing or make changes to the print statements to mirror DTM python?'
def dtm_coherence(self, time, num_words=20):
coherence_topics = [] for topic_no in range(0, self.num_topics): topic = self.show_topic(topicid=topic_no, time=time, num_words=num_words) coherence_topic = [] for (prob, word) in topic: coherence_topic.append(word) coherence_topics.append(coherence_topic) return ...
'`mallet_path` is path to the mallet executable, e.g. `/home/kofola/mallet-2.0.7/bin/mallet`. `corpus` is a gensim corpus, aka a stream of sparse document vectors. `id2word` is a mapping between tokens ids and token. `workers` is the number of threads, for parallel training. `prefix` is the string prefix under which al...
def __init__(self, mallet_path, corpus=None, num_topics=100, alpha=50, id2word=None, workers=4, prefix=None, optimize_interval=0, iterations=1000, topic_threshold=0.0):
self.mallet_path = mallet_path self.id2word = id2word if (self.id2word is None): logger.warning('no word id mapping provided; initializing from corpus, assuming identity') self.id2word = utils.dict_from_corpus(corpus) self.num_terms = len(self.id2word) ...
'Write out `corpus` in a file format that MALLET understands: one document per line: document id[SPACE]label (not used)[SPACE]whitespace delimited utf8-encoded tokens[NEWLINE]'
def corpus2mallet(self, corpus, file_like):
for (docno, doc) in enumerate(corpus): if self.id2word: tokens = sum((([self.id2word[tokenid]] * int(cnt)) for (tokenid, cnt) in doc), []) else: tokens = sum((([str(tokenid)] * int(cnt)) for (tokenid, cnt) in doc), []) file_like.write(utils.to_utf8(('%s 0 %s\n' ...
'Serialize documents (lists of unicode tokens) to a temporary text file, then convert that text file to MALLET format `outfile`.'
def convert_input(self, corpus, infer=False, serialize_corpus=True):
if serialize_corpus: logger.info('serializing temporary corpus to %s', self.fcorpustxt()) with smart_open(self.fcorpustxt(), 'wb') as fout: self.corpus2mallet(corpus, fout) cmd = (self.mallet_path + ' import-file --preserve-case --keep-sequence --remove-stopwo...
'Return an iterator over the topic distribution of training corpus, by reading the doctopics.txt generated during training.'
def load_document_topics(self):
return self.read_doctopics(self.fdoctopics())
'Print the `num_words` most probable words for `num_topics` number of topics. Set `num_topics=-1` to print all topics. Set `formatted=True` to return the topics as a list of strings, or `False` as lists of (weight, word) pairs.'
def show_topics(self, num_topics=10, num_words=10, log=False, formatted=True):
if ((num_topics < 0) or (num_topics >= self.num_topics)): num_topics = self.num_topics chosen_topics = range(num_topics) else: num_topics = min(num_topics, self.num_topics) sort_alpha = (self.alpha + (0.0001 * numpy.random.rand(len(self.alpha)))) sorted_topics = list(matu...
'function to return the version of `mallet`'
def get_version(self, direc_path):
try: '\n Check version of mallet via jar file\n ' archive = zipfile.ZipFile(direc_path, 'r') if (u'cc/mallet/regression/' not in archive.namelist()): return '2.0.7' ...
'Yield document topic vectors from MALLET\'s "doc-topics" format, as sparse gensim vectors.'
def read_doctopics(self, fname, eps=1e-06, renorm=True):
mallet_version = self.get_version(self.mallet_path) with utils.smart_open(fname) as fin: for (lineno, line) in enumerate(fin): if ((lineno == 0) and line.startswith('#doc ')): continue parts = line.split()[2:] if (len(parts) == (2 * self.num_topics)...
'`id2word` is a mapping from word ids (integers) to words (strings). It is used to determine the vocabulary size, as well as for debugging and topic printing. If not set, it will be determined from the corpus.'
def __init__(self, corpus, id2word=None, num_topics=300):
self.id2word = id2word self.num_topics = num_topics if (corpus is not None): self.initialize(corpus)
'Initialize the random projection matrix.'
def initialize(self, corpus):
if (self.id2word is None): logger.info('no word id mapping provided; initializing from corpus, assuming identity') self.id2word = utils.dict_from_corpus(corpus) self.num_terms = len(self.id2word) else: self.num_terms = (1 + max(([(-1)] + self.id2word.ke...
'Return RP representation of the input vector and/or corpus.'
def __getitem__(self, bow):
(is_corpus, bow) = utils.is_corpus(bow) if is_corpus: return self._apply(bow) if getattr(self, 'freshly_loaded', False): self.freshly_loaded = False self.projection = self.projection.copy('F') vec = (matutils.sparse2full(bow, self.num_terms).reshape(self.num_terms, 1) / np.sqrt(s...
'Initialize the model from an iterable of `sentences`. Each sentence is a list of words (unicode strings) that will be used for training. The `sentences` iterable can be simply a list, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`BrownCorpus`, :class:`T...
def __init__(self, sentences=None, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, sample=0.001, seed=1, workers=3, min_alpha=0.0001, sg=0, hs=0, negative=5, cbow_mean=1, hashfxn=hash, iter=5, null_word=0, trim_rule=None, sorted_vocab=1, batch_words=MAX_WORDS_IN_BATCH, compute_loss=False):
self.load = call_on_class_only if (FAST_VERSION == (-1)): logger.warning('Slow version of {0} is being used'.format(__name__)) else: logger.debug('Fast version of {0} is being used'.format(__name__)) self.initialize_word_vectors() self.sg = int(sg)...
'Create a cumulative-distribution table using stored vocabulary word counts for drawing random words in the negative-sampling training routines. To draw a word index, choose a random integer up to the maximum value in the table (cum_table[-1]), then finding that integer\'s sorted insertion point (as if by bisect_left o...
def make_cum_table(self, power=0.75, domain=((2 ** 31) - 1)):
vocab_size = len(self.wv.index2word) self.cum_table = zeros(vocab_size, dtype=uint32) train_words_pow = 0.0 for word_index in xrange(vocab_size): train_words_pow += (self.wv.vocab[self.wv.index2word[word_index]].count ** power) cumulative = 0.0 for word_index in xrange(vocab_size): ...
'Create a binary Huffman tree using stored vocabulary word counts. Frequent words will have shorter binary codes. Called internally from `build_vocab()`.'
def create_binary_tree(self):
logger.info('constructing a huffman tree from %i words', len(self.wv.vocab)) heap = list(itervalues(self.wv.vocab)) heapq.heapify(heap) for i in xrange((len(self.wv.vocab) - 1)): (min1, min2) = (heapq.heappop(heap), heapq.heappop(heap)) heapq.heappush(heap, Vocab(count=...
'Build vocabulary from a sequence of sentences (can be a once-only generator stream). Each sentence must be a list of unicode strings.'
def build_vocab(self, sentences, keep_raw_vocab=False, trim_rule=None, progress_per=10000, update=False):
self.scan_vocab(sentences, progress_per=progress_per, trim_rule=trim_rule) self.scale_vocab(keep_raw_vocab=keep_raw_vocab, trim_rule=trim_rule, update=update) self.finalize_vocab(update=update)
'Do an initial scan of all words appearing in sentences.'
def scan_vocab(self, sentences, progress_per=10000, trim_rule=None):
logger.info('collecting all words and their counts') sentence_no = (-1) total_words = 0 min_reduce = 1 vocab = defaultdict(int) checked_string_types = 0 for (sentence_no, sentence) in enumerate(sentences): if (not checked_string_types): if isinstance(senten...
'Apply vocabulary settings for `min_count` (discarding less-frequent words) and `sample` (controlling the downsampling of more-frequent words). Calling with `dry_run=True` will only simulate the provided settings and report the size of the retained vocabulary, effective corpus length, and estimated memory requirements....
def scale_vocab(self, min_count=None, sample=None, dry_run=False, keep_raw_vocab=False, trim_rule=None, update=False):
min_count = (min_count or self.min_count) sample = (sample or self.sample) drop_total = drop_unique = 0 if (not update): logger.info('Loading a fresh vocabulary') (retain_total, retain_words) = (0, []) if (not dry_run): self.wv.index2word = [] sel...
'Build tables and model weights based on final vocabulary settings.'
def finalize_vocab(self, update=False):
if (not self.wv.index2word): self.scale_vocab() if (self.sorted_vocab and (not update)): self.sort_vocab() if self.hs: self.create_binary_tree() if self.negative: self.make_cum_table() if self.null_word: (word, v) = ('\x00', Vocab(count=1, sample_int=0)) ...
'Sort the vocabulary so the most frequent words have the lowest indexes.'
def sort_vocab(self):
if len(self.wv.syn0): raise RuntimeError('cannot sort vocabulary after model weights already initialized.') self.wv.index2word.sort(key=(lambda word: self.wv.vocab[word].count), reverse=True) for (i, word) in enumerate(self.wv.index2word): self.wv.vocab[word].index = i
'Borrow shareable pre-built structures (like vocab) from the other_model. Useful if testing multiple models in parallel on the same corpus.'
def reset_from(self, other_model):
self.wv.vocab = other_model.wv.vocab self.wv.index2word = other_model.wv.index2word self.cum_table = other_model.cum_table self.corpus_count = other_model.corpus_count self.reset_weights()
'Train a single batch of sentences. Return 2-tuple `(effective word count after ignoring unknown words and sentence length trimming, total word count)`.'
def _do_train_job(self, sentences, alpha, inits):
(work, neu1) = inits tally = 0 if self.sg: tally += train_batch_sg(self, sentences, alpha, work, self.compute_loss) else: tally += train_batch_cbow(self, sentences, alpha, work, neu1, self.compute_loss) return (tally, self._raw_word_count(sentences))
'Return the number of words in a given job.'
def _raw_word_count(self, job):
return sum((len(sentence) for sentence in job))
'Update the model\'s neural weights from a sequence of sentences (can be a once-only generator stream). For Word2Vec, each sentence must be a list of unicode strings. (Subclasses may accept other examples.) To support linear learning-rate decay from (initial) alpha to min_alpha, and accurate progres-percentage logging,...
def train(self, sentences, total_examples=None, total_words=None, epochs=None, start_alpha=None, end_alpha=None, word_count=0, queue_factor=2, report_delay=1.0, compute_loss=None):
if self.model_trimmed_post_training: raise RuntimeError('Parameters for training were discarded using model_trimmed_post_training method') if (FAST_VERSION < 0): warnings.warn('C extension not loaded for Word2Vec, training will be slow. Install ...
'Score the log probability for a sequence of sentences (can be a once-only generator stream). Each sentence must be a list of unicode strings. This does not change the fitted model in any way (see Word2Vec.train() for that). We have currently only implemented score for the hierarchical softmax scheme, so you need to ha...
def score(self, sentences, total_sentences=int(1000000.0), chunksize=100, queue_factor=2, report_delay=1):
if (FAST_VERSION < 0): warnings.warn('C extension compilation failed, scoring will be slow. Install a C compiler and reinstall gensim for fastness.') logger.info('scoring sentences with %i workers on %i vocabulary and %i featu...
'Removes all L2-normalized vectors for words from the model. You will have to recompute them using init_sims method.'
def clear_sims(self):
self.wv.syn0norm = None
'Copy all the existing weights, and reset the weights for the newly added vocabulary.'
def update_weights(self):
logger.info('updating layer weights') gained_vocab = (len(self.wv.vocab) - len(self.wv.syn0)) newsyn0 = empty((gained_vocab, self.vector_size), dtype=REAL) for i in xrange(len(self.wv.syn0), len(self.wv.vocab)): newsyn0[(i - len(self.wv.syn0))] = self.seeded_vector((self.wv.index2word[i] +...