INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Since our vectors are dictionaries, lets convert them to lists for easier mathing.
def cosine_sim(vec1, vec2): """ Since our vectors are dictionaries, lets convert them to lists for easier mathing. """ vec1 = [val for val in vec1.values()] vec2 = [val for val in vec2.values()] dot_prod = 0 for i, v in enumerate(vec1): dot_prod += v * vec2[i] mag_1...
search for the most relevant document
def tfidf_search(text, corpus=tfidf_dense, corpus_text=corpus): """ search for the most relevant document """ tokens = tokenize(text, vocabulary=corpus.columns) tfidf_vector_query = np.array(tfidfer.transform([' '.join(tokens)]).todense())[0] query_series = pd.Series(tfidf_vector_query, index=corpus.col...
search for the most relevant document
def topic_search(text, corpus=doc_topic_vectors, pcaer=pcaer, corpus_text=corpus): """ search for the most relevant document """ tokens = tokenize(text, vocabulary=corpus.columns) tfidf_vector_query = np.array(tfidfer.transform([' '.join(tokens)]).todense())[0] topic_vector_query = pcaer.transform([tfid...
Compute average slope and intercept for all X, y pairs Arguments: X (np.array): model input (independent variable) y (np.array): model output (dependent variable) Returns: Linear Regression instance with `slope` and `intercept` attributes References: Ba...
def fit(self, X, y): """ Compute average slope and intercept for all X, y pairs Arguments: X (np.array): model input (independent variable) y (np.array): model output (dependent variable) Returns: Linear Regression instance with `slope` and `intercept` attributes ...
w = w + α * δ * X
def fit(self, X, y, n_iter=None): """w = w + α * δ * X""" self.n_iter = self.n_iter if n_iter is None else n_iter X = getattr(X, 'values', X).reshape(len(X), 1) X_1 = self.homogenize(X) for i in range(self.n_iter): for i in range(0, len(X), 10): # minibatch learning ...
Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True
def looks_like_url(url): """ Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True """ if not isins...
User urlparse to try to parse URL returning None on exception
def try_parse_url(url): """ User urlparse to try to parse URL returning None on exception """ if len(url.strip()) < 4: logger.info('URL too short: {}'.format(url)) return None try: parsed_url = urlparse(url) except ValueError: logger.info('Parse URL ValueError: {}'.format...
Request HTML for the page at the URL indicated and return the url, filename, and remote size TODO: just add remote_size and basename and filename attributes to the urlparse object instead of returning a dict >>> sorted(get_url_filemeta('mozilla.com').items()) [('filename', ''), ('hostname',...
def get_url_filemeta(url): """ Request HTML for the page at the URL indicated and return the url, filename, and remote size TODO: just add remote_size and basename and filename attributes to the urlparse object instead of returning a dict >>> sorted(get_url_filemeta('mozilla.com').items()) [...
r""" Request HTML for the page at the URL indicated and return it's <title> property >>> get_url_title('mozilla.com').strip() 'Internet for people, not profit\n — Mozilla'
def get_url_title(url): r""" Request HTML for the page at the URL indicated and return it's <title> property >>> get_url_title('mozilla.com').strip() 'Internet for people, not profit\n — Mozilla' """ parsed_url = try_parse_url(url) if parsed_url is None: return None try: ...
r""" Get the filename associated with a google drive driveid or drive.google.com URL >>> get_url_filename(driveid='1a-64b6y6xsQr5puUsHX_wxI1orQDercM') 'VGG_VOC0712Plus_SSD_512x512_ft_iter_160000.h5' >>> get_url_filename(url='https://drive.google.com/open?id=' + '1fyDDUcIOSjeiP08vl1WCndcFdtboFXua') 'VGG...
def get_url_filename(url=None, driveid=None): r""" Get the filename associated with a google drive driveid or drive.google.com URL >>> get_url_filename(driveid='1a-64b6y6xsQr5puUsHX_wxI1orQDercM') 'VGG_VOC0712Plus_SSD_512x512_ft_iter_160000.h5' >>> get_url_filename(url='https://drive.google.com/open?id...
For streaming response from requests, download the content one CHUNK at a time
def save_response_content(response, filename='data.csv', destination=os.path.curdir, chunksize=32768): """ For streaming response from requests, download the content one CHUNK at a time """ chunksize = chunksize or 32768 if os.path.sep in filename: full_destination_path = filename else: ...
Download script for google drive shared links Thank you @turdus-merula and Andrew Hundt! https://stackoverflow.com/a/39225039/623735
def download_file_from_google_drive(driveid, filename=None, destination=os.path.curdir): """ Download script for google drive shared links Thank you @turdus-merula and Andrew Hundt! https://stackoverflow.com/a/39225039/623735 """ if '&id=' in driveid: # https://drive.google.com/uc?export=...
Strip off the dl=0 suffix from dropbox links >>> dropbox_basename('https://www.dropbox.com/s/yviic64qv84x73j/aclImdb_v1.tar.gz?dl=1') 'aclImdb_v1.tar.gz'
def dropbox_basename(url): """ Strip off the dl=0 suffix from dropbox links >>> dropbox_basename('https://www.dropbox.com/s/yviic64qv84x73j/aclImdb_v1.tar.gz?dl=1') 'aclImdb_v1.tar.gz' """ filename = os.path.basename(url) match = re.findall(r'\?dl=[0-9]$', filename) if match: re...
Args: inputs: list of sentences (integer lists) max_sequence_length: integer specifying how large should `max_time` dimension be. If None, maximum sequence length would be used Outputs: inputs_time_major: input sentences transformed into t...
def batch(inputs, max_sequence_length=None): """ Args: inputs: list of sentences (integer lists) max_sequence_length: integer specifying how large should `max_time` dimension be. If None, maximum sequence length would be used Outputs: inputs_t...
Generates batches of random integer sequences, sequence length in [length_from, length_to], vocabulary in [vocab_lower, vocab_upper]
def random_sequences(length_from, length_to, vocab_lower, vocab_upper, batch_size): """ Generates batches of random integer sequences, sequence length in [length_from, length_to], vocabulary in [vocab_lower, vocab_upper] """ if length_from > length_t...
Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string >>> find_greeting('Hi Mr. Turing!') 'Hi' >>> find_greeting('Hello, Rosa.') 'Hello' >>> find_greeting("Yo, what's up?") 'Yo' >>> find_greeting("Hello") 'Hello' >>> print(find_greeting("hello")) ...
def find_greeting(s): """ Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string >>> find_greeting('Hi Mr. Turing!') 'Hi' >>> find_greeting('Hello, Rosa.') 'Hello' >>> find_greeting("Yo, what's up?") 'Yo' >>> find_greeting("Hello") 'Hello' >>> ...
Returns a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence.
def sentiment(text): """ Returns a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence. """ sentiment.valence_dict = load_valence_dict() if sentiment.valence_dict is None else sentiment_valence_dict wordsAndEmotico...
Listten for a single utterance (concluded with a 2 sec pause) and return a recording in an Audio object Arguments: energy_threshold (int): minimum audio energy to trigger start of recording (default=300) dynamic_energy_adjustment_damping (float): dyn thresh adjustment slowness: 1=static energy_thre...
def record_audio(source='Microphone', energy_threshold=300, pause_threshold=.9, dynamic_energy_ratio=1.5, dynamic_energy_adjustment_damping=.15, **kwargs): """ Listten for a single utterance (concluded with a 2 sec pause) and return a recording in an Audio object Arguments: energy_thre...
Reads file into list
def file_to_list(in_file): ''' Reads file into list ''' lines = [] for line in in_file: # Strip new line line = line.strip('\n') # Ignore empty lines if line != '': # Ignore comments if line[0] != '#': lines.append(line) return li...
Generates prefixes/suffixes in a short form to parse and remove some redundancy
def generate_add_sub(self): ''' Generates prefixes/suffixes in a short form to parse and remove some redundancy ''' # Prefix or Suffix affix_type = 'p:' if self.opt == "PFX" else 's:' remove_char = '-' + self.char_to_strip if self.char_to_strip != '' else '' return affix_type + ...
Creates derivative of (base) word by adding any affixes that apply
def create_derivative(self, word): ''' Creates derivative of (base) word by adding any affixes that apply ''' result = None if self.char_to_strip != '': if self.opt == "PFX": result = word[len(self.char_to_strip):len(word)] result = self.affix + result...
Adds flag value to applicable compounds
def add_flag_values(self, entry, flag): ''' Adds flag value to applicable compounds ''' if flag in self.flags: self.flags[flag].append(entry)
Generates and returns compound regular expression
def get_regex(self): ''' Generates and returns compound regular expression ''' regex = '' for flag in self.compound: if flag == '?' or flag == '*': regex += flag else: regex += '(' + '|'.join(self.flags[flag]) + ')' return regex
Parses dictionary with according rules
def __parse_dict(self): ''' Parses dictionary with according rules ''' i = 0 lines = self.lines for line in lines: line = line.split('/') word = line[0] flags = line[1] if len(line) > 1 else None # Base Word self.num_words += ...
Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings Returns: DataFrame: columns=['url', 'rating', 'text'], index=MultiIndex(['train_test', 'pos_neg_unsup', 'id']) TODO: Make this more robust/general by allowing the subdirectories ...
def load_imdb_df(dirpath=os.path.join(BIGDATA_PATH, 'aclImdb'), subdirectories=(('train', 'test'), ('pos', 'neg', 'unsup'))): """ Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings Returns: DataFrame: columns=['url', 'rating', 'text'], ...
r""" Load a pretrained GloVE word vector model First header line of GloVE text file should look like: 400000 50\n First vector of GloVE text file should look like: the .12 .22 .32 .42 ... .42 >>> wv = load_glove(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> wv.most_similar('and')[:...
def load_glove(filepath, batch_size=1000, limit=None, verbose=True): r""" Load a pretrained GloVE word vector model First header line of GloVE text file should look like: 400000 50\n First vector of GloVE text file should look like: the .12 .22 .32 .42 ... .42 >>> wv = load_glove(os.pa...
Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 Name: the, dtype: float64
def load_glove_df(filepath, **kwargs): """ Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 ...
Download and parse English->French translation dataset used in Keras seq2seq example
def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'): """ Download and parse English->French translation dataset used in Keras seq2seq example """ download_unzip(url) return pd.read_table(url, compression='zip', header=None, skip_blank_lines=True, sep='\t', skiprows=0, names='en fr'.split())
Load into a DataFrame statements in one language along with their translation into English >>> get_data('zsm').head(1) eng zsm 0 Are you new? Awak baru?
def load_anki_df(language='deu'): """ Load into a DataFrame statements in one language along with their translation into English >>> get_data('zsm').head(1) eng zsm 0 Are you new? Awak baru? """ if os.path.isfile(langua...
Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality
def generate_big_urls_glove(bigurls=None): """ Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality """ bigurls = bigurls or {} for num_dim in (50, 100, 200, 300): # not all of these dimensionality, and training set size combinations were trained by S...
Rename (mv) file(s) from source to dest >>> from tempfile import mkdtemp >>> tmpdir = mkdtemp(suffix='doctest_rename_file', prefix='tmp') >>> fout = ensure_open(os.path.join(tmpdir, 'fake_data.bin.gz'), 'w') >>> fout.write(b'fake nlpia.loaders.rename_file') 30 >>> fout.close() >>> dest = re...
def rename_file(source, dest): """ Rename (mv) file(s) from source to dest >>> from tempfile import mkdtemp >>> tmpdir = mkdtemp(suffix='doctest_rename_file', prefix='tmp') >>> fout = ensure_open(os.path.join(tmpdir, 'fake_data.bin.gz'), 'w') >>> fout.write(b'fake nlpia.loaders.rename_file') 30...
normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file >>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt') >>> pth == normalize_ext_rename(pth) True
def normalize_ext_rename(filepath): """ normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file >>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt') >>> pth == normalize_ext_rename(pth) True """ logger.debug('normalize_ext.filepath=' + str(filepath)...
Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory
def untar(fname, verbose=True): """ Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory """ if fname.lower().endswith(".tar.gz"): dirpath = os.path.join(BIGDATA_PATH, os.path.basename(fname)[:-7]) if os.path.isdir(dirpath): return dirpath with tarfile.o...
Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str
def series_rstrip(series, endswith='/usercomments', ignorecase=True): """ Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str """ return series_strip(series, startswith=None, endswith=endswith, startsorendswith=None, ignorecase=ignorecase)
Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str
def series_lstrip(series, startswith='http://', ignorecase=True): """ Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str """ return series_strip(series, startswith=startswith, endswith=None, startsorendswith=None, ignorecase=ignorecase)
Strip a suffix/prefix str (`endswith`/`startswith` str) from a `df` columns or pd.Series of type str
def series_strip(series, startswith=None, endswith=None, startsorendswith=None, ignorecase=True): """ Strip a suffix/prefix str (`endswith`/`startswith` str) from a `df` columns or pd.Series of type str """ if ignorecase: mask = series.str.lower() endswith = endswith.lower() else: ma...
Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com'
def endswith_strip(s, endswith='.txt', ignorecase=True): """ Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com' """ if ignorecase: ...
Strip a prefix from the beginning of a string >>> startswith_strip('HTtp://TotalGood.com', 'HTTP://') 'TotalGood.com' >>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False) 'HTtp://TotalGood.com'
def startswith_strip(s, startswith='http://', ignorecase=True): """ Strip a prefix from the beginning of a string >>> startswith_strip('HTtp://TotalGood.com', 'HTTP://') 'TotalGood.com' >>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False) 'HTtp://TotalGood.com' "...
Retrieve the HTML tables from a URL and return the longest DataFrame found >>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns Index(['Common and formal names', 'Membership within the UN System[a]', 'Sovereignty dispute[b]', 'Further information on status and r...
def get_longest_table(url='https://www.openoffice.org/dev_docs/source/file_extensions.html', header=0): """ Retrieve the HTML tables from a URL and return the longest DataFrame found >>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns Index(['Common and formal names', 'M...
r""" Retrieve mapping from English letters to l33t like E => 3 or A => /\ or /-\ or @
def get_leet_map(): r""" Retrieve mapping from English letters to l33t like E => 3 or A => /\ or /-\ or @ """ df = get_longest_table( 'https://sites.google.com/site/inhainternetlanguage/different-internet-languages/l33t/list-of-l33ts', header=None) df = df.drop(index=0).iloc[:, :2] df.columns = ...
Retrieve mapping from chat/text abbreviations and acronyms like LMK => Let Me Know
def get_netspeak_map(): """ Retrieve mapping from chat/text abbreviations and acronyms like LMK => Let Me Know """ dfs = pd.read_html('https://www.webopedia.com/quick_ref/textmessageabbreviations.asp') df = dfs[0].drop(index=0) df.columns = ['abbrev', 'definition'] csv_path = os.path.join(DATA_PATH,...
Return this single longest DataFrame that among an array/list/tuple of DataFrames Useful for automagically finding the DataFrame you want when using pd.read_html() on a Wikipedia page.
def longest_table(dfs): """ Return this single longest DataFrame that among an array/list/tuple of DataFrames Useful for automagically finding the DataFrame you want when using pd.read_html() on a Wikipedia page. """ sorted_indices = sorted((len(df if hasattr(df, '__len__') else []), i) for i, df in en...
Load a DataFrame of filename extensions from the indicated url >>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html') >>> df.head(2) ext description 0 .a UNIX static library file. 1 .asm Non-UNIX assembler source file...
def get_filename_extensions(url='https://www.webopedia.com/quick_ref/fileextensionsfull.asp'): """ Load a DataFrame of filename extensions from the indicated url >>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html') >>> df.head(2) ext ...
r""" Migrate the big_urls table schema/structure from a dict of lists to a dict of dicts >>> big_urls = {'x': (1, 2, 3, "4x"), 'y': ("yme", "cause")} >>> inplace = migrate_big_urls(big_urls=big_urls) >>> inplace {'x': {0: 1, 1: 2, 2: 3, 3: '4x'}, 'y': {0: 'yme', 1: 'cause'}} >>> inplace is big_urls...
def migrate_big_urls(big_urls=BIG_URLS, inplace=True): r""" Migrate the big_urls table schema/structure from a dict of lists to a dict of dicts >>> big_urls = {'x': (1, 2, 3, "4x"), 'y': ("yme", "cause")} >>> inplace = migrate_big_urls(big_urls=big_urls) >>> inplace {'x': {0: 1, 1: 2, 2: 3, 3: '4x'...
r""" Unzip GloVE models and convert to word2vec binary models (gensim.KeyedVectors) The only kinds of files that are returned are "*.asc" and "*.txt" and only after renaming.
def unzip(filepath, verbose=True): r""" Unzip GloVE models and convert to word2vec binary models (gensim.KeyedVectors) The only kinds of files that are returned are "*.asc" and "*.txt" and only after renaming. """ filepath = expand_filepath(filepath) filename = os.path.basename(filepath) tqdm_p...
If name looks like a url, with an http, add an entry for it in BIG_URLS
def create_big_url(name): """ If name looks like a url, with an http, add an entry for it in BIG_URLS """ # BIG side effect global BIG_URLS filemeta = get_url_filemeta(name) if not filemeta: return None filename = filemeta['filename'] remote_size = filemeta['remote_size'] url = f...
FIXME: Get file size, hostname, path metadata from FTP server using parsed_url (urlparse)
def get_ftp_filemeta(parsed_url, username='anonymous', password='nlpia@totalgood.com'): """ FIXME: Get file size, hostname, path metadata from FTP server using parsed_url (urlparse)""" return dict( url=parsed_url.geturl(), hostname=parsed_url.hostname, path=parsed_url.path, username=(parsed_url....
r""" Download CSV or HTML tables listed in `names`, unzip and to DATA_PATH/`names`.csv .txt etc TODO: move to web or data_utils or futils Also normalizes file name extensions (.bin.gz -> .w2v.bin.gz). Uses table in data_info.csv (internal DATA_INFO) to determine URL or file path from dataset name. Also...
def download_unzip(names=None, normalize_filenames=False, verbose=True): r""" Download CSV or HTML tables listed in `names`, unzip and to DATA_PATH/`names`.csv .txt etc TODO: move to web or data_utils or futils Also normalizes file name extensions (.bin.gz -> .w2v.bin.gz). Uses table in data_info.csv (...
Uses stream=True and a reasonable chunk size to be able to download large (GB) files over https Downloading this small file takes 1.5 sec. All subsequent "downloads" takes .6 sec to verify path and size. >>> import time >>> meta = BIG_URLS['ubuntu_dialog_test'] >>> pathend = os.path.join(*('nlpia/src/n...
def download_file(url, data_path=BIGDATA_PATH, filename=None, size=None, chunk_size=4096, normalize_filename=False, verbose=True): """Uses stream=True and a reasonable chunk size to be able to download large (GB) files over https Downloading this small file takes 1.5 sec. All subsequent "downloads" takes .6 se...
Convert a dataset in a local file (usually a CSV) into a Pandas DataFrame TODO: should be called read_named_dataset Args: `name` is assumed not to have an extension (like ".csv"), alternative extensions are tried automatically.file
def read_named_csv(name, data_path=DATA_PATH, nrows=None, verbose=True): """ Convert a dataset in a local file (usually a CSV) into a Pandas DataFrame TODO: should be called read_named_dataset Args: `name` is assumed not to have an extension (like ".csv"), alternative extensions are tried automaticall...
Load data from a json, csv, or txt file if it exists in the data dir. References: [cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp) [cities](http://download.geonames.org/export/dump/cities.zip) [cities_us](http://download.geonames.org/export/dump/cities_us.zip) >>> ...
def get_data(name='sms-spam', nrows=None, limit=None): """ Load data from a json, csv, or txt file if it exists in the data dir. References: [cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp) [cities](http://download.geonames.org/export/dump/cities.zip) [cities_us](ht...
Like pandas.read_csv, but loads and concatenates (df.append(df)s) DataFrames together
def multifile_dataframe(paths=['urbanslang{}of4.csv'.format(i) for i in range(1, 5)], header=0, index_col=None): """Like pandas.read_csv, but loads and concatenates (df.append(df)s) DataFrames together""" df = pd.DataFrame() for p in paths: df = df.append(read_csv(p, header=header, index_col=index_c...
Retrieve the Query number for a wikidata database of metadata about a particular article >>> print(get_wikidata_qnum(wikiarticle="Andromeda Galaxy", wikisite="enwiki")) Q2469
def get_wikidata_qnum(wikiarticle, wikisite): """Retrieve the Query number for a wikidata database of metadata about a particular article >>> print(get_wikidata_qnum(wikiarticle="Andromeda Galaxy", wikisite="enwiki")) Q2469 """ resp = requests.get('https://www.wikidata.org/w/api.php', timeout=5, pa...
r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns` >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here']) >>> normalize_column_names(df) ['hello_world', 'not_here']
def normalize_column_names(df): r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns` >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here']) >>> normalize_column_names(df) ['hello_world', 'not_here'] """ columns = df.columns if hasattr(df, ...
r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year 10/2017-3/2018 Presiden...
def clean_column_values(df, inplace=True): r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year ...
Clean the table of city metadata from download.geoname.org/export/dump/{filename} Reference: http://download.geonames.org/export/dump/readme.txt 'cities1000.txt' and 'allCountries.txt' have the following tab-separated fields: 0 geonameid : integer id of record in geonames database 1 n...
def load_geonames(filepath='http://download.geonames.org/export/dump/cities1000.zip'): """Clean the table of city metadata from download.geoname.org/export/dump/{filename} Reference: http://download.geonames.org/export/dump/readme.txt 'cities1000.txt' and 'allCountries.txt' have the following tab-se...
WARN: Not a good source of city names. This table has many errors, even after cleaning
def load_geo_adwords(filename='AdWords API Location Criteria 2017-06-26.csv.gz'): """ WARN: Not a good source of city names. This table has many errors, even after cleaning""" df = pd.read_csv(filename, header=0, index_col=0, low_memory=False) df.columns = [c.replace(' ', '_').lower() for c in df.columns] ...
Load a dataframe of ~100k raw (uncollated) movie lines from the cornell movies dialog corpus >>> local_filepath = download_file(BIG_URLS['cornell_movie_dialogs_corpus'][0]) >>> df = clean_cornell_movies(filename='cornell_movie_dialogs_corpus.zip') >>> df.describe(include='all') user mov...
def clean_cornell_movies(filename='cornell_movie_dialogs_corpus.zip', subdir='cornell movie-dialogs corpus'): """ Load a dataframe of ~100k raw (uncollated) movie lines from the cornell movies dialog corpus >>> local_filepath = download_file(BIG_URLS['cornell_movie_dialogs_corpus'][0]) >>> df = clean_c...
Get the first word vector in a GloVE file and return its dimensionality or False if not a vector >>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt')) False
def isglove(filepath): """ Get the first word vector in a GloVE file and return its dimensionality or False if not a vector >>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt')) False """ with ensure_open(filepath, 'r') as f: header_line = f.readline() vector_line = f.readline(...
r""" Use the SpaCy parser to parse and tag natural language strings. Load the SpaCy parser language model lazily and share it among all nlpia modules. Probably unnecessary, since SpaCy probably takes care of this with `spacy.load()` >>> _parse is None True >>> doc = nlp("Domo arigatto Mr. Roboto."...
def nlp(texts, lang='en', linesep=None, verbose=True): r""" Use the SpaCy parser to parse and tag natural language strings. Load the SpaCy parser language model lazily and share it among all nlpia modules. Probably unnecessary, since SpaCy probably takes care of this with `spacy.load()` >>> _parse is ...
Create a decoder with the requested language model
def get_decoder(libdir=None, modeldir=None, lang='en-us'): """ Create a decoder with the requested language model """ modeldir = modeldir or (os.path.join(libdir, 'model') if libdir else MODELDIR) libdir = os.path.dirname(modeldir) config = ps.Decoder.default_config() config.set_string('-hmm', os.pa...
Decode streaming audio data from raw binary file on disk.
def transcribe(decoder, audio_file, libdir=None): """ Decode streaming audio data from raw binary file on disk. """ decoder = get_decoder() decoder.start_utt() stream = open(audio_file, 'rb') while True: buf = stream.read(1024) if buf: decoder.process_raw(buf, False, Fal...
Parse documents from a .txt file assuming 1 document per line, yielding lists of filtered tokens
def get_texts(self): """ Parse documents from a .txt file assuming 1 document per line, yielding lists of filtered tokens """ with self.getstream() as text_stream: for i, line in enumerate(text_stream): line = to_unicode(line) line = (TweetCorpus.case_normaliz...
r"""Ensure that strings are unicode (UTF-8 encoded). Evaluate bytes literals that are sometimes accidentally created by str(b'whatever') >>> to_unicode(b'whatever') 'whatever' >>> to_unicode(b'b"whatever"') 'whatever' >>> to_unicode(repr(b'b"whatever"')) 'whatever' >>> to_unicode(str(b...
def to_unicode(sorb, allow_eval=False): r"""Ensure that strings are unicode (UTF-8 encoded). Evaluate bytes literals that are sometimes accidentally created by str(b'whatever') >>> to_unicode(b'whatever') 'whatever' >>> to_unicode(b'b"whatever"') 'whatever' >>> to_unicode(repr(b'b"whatever...
Parse documents from a .txt file assuming 1 document per line, yielding lists of filtered tokens
def get_texts(self): """ Parse documents from a .txt file assuming 1 document per line, yielding lists of filtered tokens """ with self.getstream() as text_stream: for i, line in enumerate(text_stream): line = SMSCorpus.case_normalizer(line) if self.mask is no...
Uses stream=True and a reasonable chunk size to be able to download large (GB) files over https
def download_file(url, data_path='.', filename=None, size=None, chunk_size=4096, verbose=True): """Uses stream=True and a reasonable chunk size to be able to download large (GB) files over https""" if filename is None: filename = dropbox_basename(url) file_path = os.path.join(data_path, filename) ...
This is dependent on your training data source but we will try to generalize it as best as possible.
def pre_process_data(filepath): """ This is dependent on your training data source but we will try to generalize it as best as possible. """ positive_path = os.path.join(filepath, 'pos') negative_path = os.path.join(filepath, 'neg') pos_label = 1 neg_label = 0 dataset = [] for fil...
For a given dataset pad with zero vectors or truncate to maxlen
def pad_trunc(data, maxlen): """ For a given dataset pad with zero vectors or truncate to maxlen """ new_data = [] # Create a vector of 0's the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sampl...
Shift to lower case, replace unknowns with UNK, and listify
def clean_data(data): """ Shift to lower case, replace unknowns with UNK, and listify """ new_data = [] VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; ' for sample in data: new_sample = [] for char in sample[1].lower(): # Just grab the string, not the label if char in...
We truncate to maxlen or add in PAD tokens
def char_pad_trunc(data, maxlen): """ We truncate to maxlen or add in PAD tokens """ new_dataset = [] for sample in data: if len(sample) > maxlen: new_data = sample[:maxlen] elif len(sample) < maxlen: pads = maxlen - len(sample) new_data = sample + ['PAD']...
Modified from Keras LSTM example
def create_dicts(data): """ Modified from Keras LSTM example""" chars = set() for sample in data: chars.update(set(sample)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) return char_indices, indices_char
One hot encode the tokens Args: dataset list of lists of tokens char_indices dictionary of {key=character, value=index to use encoding vector} maxlen int Length of each sample Return: np array of shape (samples, tokens, encoding length)
def onehot_encode(dataset, char_indices, maxlen): """ One hot encode the tokens Args: dataset list of lists of tokens char_indices dictionary of {key=character, value=index to use encoding vector} maxlen int Length of each sample Return: np array of shape (samples, ...
Sign correction to ensure deterministic output from SVD. Adjusts the columns of u and the rows of v such that the loadings in the columns in u that are largest in absolute value are always positive. Parameters ---------- u, v : ndarray u and v are the output of `linalg.svd` or `sklea...
def svd_flip(u, v, u_based_decision=True): """Sign correction to ensure deterministic output from SVD. Adjusts the columns of u and the rows of v such that the loadings in the columns in u that are largest in absolute value are always positive. Parameters ---------- u, v : ndarray u and ...
Fit the model by computing full SVD on X
def _fit_full(self=self, X=X, n_components=6): """Fit the model by computing full SVD on X""" n_samples, n_features = X.shape # Center data self.mean_ = np.mean(X, axis=0) print(self.mean_) X -= self.mean_ print(X.round(2)) U, S, V = linalg.svd(X, full_matrices=False) print(V.round...
Strip trailing </aiml> tag and concatenate all valid AIML files found in the ZIP.
def concatenate_aiml(path='aiml-en-us-foundation-alice.v1-9.zip', outfile='aiml-en-us-foundation-alice.v1-9.aiml'): """Strip trailing </aiml> tag and concatenate all valid AIML files found in the ZIP.""" path = find_data_path(path) or path zf = zipfile.ZipFile(path) for name in zf.namelist(): i...
Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths
def extract_aiml(path='aiml-en-us-foundation-alice.v1-9'): """ Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths """ path = find_data_path(path) or path if os.path.isdir(path): paths = os.listdir(path) paths = [os.path.join(path, p) for p in paths] e...
Create an aiml_bot.Bot brain from an AIML zip file or directory of AIML files
def create_brain(path='aiml-en-us-foundation-alice.v1-9.zip'): """ Create an aiml_bot.Bot brain from an AIML zip file or directory of AIML files """ path = find_data_path(path) or path bot = Bot() num_templates = bot._brain.template_count paths = extract_aiml(path=path) for path in paths: ...
Use bitly or similar minifier to shrink all URLs in text files within a folder structure. Used for the NLPIA manuscript directory for Manning Publishing bitly API: https://dev.bitly.com/links.html Args: path (str): Directory or file path ext (str): File name extension to filter text files by....
def minify_urls(filepath, ext='asc', url_regex=None, output_ext='.urls_minified', access_token=None): """ Use bitly or similar minifier to shrink all URLs in text files within a folder structure. Used for the NLPIA manuscript directory for Manning Publishing bitly API: https://dev.bitly.com/links.html ...
Return a str of separated tokens found within a slugLike_This => 'slug Like This' >>> delimit_slug("slugLike_ThisW/aTLA's") 'slug Like This W a TLA s' >>> delimit_slug('slugLike_ThisW/aTLA', '|') 'slug|Like|This|W|a|TLA'
def delimit_slug(slug, sep=' '): """ Return a str of separated tokens found within a slugLike_This => 'slug Like This' >>> delimit_slug("slugLike_ThisW/aTLA's") 'slug Like This W a TLA s' >>> delimit_slug('slugLike_ThisW/aTLA', '|') 'slug|Like|This|W|a|TLA' """ hyphenated_slug = re.sub(CRE_...
r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!'
def clean_asciidoc(text): r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!' """ text = re.sub(r'(\b|^)[\[_*]{1,...
Use dead-simple regex to split text into sentences. Very poor accuracy. >>> split_sentences_regex("Hello World. I'm I.B.M.'s Watson. --Watson") ['Hello World.', "I'm I.B.M.'s Watson.", '--Watson']
def split_sentences_regex(text): """ Use dead-simple regex to split text into sentences. Very poor accuracy. >>> split_sentences_regex("Hello World. I'm I.B.M.'s Watson. --Watson") ['Hello World.', "I'm I.B.M.'s Watson.", '--Watson'] """ parts = regex.split(r'([a-zA-Z0-9][.?!])[\s$]', text) sen...
r""" You must download a spacy language model with python -m download 'en' The default English language model for spacy tends to be a lot more agressive than NLTK's punkt: >>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) --Watson 2.0") ['Hi Ms. Lovelace.', "I'm a wanna-\nbe h...
def split_sentences_spacy(text, language_model='en'): r""" You must download a spacy language model with python -m download 'en' The default English language model for spacy tends to be a lot more agressive than NLTK's punkt: >>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) -...
Return a list of all sentences and empty lines. TODO: 1. process each line with an aggressive sentence segmenter, like DetectorMorse 2. process our manuscript to create a complete-sentence and heading training set normalized/simplified syntax net tree is the input feature set common word...
def segment_sentences(path=os.path.join(DATA_PATH, 'book'), splitter=split_sentences_nltk, **find_files_kwargs): """ Return a list of all sentences and empty lines. TODO: 1. process each line with an aggressive sentence segmenter, like DetectorMorse 2. process our manuscript to create a complet...
Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output json file with properly quoted strings in list of affixes Returns: list of all w...
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'): """Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output ...
Count the words in a corpus and return a TfidfVectorizer() as well as all the TFIDF vecgtors for the corpus Args: docs (iterable of strs): a sequence of documents (strings) Returns: (TfidfVectorizer, tfidf_vectors)
def tfidf_corpus(docs=CORPUS): """ Count the words in a corpus and return a TfidfVectorizer() as well as all the TFIDF vecgtors for the corpus Args: docs (iterable of strs): a sequence of documents (strings) Returns: (TfidfVectorizer, tfidf_vectors) """ vectorizer = TfidfVectorizer() ...
Split a string on __eot__ markders (turns)
def split_turns(s, splitter=re.compile('__eot__')): """ Split a string on __eot__ markders (turns) """ for utterance in splitter.split(s): utterance = utterance.replace('__eou__', '\n') utterance = utterance.replace('__eot__', '') if len(utterance.strip()): yield utterance
Split all strings in df.Context and df.Utterance on __eot__ (turn) markers
def preprocess_ubuntu_corpus(df): """Split all strings in df.Context and df.Utterance on __eot__ (turn) markers """ statements = [] replies = [] for i, record in tqdm(df.iterrows()): turns = list(split_turns(record.Context)) statement = turns[-1] if len(turns) else '\n' # <1> st...
Print statements paired with replies, formatted for easy review
def format_ubuntu_dialog(df): """ Print statements paired with replies, formatted for easy review """ s = '' for i, record in df.iterrows(): statement = list(split_turns(record.Context))[-1] # <1> reply = list(split_turns(record.Utterance))[-1] # <2> s += 'Statement: {}\n'.format(s...
Like os.path.splitext except splits compound extensions as one long one >>> splitext('~/.bashrc.asciidoc.ext.ps4.42') ('~/.bashrc', '.asciidoc.ext.ps4.42') >>> splitext('~/.bash_profile') ('~/.bash_profile', '')
def splitext(filepath): """ Like os.path.splitext except splits compound extensions as one long one >>> splitext('~/.bashrc.asciidoc.ext.ps4.42') ('~/.bashrc', '.asciidoc.ext.ps4.42') >>> splitext('~/.bash_profile') ('~/.bash_profile', '') """ exts = getattr(CRE_FILENAME_EXT.search(filepath...
Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime
def to_tsv(): """ Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime """ with open(os.path.join(DATA_PATH, 'regexes.tsv'), mode='wt') as fout: vars = copy.copy(tuple(globals().items())) for k, v in vars: if k.lower().startswith('cre_'): ...
Setup basic logging Args: loglevel (int): minimum loglevel for emitting messages
def stdout_logging(loglevel=logging.INFO): """Setup basic logging Args: loglevel (int): minimum loglevel for emitting messages """ logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(lineno)d: %(message)s" logging.config.dictConfig(level=loglevel, stream=sys.stdout, ...
Plot an offline scatter plot colored according to the categories in the 'name' column. >> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv') >> offline_plotly(df)
def offline_plotly_scatter3d(df, x=0, y=1, z=-1): """ Plot an offline scatter plot colored according to the categories in the 'name' column. >> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv') >> offline_plotly(df) """ data = [] # clusters = [] colors = ...
Add a text label to the plot of a DataFrame indicated by the provided axis (ax). Reference: https://stackoverflow.com/a/40979683/623735
def annotate(row, ax, x='x', y='y', text='name', xytext=(7, -5), textcoords='offset points', **kwargs): """Add a text label to the plot of a DataFrame indicated by the provided axis (ax). Reference: https://stackoverflow.com/a/40979683/623735 """ # idx = row.name text = row[text] if text in ...
r""" Write a plotly scatter plot to HTML file that doesn't require server >>> from nlpia.loaders import get_data >>> df = get_data('etpinard') # pd.read_csv('https://plot.ly/~etpinard/191.csv') >>> df.columns = [eval(c) if c[0] in '"\'' else str(c) for c in df.columns] >>> data = {'data': [ ... ...
def offline_plotly_data(data, filename=None, config=None, validate=True, default_width='100%', default_height=525, global_requirejs=False): r""" Write a plotly scatter plot to HTML file that doesn't require server >>> from nlpia.loaders import get_data >>> df = get_data('etpinard') ...
Reformat a dataframe in etpinard's format for use in plot functions and sklearn models
def normalize_etpinard_df(df='https://plot.ly/~etpinard/191.csv', columns='x y size text'.split(), category_col='category', possible_categories=['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']): """Reformat a dataframe in etpinard's format for use in plot functions and sklearn models"""...
r"""Interactive scatterplot of a DataFrame with the size and color of circles linke to two columns config keys: fillFrame setBackground displaylogo sendData showLink linkText staticPlot scrollZoom plot3dPixelRatio displayModeBar showTips workspace doubleClick autosizable editable layout keys: ...
def offline_plotly_scatter_bubble(df, x='x', y='y', size_col='size', text_col='text', category_col='category', possible_categories=None, filename=None, config={'displaylogo': False}, x...
Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017'
def format_hex(i, num_bytes=4, prefix='0x'): """ Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017' """ prefix = str(prefix or '') i = int(i or 0) return prefix + '{0:0{1}x}'.format(i, num_bytes)
Ensure there's a scheme specified at the beginning of a url, defaulting to http:// >>> prepend_http('duckduckgo.com') 'http://duckduckgo.com'
def prepend_http(url): """ Ensure there's a scheme specified at the beginning of a url, defaulting to http:// >>> prepend_http('duckduckgo.com') 'http://duckduckgo.com' """ url = url.lstrip() if not urlparse(url).scheme: return 'http://' + url return url
r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "http://") >>> is_up_url("duckduckgo.com") # a more pri...
def is_up_url(url, allow_redirects=False, timeout=5): r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "ht...
r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bullet \n##bad\n# hello\n ### world\n') [(0, '- bullet '), (2, 'bad')...
def get_markdown_levels(lines, levels=set((0, 1, 2, 3, 4, 5, 6))): r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bul...