INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Generate a path from egg_base back to '.' where the setup script resides and ensure that path points to the setup path from $install_dir/$egg_path.
def _resolve_setup_path(egg_base, install_dir, egg_path): """ Generate a path from egg_base back to '.' where the setup script resides and ensure that path points to the setup path from $install_dir/$egg_path. """ path_to_setup = egg_base.replace(os.sep, '/').rstrip('/') ...
Just like 'imp.find_module()', but with package support
def find_module(module, paths=None): """Just like 'imp.find_module()', but with package support""" parts = module.split('.') while parts: part = parts.pop(0) f, path, (suffix, mode, kind) = info = imp.find_module(part, paths) if kind == PKG_DIRECTORY: parts = parts or ...
Find 'module' by searching 'paths', and extract 'symbol' Return 'None' if 'module' does not exist on 'paths', or it does not define 'symbol'. If the module defines 'symbol' as a constant, return the constant. Otherwise, return 'default'.
def get_module_constant(module, symbol, default=-1, paths=None): """Find 'module' by searching 'paths', and extract 'symbol' Return 'None' if 'module' does not exist on 'paths', or it does not define 'symbol'. If the module defines 'symbol' as a constant, return the constant. Otherwise, return 'defau...
Extract the constant value of 'symbol' from 'code' If the name 'symbol' is bound to a constant value by the Python code object 'code', return that value. If 'symbol' is bound to an expression, return 'default'. Otherwise, return 'None'. Return value is based on the first assignment to 'symbol'. 'sy...
def extract_constant(code, symbol, default=-1): """Extract the constant value of 'symbol' from 'code' If the name 'symbol' is bound to a constant value by the Python code object 'code', return that value. If 'symbol' is bound to an expression, return 'default'. Otherwise, return 'None'. Return v...
Patch the globals to remove the objects not available on some platforms. XXX it'd be better to test assertions about bytecode instead.
def _update_globals(): """ Patch the globals to remove the objects not available on some platforms. XXX it'd be better to test assertions about bytecode instead. """ if not sys.platform.startswith('java') and sys.platform != 'cli': return incompatible = 'extract_constant', 'get_module_...
Return full package/distribution name, w/version
def full_name(self): """Return full package/distribution name, w/version""" if self.requested_version is not None: return '%s-%s' % (self.name, self.requested_version) return self.name
Is 'version' sufficiently up-to-date?
def version_ok(self, version): """Is 'version' sufficiently up-to-date?""" return self.attribute is None or self.format is None or \ str(version) != "unknown" and version >= self.requested_version
Get version number of installed module, 'None', or 'default' Search 'paths' for module. If not found, return 'None'. If found, return the extracted version attribute, or 'default' if no version attribute was specified, or the value cannot be determined without importing the module. T...
def get_version(self, paths=None, default="unknown"): """Get version number of installed module, 'None', or 'default' Search 'paths' for module. If not found, return 'None'. If found, return the extracted version attribute, or 'default' if no version attribute was specified, or the va...
Return true if dependency is present and up-to-date on 'paths
def is_current(self, paths=None): """Return true if dependency is present and up-to-date on 'paths'""" version = self.get_version(paths) if version is None: return False return self.version_ok(version)
Return sorted list of all package namespaces
def _get_all_ns_packages(self): """Return sorted list of all package namespaces""" pkgs = self.distribution.namespace_packages or [] return sorted(flatten(map(self._pkg_names, pkgs)))
Given a namespace package, yield the components of that package. >>> names = Installer._pkg_names('a.b.c') >>> set(names) == set(['a', 'a.b', 'a.b.c']) True
def _pkg_names(pkg): """ Given a namespace package, yield the components of that package. >>> names = Installer._pkg_names('a.b.c') >>> set(names) == set(['a', 'a.b', 'a.b.c']) True """ parts = pkg.split('.') while parts: yield '.'.joi...
Return an existing CA bundle path, or None
def find_ca_bundle(): """Return an existing CA bundle path, or None""" extant_cert_paths = filter(os.path.isfile, cert_paths) return ( get_win_certfile() or next(extant_cert_paths, None) or _certifi_where() )
Rewrite imports in packaging to redirect to vendored copies.
def rewrite_packaging(pkg_files, new_root): """ Rewrite imports in packaging to redirect to vendored copies. """ for file in pkg_files.glob('*.py'): text = file.text() text = re.sub(r' (pyparsing|six)', rf' {new_root}.\1', text) file.write_text(text)
Convert POS sequence to our coarse system, formatted as a string.
def coarse_tag_str(pos_seq): """Convert POS sequence to our coarse system, formatted as a string.""" global tag2coarse tags = [tag2coarse.get(tag, 'O') for tag in pos_seq] return ''.join(tags)
The "GreedyFSA" method in Handler et al. 2016. Returns token position spans of valid ngrams.
def extract_finditer(pos_seq, regex=SimpleNP): """The "GreedyFSA" method in Handler et al. 2016. Returns token position spans of valid ngrams.""" ss = coarse_tag_str(pos_seq) def gen(): for m in re.finditer(regex, ss): yield (m.start(), m.end()) return list(gen())
The "FilterFSA" method in Handler et al. 2016. Returns token position spans of valid ngrams.
def extract_ngram_filter(pos_seq, regex=SimpleNP, minlen=1, maxlen=8): """The "FilterFSA" method in Handler et al. 2016. Returns token position spans of valid ngrams.""" ss = coarse_tag_str(pos_seq) def gen(): for s in xrange(len(ss)): for n in xrange(minlen, 1 + min(maxlen, len(ss) - s)): e = s + n s...
The 'JK' method in Handler et al. 2016. Returns token positions of valid ngrams.
def extract_JK(pos_seq): """The 'JK' method in Handler et al. 2016. Returns token positions of valid ngrams.""" def find_ngrams(input_list, num_): '''get ngrams of len n from input list''' return zip(*[input_list[i:] for i in range(num_)]) # copied from M and S chp 5''' patterns = set(['AN', 'NN', 'AAN', 'AN...
Give a text (or POS tag sequence), return the phrases matching the given grammar. Works on documents or sentences. Returns a dict with one or more keys with the phrase information. text: the text of the document. If supplied, we will try to POS tag it. You can also do your own tokenzation and/or tagging and sup...
def get_phrases(text=None, tokens=None, postags=None, tagger='nltk', grammar='SimpleNP', regex=None, minlen=2, maxlen=8, output='counts'): """Give a text (or POS tag sequence), return the phrases matching the given grammar. Works on documents or sentences. Returns a dict with one or more keys with t...
take input text and return tokens w/ part of speech tags using NLTK
def tag_text(self, text): '''take input text and return tokens w/ part of speech tags using NLTK''' # putting import here instead of top of file b.c. not all will have nltk installed sents = self.sent_detector.tokenize(text) # TODO: this will fail on some unicode chars. I think assumes ascii word_pos_pairs = ...
Constructs the term doc matrix. Returns ------- scattertext.ParsedCorpus.ParsedCorpus
def build(self): '''Constructs the term doc matrix. Returns ------- scattertext.ParsedCorpus.ParsedCorpus ''' self._y = self._get_y_and_populate_category_idx_store() self._df.apply(self._add_to_x_factory, axis=1) self._X = self._X_factory.set_last_row_idx(len(self._y) - 1).get_csr_matrix() self._mX =...
Combines documents together that are in the same domain Parameters ---------- doc_domains : array-like Returns ------- scipy.sparse.csr_matrix
def get_new_term_doc_mat(self, doc_domains): ''' Combines documents together that are in the same domain Parameters ---------- doc_domains : array-like Returns ------- scipy.sparse.csr_matrix ''' assert len(doc_domains) == self.term_doc_matrix.get_num_docs() doc_domain_set = set(doc_domains) ...
Constructs the term doc matrix. Returns ------- scattertext.ParsedCorpus.ParsedCorpus
def build(self): '''Constructs the term doc matrix. Returns ------- scattertext.ParsedCorpus.ParsedCorpus ''' self._y = self._get_y_and_populate_category_idx_store() self._df.apply(self._add_to_x_factory, axis=1) self._X = self._X_factory.set_last_row_idx(len(self._y)-1).get_csr_matrix() self._mX = s...
Returns ------- A pd.DataFrame consisting of unigram term counts of words occurring in the TermDocumentMatrix and their corresponding background corpus counts. The dataframe has two columns, corpus and background. >>> corpus.get_unigram_corpus.get_term_and_background_counts() corpus b...
def get_term_and_background_counts(self): ''' Returns ------- A pd.DataFrame consisting of unigram term counts of words occurring in the TermDocumentMatrix and their corresponding background corpus counts. The dataframe has two columns, corpus and background. >>> corpus.get_unigram_corpus.get_term_and...
Returns ------- np.array Integer document indices
def get_doc_indices(self): ''' Returns ------- np.array Integer document indices ''' if self._document_category_df is None: return pd.np.array([]) categories_d = {d: i for i, d in enumerate(self.get_categories())} return self._document_category_df.category.apply(categories_d.get).values
Returns ------- np.array Texts
def get_texts(self): ''' Returns ------- np.array Texts ''' if self._document_category_df is None: return pd.np.array([]) return self._document_category_df.text.values
Parameters ---------- scatterchartdata : ScatterChartData Returns ------- pd.DataFrame
def get_term_category_frequencies(self, scatterchartdata): ''' Parameters ---------- scatterchartdata : ScatterChartData Returns ------- pd.DataFrame ''' df = self.term_category_freq_df.rename( columns={c: c + ' freq' for c in self.term_category_freq_df} ) df.index.name = 'term' return df
Parameters ---------- term_doc_matrix : TermDocMatrix Returns ------- TermDocMatrix pmi-filterd term doc matrix
def filter(self, term_doc_matrix): ''' Parameters ---------- term_doc_matrix : TermDocMatrix Returns ------- TermDocMatrix pmi-filterd term doc matrix ''' df = term_doc_matrix.get_term_freq_df() if len(df) == 0: return term_doc_matrix low_pmi_bigrams = get_low_pmi_bigrams(self._threshold_coef...
Returns html code of visualization. Parameters ---------- corpus : Corpus Corpus to use. category : str Name of category column as it appears in original data frame. category_name : str Name of category to use. E.g., "5-star reviews." Optional, defaults to category ...
def produce_scattertext_explorer(corpus, category, category_name=None, not_category_name=None, protocol='https', pmi_threshold_coefficient=DEFAULT_MINIMUM_...
Returns html code of visualization. Parameters ---------- term_doc_matrix : TermDocMatrix Corpus to use category : str name of category column category_name: str name of category to mine for not_category_name: str name of everything that isn't in category pro...
def produce_scattertext_html(term_doc_matrix, category, category_name, not_category_name, protocol='https', minimum_term_frequency=DEFAULT_MINIMUM_TERM_FREQUENCY, ...
Parameters ---------- corpus : Corpus Corpus to use. category : str Name of category column as it appears in original data frame. category_name : str Name of category to use. E.g., "5-star reviews." not_category_name : str Name of ...
def word_similarity_explorer_gensim(corpus, category, target_term, category_name=None, not_category_name=None, word2vec=None, ...
Parameters ---------- corpus : Corpus Corpus to use. category : str Name of category column as it appears in original data frame. category_name : str Name of category to use. E.g., "5-star reviews." not_category_name : str Name of everything that isn't in category. ...
def word_similarity_explorer(corpus, category, category_name, not_category_name, target_term, nlp=None, alpha=0.01, m...
Produces a Monroe et al. style visualization, with the x-axis being the log frequency Parameters ---------- corpus : Corpus Corpus to use. category : str Name of category column as it appears in original data frame. category_name : str or None Name of category to use. E.g.,...
def produce_frequency_explorer(corpus, category, category_name=None, not_category_name=None, term_ranker=termranking.AbsoluteFrequencyRanker, alpha=0.01, ...
Produces a semiotic square visualization. Parameters ---------- semiotic_square : SemioticSquare The basis of the visualization x_label : str The x-axis label in the scatter plot. Relationship between `category_a` and `category_b`. y_label The y-axis label in the scatter pl...
def produce_semiotic_square_explorer(semiotic_square, x_label, y_label, category_name=None, not_category_name=None, neutral_category_na...
Produces a semiotic square visualization. Parameters ---------- four_square : FourSquare The basis of the visualization x_label : str The x-axis label in the scatter plot. Relationship between `category_a` and `category_b`. y_label The y-axis label in the scatter plot. Rel...
def produce_four_square_explorer(four_square, x_label=None, y_label=None, a_category_name=None, b_category_name=None, not_a_category_name=None, ...
Produces a semiotic square visualization. Parameters ---------- four_square : FourSquareAxes The basis of the visualization x_label : str The x-axis label in the scatter plot. Relationship between `category_a` and `category_b`. y_label The y-axis label in the scatter plot. ...
def produce_four_square_axes_explorer(four_square_axes, x_label=None, y_label=None, num_terms_semiotic_square=None, get_tooltip_content=None, ...
Parameters ---------- corpus : ParsedCorpus It is highly recommended to use a stoplisted, unigram corpus-- `corpus.get_stoplisted_unigram_corpus()` category : str word2vec_model : Word2Vec A gensim word2vec model. A default model will be used instead. See Word2VecFromParsedCorpus for th...
def produce_pca_explorer(corpus, category, word2vec_model=None, projection_model=None, embeddings=None, projection=None, term_acceptance_re=re.compile('[a-z]{3,}'), ...
Parameters ---------- corpus : Corpus It is highly recommended to use a stoplisted, unigram corpus-- `corpus.get_stoplisted_unigram_corpus()` category : str category_name : str not_category_name : str not_categories : list characteristic_scorer : CharacteristicScorer term_ranker ...
def produce_characteristic_explorer(corpus, category, category_name=None, not_category_name=None, not_categories=None, characteristic_scorer...
Parameters ---------- corpus : Corpus Corpus to use. category : str Name of category column as it appears in original data frame. category_name : str Name of category to use. E.g., "5-star reviews." not_category_name : str Name of everything that isn't in category. ...
def sparse_explorer(corpus, category, scores, category_name=None, not_category_name=None, **kwargs): ''' Parameters ---------- corpus : Corpus Corpus to use. category : str Name of cat...
Parameters ---------- values: [term, ...] Returns ------- IndexStore
def build(values): ''' Parameters ---------- values: [term, ...] Returns ------- IndexStore ''' idxstore = IndexStore() idxstore._i2val = list(values) idxstore._val2i = {term:i for i,term in enumerate(values)} idxstore._next_i = len(values) return idxstore
Parameters ------- term_doc_matrix : TermDocMatrix Returns ------- New term doc matrix
def compact(self, term_doc_matrix): ''' Parameters ------- term_doc_matrix : TermDocMatrix Returns ------- New term doc matrix ''' tdf = self.term_ranker(term_doc_matrix).get_ranks() tdf_sum = tdf.sum(axis=0) tdf_portions = tdf / tdf_sum threshold = np.max(self.term_count / tdf_sum) terms_to_...
median = np.median(cat_scores) scores = np.zeros(len(cat_scores)).astype(np.float) scores[cat_scores > median] = cat_scores[cat_scores > median] not_cat_mask = cat_scores < median if median != 0 else cat_scores <= median scores[not_cat_mask] = -not_cat_scores[not_cat_mask]
def balance_scores_and_dont_scale(cat_scores, not_cat_scores): ''' median = np.median(cat_scores) scores = np.zeros(len(cat_scores)).astype(np.float) scores[cat_scores > median] = cat_scores[cat_scores > median] not_cat_mask = cat_scores < median if median != 0 else cat_scores <= median scores[not_cat_mask]...
Parameters ---------- metadata : (array like or None) Returns ------- {'labels':[], 'texts': []} or {'labels':[], 'texts': [], 'meta': []}
def get_labels_and_texts(self, metadata=None): ''' Parameters ---------- metadata : (array like or None) Returns ------- {'labels':[], 'texts': []} or {'labels':[], 'texts': [], 'meta': []} ''' to_ret = {'categories': self._corpus.get_categories(), 'labels': [], 'texts': []} labels = self._corpus._...
Parameters ---------- cat_word_counts : np.array category counts not_cat_word_counts : np.array not category counts Returns ------- np.array scores
def get_scores(self, cat_word_counts, not_cat_word_counts): ''' Parameters ---------- cat_word_counts : np.array category counts not_cat_word_counts : np.array not category counts Returns ------- np.array scores ''' cat_scores = self.get_scores_for_category(cat_word_counts, ...
Parameters ---------- cat_word_counts : np.array category counts not_cat_word_counts : np.array not category counts Returns ------- np.array scores
def get_scores_for_category(self, cat_word_counts, not_cat_word_counts): ''' Parameters ---------- cat_word_counts : np.array category counts not_cat_word_counts : np.array not category counts Returns ------- np.array scores ''' beta = self.beta_ assert len(cat_word_counts) == len(not_ca...
Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. None by default Returns ------- np.array of p-values
def get_p_vals(self, X): ''' Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. None by default Returns ------- np.array of p-values ''' z_scores = self.get_scores(X[:, 0], X[:, 1])...
Computes unbalanced scaled-fscores Parameters ---------- category : str category name to score scaler_algo : str Function that scales an array to a range \in [0 and 1]. Use 'percentile', 'normcdf'. Default normcdf beta : float Beta in (1+B^2) * (Scale(P(w|c)) * Scale(P(c|w)))/(B^2*Scale(P(w|c)) + Sca...
def get_scores_for_category(cat_word_counts, not_cat_word_counts, scaler_algo=DEFAULT_SCALER_ALGO, beta=DEFAULT_BETA): ''' Computes unbalanced scaled-fscores Parameters ---------- category : str category name to score scaler_algo : str Function that scales an array to a rang...
Parameters ---------- text, str Returns ------- List of 5.0-compliant emojis that occur in text.
def extract_emoji(text): ''' Parameters ---------- text, str Returns ------- List of 5.0-compliant emojis that occur in text. ''' found_emojis = [] len_text = len(text) i = 0 while i < len_text: cur_char = ord(text[i]) try: VALID_EMOJIS[cur_char] except: i += 1 continue found = False for...
Returns ------- altair.Chart
def make_chart(self): ''' Returns ------- altair.Chart ''' task_df = self.get_task_df() import altair as alt chart = alt.Chart(task_df).mark_bar().encode( x='start', x2='end', y='term', ) return chart
Returns -------
def get_temporal_score_df(self): ''' Returns ------- ''' scoredf = {} tdf = self.term_ranker(self.corpus).get_ranks() for cat in sorted(self.corpus.get_categories()): if cat >= self.starting_time_step: negative_categories = self._get_negative_categories(cat, tdf) scores = self.term_scorer.get_...
Returns -------
def get_task_df(self): ''' Returns ------- ''' term_time_df = self._get_term_time_df() terms_to_include = ( term_time_df .groupby('term')['top'] .sum() .sort_values(ascending=False) .iloc[:self.num_terms_to_include].index ) task_df = ( term_time_df[term_time_df.term.isin(terms_to_...
Parameters ---------- ngram, str or unicode, string to search for Returns ------- pd.DataFrame, {self._parsed_col: <matching texts>, self._category_col: <corresponding categories>, ...}
def search(self, ngram): ''' Parameters ---------- ngram, str or unicode, string to search for Returns ------- pd.DataFrame, {self._parsed_col: <matching texts>, self._category_col: <corresponding categories>, ...} ''' mask = self._document_index...
Parameters ---------- df : A data frame from, e.g., get_term_freq_df : pd.DataFrame positive_category : str The positive category name. term_significance : TermSignificance A TermSignificance instance from which to extract p-values.
def get_p_vals(df, positive_category, term_significance): ''' Parameters ---------- df : A data frame from, e.g., get_term_freq_df : pd.DataFrame positive_category : str The positive category name. term_significance : TermSignificance A TermSignificance instance from which to extract p-values. ''' df_pos = ...
:return: term freq matrix or metadata freq matrix
def get_X(self): ''' :return: term freq matrix or metadata freq matrix ''' if self._use_non_text_features: return self._term_doc_matrix._mX else: return self._term_doc_matrix._X
!!! not working
def scale_neg_1_to_1_with_zero_mean_log_abs_max(v): ''' !!! not working ''' df = pd.DataFrame({'v':v, 'sign': (v > 0) * 2 - 1}) df['lg'] = np.log(np.abs(v)) / np.log(1.96) df['exclude'] = (np.isinf(df.lg) | np.isneginf(df.lg)) for mask in [(df['sign'] == -1) & (df['exclude'] == False), ...
Constructs the term doc matrix. Returns ------- TermDocMatrix
def build(self): '''Constructs the term doc matrix. Returns ------- TermDocMatrix ''' X_factory, mX_factory, category_idx_store, term_idx_store, metadata_idx_store, y \ = self._init_term_doc_matrix_variables() parse_pipeline = ParsePipelineFactory(se...
Constructs the term doc matrix. Returns ------- TermDocMatrix
def build(self): '''Constructs the term doc matrix. Returns ------- TermDocMatrix ''' X_factory = CSRMatrixFactory() mX_factory = CSRMatrixFactory() term_idx_store = IndexStore() metadata_idx_store = IndexStore() parse_pipeline = ParsePi...
Parameters ---------- corpus Returns ------- float, pd.Series float: point on x-axis at even characteristicness pd.Series: term -> value between 0 and 1, sorted by score in a descending manner Background scores from corpus
def get_scores(self, corpus): ''' Parameters ---------- corpus Returns ------- float, pd.Series float: point on x-axis at even characteristicness pd.Series: term -> value between 0 and 1, sorted by score in a descending manner Background scores from corpus ''' term_ranks = self.term_ranker(corp...
Returns ------- str, the html file representation
def to_html(self): ''' Returns ------- str, the html file representation ''' javascript_to_insert = '\n'.join([ PackedDataUtils.full_content_of_javascript_files(), self.category_scatterplot_structure._visualization_data.to_javascript('getCategoryD...
Parameters ---------- corpus, ParsedCorpus Returns ------- iter: [sentence1word1, ...], [sentence2word1, ...]
def get_sentences(corpus): ''' Parameters ---------- corpus, ParsedCorpus Returns ------- iter: [sentence1word1, ...], [sentence2word1, ...] ''' assert isinstance(corpus, ParsedCorpus) return itertools.chain(*[[[corpus._term_idx_store.getidxstrict(t.lower_) for t in sent ...
Gets list of terms to display that have some interesting diachronic variation. Returns ------- pd.DataFrame e.g., term variable frequency trending 2 in 200310 1.0 0.000000 19 for 200310 1.0 0.000000 20 to 200311 1.0 0.000000
def get_display_dataframe(self): ''' Gets list of terms to display that have some interesting diachronic variation. Returns ------- pd.DataFrame e.g., term variable frequency trending 2 in 200310 1.0 0.000000 19 for 200310 1.0 0.000000 20 ...
Parameters ---------- doc, Spacy Doc Returns ------- Counter noun chunk -> count
def get_feats(self, doc): ''' Parameters ---------- doc, Spacy Doc Returns ------- Counter noun chunk -> count ''' ngram_counter = Counter() for sent in doc.sents: ngram_counter += _phrase_counts(sent) return ngram_counter
Parameters ---------- doc, Spacy Doc Returns ------- Counter noun chunk -> count
def get_feats(self, doc): ''' Parameters ---------- doc, Spacy Doc Returns ------- Counter noun chunk -> count ''' # ngram_counter = phrasemachine.get_phrases(str(doc), tagger='spacy')['counts'] ngram_counter = Counter() for sent in doc.sents: unigrams = self._get_unigram_feats(sent) ngram_...
Parameters ---------- protocol : str 'http' or 'https' for including external urls d3_url, str None by default. The url (or path) of d3, to be inserted into <script src="..."/> By default, this is `DEFAULT_D3_URL` declared in `ScatterplotStructure`. ...
def to_html(self, protocol='http', d3_url=None, d3_scale_chromatic_url=None, html_base=None): ''' Parameters ---------- protocol : str 'http' or 'https' for including external urls d3_url, str None...
Parameters ---------- ngram str or unicode, string to search for Returns ------- pd.DataFrame, {'texts': <matching texts>, 'categories': <corresponding categories>}
def search(self, ngram): ''' Parameters ---------- ngram str or unicode, string to search for Returns ------- pd.DataFrame, {'texts': <matching texts>, 'categories': <corresponding categories>} ''' mask = self._document_index_mask(ngram) return pd.DataFrame({ 'text': self.get_texts()[mask], ...
Parameters ------- label_append : str Returns ------- pd.DataFrame indexed on terms, with columns giving frequencies for each
def get_term_freq_df(self, label_append=' freq'): ''' Parameters ------- label_append : str Returns ------- pd.DataFrame indexed on terms, with columns giving frequencies for each ''' ''' row = self._row_category_ids() newX = csr_...
Returns ------- np.array with columns as categories and rows as terms
def get_term_freq_mat(self): ''' Returns ------- np.array with columns as categories and rows as terms ''' freq_mat = np.zeros(shape=(self.get_num_terms(), self.get_num_categories()), dtype=int) for cat_i in range(self.get_num_categories()): freq_mat[:...
Returns ------- np.array with columns as categories and rows as terms
def get_term_count_mat(self): ''' Returns ------- np.array with columns as categories and rows as terms ''' freq_mat = np.zeros(shape=(self.get_num_terms(), self.get_num_categories()), dtype=int) for cat_i in range(self.get_num_categories()): X = (self...
Returns ------- np.array with columns as categories and rows as terms
def get_metadata_count_mat(self): ''' Returns ------- np.array with columns as categories and rows as terms ''' freq_mat = np.zeros(shape=(self.get_num_metadata(), self.get_num_categories()), dtype=int) for cat_i in range(self.get_num_categories()): mX...
Parameters ------- label_append : str Returns ------- pd.DataFrame indexed on metadata, with columns giving frequencies for each category
def get_metadata_freq_df(self, label_append=' freq'): ''' Parameters ------- label_append : str Returns ------- pd.DataFrame indexed on metadata, with columns giving frequencies for each category ''' row = self._row_category_ids_for_meta() ...
Non destructive category removal. Parameters ---------- categories : list list of categories to keep ignore_absences : bool, False by default if categories does not appear, don't raise an error, just move on. Returns ------- TermDocMatrix...
def keep_only_these_categories(self, categories, ignore_absences=False): ''' Non destructive category removal. Parameters ---------- categories : list list of categories to keep ignore_absences : bool, False by default if categories does not appea...
Non destructive category removal. Parameters ---------- categories : list list of categories to remove ignore_absences : bool, False by default if categories does not appear, don't raise an error, just move on. Returns ------- TermDocMatr...
def remove_categories(self, categories, ignore_absences=False): ''' Non destructive category removal. Parameters ---------- categories : list list of categories to remove ignore_absences : bool, False by default if categories does not appear, don'...
Parameters ---------- idx_to_delete_list, list Returns ------- TermDocMatrix
def remove_terms_by_indices(self, idx_to_delete_list): ''' Parameters ---------- idx_to_delete_list, list Returns ------- TermDocMatrix ''' new_X, new_term_idx_store = self._get_X_after_delete_terms(idx_to_delete_list) return self._make_ne...
Computes Rudder score. Parameters ---------- category : str category name to score Returns ------- np.array
def get_rudder_scores(self, category): ''' Computes Rudder score. Parameters ---------- category : str category name to score Returns ------- np.array ''' category_percentiles = self._get_term_percentiles_in_category(category) ...
Computes l2-penalized logistic regression score. Parameters ---------- category : str category name to score category : str category name to score Returns ------- (coefficient array, accuracy, majority class baseline accuracy)
def get_logistic_regression_coefs_l2(self, category, clf=RidgeClassifierCV()): ''' Computes l2-penalized logistic regression score. Parameters ---------- category : str category name to score category : str categor...
Computes l1-penalized logistic regression score. Parameters ---------- category : str category name to score Returns ------- (coefficient array, accuracy, majority class baseline accuracy)
def get_logistic_regression_coefs_l1(self, category, clf=LassoCV(alphas=[0.1, 0.001], max_iter=10000, n_jobs=-1)): ''' Computes l1-penalized logistic regression scor...
Computes regression score of tdfidf transformed features Parameters ---------- category : str category name to score clf : sklearn regressor Returns ------- coefficient array
def get_regression_coefs(self, category, clf=ElasticNet()): ''' Computes regression score of tdfidf transformed features Parameters ---------- category : str category name to score clf : sklearn regressor Returns ------- coefficient array ...
Computes regression score of tdfidf transformed features Parameters ---------- category : str category name to score clf : sklearn regressor Returns ------- coefficient array
def get_logreg_coefs(self, category, clf=LogisticRegression()): ''' Computes regression score of tdfidf transformed features Parameters ---------- category : str category name to score clf : sklearn regressor Returns ------- coefficient array ...
Computes scaled-fscores Parameters ---------- category : str category name to score scaler_algo : str Function that scales an array to a range \in [0 and 1]. Use 'percentile', 'normcdf'. Default. beta : float Beta in (1+B^2) * (Scale(P(w|c)) * Sc...
def get_scaled_f_scores(self, category, scaler_algo=DEFAULT_SCALER_ALGO, beta=DEFAULT_BETA): ''' Computes scaled-fscores Parameters ---------- category : str category name to score sca...
scaler = self._get_scaler_function(scaler_algo) p_word_given_category = cat_word_counts.astype(np.float64) / cat_word_counts.sum() p_category_given_word = cat_word_counts.astype(np.float64) / (cat_word_counts + not_cat_word_counts) scores \ = self._computer_harmoic_mean_of_probabilit...
def _get_scaled_f_score_from_counts(self, cat_word_counts, not_cat_word_counts, scaler_algo, beta=DEFAULT_BETA): ''' scaler = self._get_scaler_function(scaler_algo) p_word_given_category = cat_word_counts.astype(np.float64) / cat_word_counts.sum() ...
Returns ------- pd.DataFrame of fisher scores vs background
def get_fisher_scores_vs_background(self): ''' Returns ------- pd.DataFrame of fisher scores vs background ''' df = self.get_term_and_background_counts() odds_ratio, p_values = self._get_fisher_scores_from_counts( df['corpus'], df['background']) ...
Returns ------- pd.DataFrame of posterior mean scores vs background
def get_posterior_mean_ratio_scores_vs_background(self): ''' Returns ------- pd.DataFrame of posterior mean scores vs background ''' df = self.get_term_and_background_counts() df['Log Posterior Mean Ratio'] = self._get_posterior_mean_ratio_from_counts(df['cor...
Returns ------- pd.DataFrame of rudder scores vs background
def get_rudder_scores_vs_background(self): ''' Returns ------- pd.DataFrame of rudder scores vs background ''' df = self.get_term_and_background_counts() corpus_percentiles = self._get_percentiles_from_freqs(df['corpus']) background_percentiles = self._get...
Applies the ranker in scatterchartdata to term-category frequencies. Parameters ---------- scatterchartdata : ScatterChartData Returns ------- pd.DataFrame
def get_term_category_frequencies(self, scatterchartdata): ''' Applies the ranker in scatterchartdata to term-category frequencies. Parameters ---------- scatterchartdata : ScatterChartData Returns ------- pd.DataFrame ''' term_ranker = s...
Parameters ---------- new_categories : array like String names of new categories. Length should be equal to number of documents Returns ------- TermDocMatrix
def recategorize(self, new_categories): ''' Parameters ---------- new_categories : array like String names of new categories. Length should be equal to number of documents Returns ------- TermDocMatrix ''' assert len(new_categories) == sel...
Returns a TermDocMatrix which is identical to self except the metadata values are now identical to the categories present. :return: TermDocMatrix
def use_categories_as_metadata(self): ''' Returns a TermDocMatrix which is identical to self except the metadata values are now identical to the categories present. :return: TermDocMatrix ''' new_metadata_factory = CSRMatrixFactory() for i, category_idx in enume...
Returns a TermDocMatrix which is identical to self except the metadata values are now identical to the categories present and term-doc-matrix is now the metadata matrix. :return: TermDocMatrix
def use_categories_as_metadata_and_replace_terms(self): ''' Returns a TermDocMatrix which is identical to self except the metadata values are now identical to the categories present and term-doc-matrix is now the metadata matrix. :return: TermDocMatrix ''' new_metadata_...
Returns ------- pd.DataFrame I.e., >>> convention_df.iloc[0] category plot filename subjectivity_html/obj/2002/Abandon.html text A senior at an elite college (Katie Holmes), a... movie_name ...
def get_data(): ''' Returns ------- pd.DataFrame I.e., >>> convention_df.iloc[0] category plot filename subjectivity_html/obj/2002/Abandon.html text A senior at an elite college (Katie Holmes), a... movie_name ...
Returns ------- PriorFactory
def use_general_term_frequencies(self): ''' Returns ------- PriorFactory ''' tdf = self._get_relevant_term_freq() bg_df = self.term_doc_mat.get_term_and_background_counts()[['background']] bg_df = pd.merge(tdf, bg_df, left_index=True, right_index=...
Parameters ---------- pd.Series term -> frequency Returns ------- PriorFactory
def use_custom_term_frequencies(self, custom_term_frequencies): ''' Parameters ---------- pd.Series term -> frequency Returns ------- PriorFactory ''' self.priors += custom_term_frequencies.reindex(self.priors.index).fillna(0) return self
Returns ------- PriorFactory
def use_all_categories(self): ''' Returns ------- PriorFactory ''' term_df = self.term_ranker.get_ranks() self.priors += term_df.sum(axis=1).fillna(0.) return self
Returns ------- PriorFactory
def use_neutral_categories(self): ''' Returns ------- PriorFactory ''' term_df = self.term_ranker.get_ranks() self.priors += term_df[[c + ' freq' for c in self._get_neutral_categories()]].sum(axis=1) return self
Returns ------- PriorFactory
def drop_neutral_categories_from_corpus(self): ''' Returns ------- PriorFactory ''' neutral_categories = self._get_neutral_categories() self.term_doc_mat = self.term_doc_mat.remove_categories(neutral_categories) self._reindex_priors() return self
Returns ------- PriorFactory
def drop_unused_terms(self): ''' Returns ------- PriorFactory ''' self.term_doc_mat = self.term_doc_mat.remove_terms( set(self.term_doc_mat.get_terms()) - set(self.priors.index) ) self._reindex_priors() return self
Returns ------- PriorFactory
def drop_zero_priors(self): ''' Returns ------- PriorFactory ''' self.term_doc_mat = self.term_doc_mat.remove_terms( self.priors[self.priors == 0].index ) self._reindex_priors() return self
Parameters ---------- target_term_doc_mat : TermDocMatrix Returns ------- PriorFactory
def align_to_target(self, target_term_doc_mat): ''' Parameters ---------- target_term_doc_mat : TermDocMatrix Returns ------- PriorFactory ''' self.priors = self.priors[target_term_doc_mat.get_terms()].fillna(0) return self
Returns ------- pd.Series
def get_priors(self): ''' Returns ------- pd.Series ''' priors = self.priors priors[~np.isfinite(priors)] = 0 priors += self.starting_count return priors
Parameters ---------- y_i, np.array(int) Arrays of word counts of words occurring in positive class y_j, np.array(int) Returns ------- np.array of z-scores
def get_zeta_i_j_given_separate_counts(self, y_i, y_j): ''' Parameters ---------- y_i, np.array(int) Arrays of word counts of words occurring in positive class y_j, np.array(int) Returns ------- np.array of z-scores ''' yp_i = y_i + self.alpha_w yp_j = y_j + self.alpha_w np_i = np.sum(yp_i) ...
Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. None by default Returns ------- np.array of z-scores
def get_zeta_i_j(self, X): ''' Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. None by default Returns ------- np.array of z-scores ''' y_i, y_j = X.T[0], X.T[1] return self.get...
Same function as get_zeta_i_j_given_separate_counts Parameters ---------- y_i, np.array(int) Arrays of word counts of words occurring in positive class y_j, np.array(int) Returns ------- np.array of z-scores
def get_scores(self, y_i, y_j): ''' Same function as get_zeta_i_j_given_separate_counts Parameters ---------- y_i, np.array(int) Arrays of word counts of words occurring in positive class y_j, np.array(int) Returns ------- np.array of z-scores ''' z_scores = self.get_zeta_i_j_given_separate_c...
Parameters ------- term_doc_matrix : TermDocMatrix Returns ------- New term doc matrix
def compact(self, term_doc_matrix): ''' Parameters ------- term_doc_matrix : TermDocMatrix Returns ------- New term doc matrix ''' count_df = self._get_statistics_dataframe(term_doc_matrix) return term_doc_matrix.remove_terms( count_df[count_df['pmi'] < self.minimum_pmi].index )