INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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.
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.
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
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.
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.
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
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
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
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
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.
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.
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 everything that isn t in category. E. g. Below 5 - star reviews. target_term: str Word or phr...
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. E. g. Below 5 - star reviews. target_term: str Word or phr...
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
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.
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.
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.
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 the default model. projection_model: s...
def produce_projection_explorer(corpus, category, word2vec_model=None, projection_model=None, embeddings=None, term_acceptance_re=re.compile('[a-z]{3,}'), ...
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 the default model. projection_model: s...
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 term_scorer term_acceptance_re: SRE_Pattern Re...
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. E. g. Below 5 - star reviews. scores: np. array Scores to ...
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 ------- term_doc_matrix: TermDocMatrix
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_...
Parameters ---------- values: [ term... ]
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 ---------- metadata: ( array like or None )
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._...
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 ---------- cat_word_counts: np. array category counts not_cat_word_counts: np. array not category counts
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
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
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 balanced scaled f - scores Parameters ---------- cat_word_counts: np. array category counts not_cat_word_counts: np. array not category counts 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_scores(cat_word_counts, not_cat_word_counts, scaler_algo=DEFAULT_SCALER_ALGO, beta=DEFAULT_BETA): ''' Computes balanced scaled f-scores Parameters ---------- cat_word_counts : np.array category counts not_cat_word_counts : np.array not category counts scaler_algo : str Funct...
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 )) + S...
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
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
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.
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.
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 ParsedCorpus
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 ...
Parameters ---------- 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...
Gets list of terms to display that have some interesting diachronic variation.
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
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
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. d3_scale_chromatic_url: str None by default. URL of d3_scale_chromatic_url to be...
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
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
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
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.
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.
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
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
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
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
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
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
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 )) * Scale ( P ( c|w )))/ ( B^2 * Scale ( P ( w|c )) + Scale ( P ( c|w )))...
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_probabilities_over_non_zero_i...
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.
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
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.
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.
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
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
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 )
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
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
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
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 )
Parameters ---------- term_dict: dict { metadataname: [ term1 term2.... ]... }
def check_topic_model_string_format(term_dict): ''' Parameters ---------- term_dict: dict {metadataname: [term1, term2, ....], ...} Returns ------- None ''' if type(term_dict) != dict: raise TypeError("Argument for term_dict must be a dict, keyed on strings, and contain a li...
Inserts dictionary of meta data terms into object.
def inject_metadata_term_lists(self, term_dict): ''' Inserts dictionary of meta data terms into object. Parameters ---------- term_dict: dict {metadataname: [term1, term2, ....], ...} Returns ------- self: ScatterChart ''' check_topic_mod...
Inserts a set of descriptions of meta data terms. These will be displayed below the scatter plot when a meta data term is clicked. All keys in the term dict must occur as meta data.
def inject_metadata_descriptions(self, term_dict): ''' Inserts a set of descriptions of meta data terms. These will be displayed below the scatter plot when a meta data term is clicked. All keys in the term dict must occur as meta data. Parameters ---------- ter...
Inject custom x and y coordinates for each term into chart.
def inject_coordinates(self, x_coords, y_coords, rescale_x=None, rescale_y=None, original_x=None, original_y=None): ''' Inject custom x and y ...
: param vec: array to jitter: return: array jittered version of arrays
def _add_jitter(self, vec): """ :param vec: array to jitter :return: array, jittered version of arrays """ if self.scatterchartdata.jitter == 0 or self.scatterchartdata.jitter is None: return vec return vec + np.random.rand(1, len(vec))[0] * self.scatterchartd...
Outdated. MPLD3 drawing.
def draw(self, category, num_top_words_to_annotate=4, words_to_annotate=[], scores=None, transform=percentile_alphabetical): '''Outdated. MPLD3 drawing. Parameters ---------- category num_top_words_to_annotate ...
Parameters ---------- y_i np. array ( int ) Arrays of word counts of words occurring in positi ve class y_j np. array ( int )
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 positi ve class y_j, np.array(int) Returns ------- np.array of z-scores ''' n_i, n_j = y_i.sum(), y_j.sum() delta_i_j = (np.log((y_i + 1) / (1. + n_i...
Parameters ---------- tdm: TermDocMatrix category: str category name
def get_scores_and_p_values(self, tdm, category): ''' Parameters ---------- tdm: TermDocMatrix category: str, category name Returns ------- pd.DataFrame(['coef', 'p-val']) ''' X = tdm._X y = self._make_response_variable_1_or_negative_1(category, tdm) pX = X / X.sum(axis=1) ansX = self._anscom...
>>> a = csr_matrix ( np. array ( [[ 0 1 3 0 1 0 ] [ 0 0 1 0 1 1 ]] ) >>> delete_columns ( a [ 1 2 ] ). todense () matrix ( [[ 0 0 1 0 ] [ 0 0 1 1 ]] )
def delete_columns(mat, columns_to_delete): ''' >>> a = csr_matrix(np.array([[0, 1, 3, 0, 1, 0], [0, 0, 1, 0, 1, 1]]) >>> delete_columns(a, [1,2]).todense() matrix([[0, 0, 1, 0], [0, 0, 1, 1]]) Parameters ---------- mat : csr_matrix columns_to_delete : list[int] Returns...
Parameters ---------- param last_col_idx: int number of columns
def set_last_col_idx(self, last_col_idx): ''' Parameters ---------- param last_col_idx : int number of columns ''' assert last_col_idx >= self._max_col self._max_col = last_col_idx return self
Parameters ---------- param last_row_idx: int number of rows
def set_last_row_idx(self, last_row_idx): ''' Parameters ---------- param last_row_idx : int number of rows ''' assert last_row_idx >= self._max_row self._max_row = last_row_idx return self