id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
32,400
paramiko/paramiko
paramiko/client.py
SSHClient.close
def close(self): """ Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It's good practice to `close` your client obj...
python
def close(self): """ Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It's good practice to `close` your client obj...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_transport", "is", "None", ":", "return", "self", ".", "_transport", ".", "close", "(", ")", "self", ".", "_transport", "=", "None", "if", "self", ".", "_agent", "is", "not", "None", ":", "...
Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It's good practice to `close` your client objects anytime you're done ...
[ "Close", "this", "SSHClient", "and", "its", "underlying", ".", "Transport", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L440-L457
32,401
paramiko/paramiko
paramiko/client.py
SSHClient.exec_command
def exec_command( self, command, bufsize=-1, timeout=None, get_pty=False, environment=None, ): """ Execute a command on the SSH server. A new `.Channel` is opened and the requested command is executed. The command's input and output s...
python
def exec_command( self, command, bufsize=-1, timeout=None, get_pty=False, environment=None, ): """ Execute a command on the SSH server. A new `.Channel` is opened and the requested command is executed. The command's input and output s...
[ "def", "exec_command", "(", "self", ",", "command", ",", "bufsize", "=", "-", "1", ",", "timeout", "=", "None", ",", "get_pty", "=", "False", ",", "environment", "=", "None", ",", ")", ":", "chan", "=", "self", ".", "_transport", ".", "open_session", ...
Execute a command on the SSH server. A new `.Channel` is opened and the requested command is executed. The command's input and output streams are returned as Python ``file``-like objects representing stdin, stdout, and stderr. :param str command: the command to execute :param ...
[ "Execute", "a", "command", "on", "the", "SSH", "server", ".", "A", "new", ".", "Channel", "is", "opened", "and", "the", "requested", "command", "is", "executed", ".", "The", "command", "s", "input", "and", "output", "streams", "are", "returned", "as", "P...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L459-L509
32,402
paramiko/paramiko
paramiko/client.py
SSHClient.invoke_shell
def invoke_shell( self, term="vt100", width=80, height=24, width_pixels=0, height_pixels=0, environment=None, ): """ Start an interactive shell session on the SSH server. A new `.Channel` is opened and connected to a pseudo-terminal us...
python
def invoke_shell( self, term="vt100", width=80, height=24, width_pixels=0, height_pixels=0, environment=None, ): """ Start an interactive shell session on the SSH server. A new `.Channel` is opened and connected to a pseudo-terminal us...
[ "def", "invoke_shell", "(", "self", ",", "term", "=", "\"vt100\"", ",", "width", "=", "80", ",", "height", "=", "24", ",", "width_pixels", "=", "0", ",", "height_pixels", "=", "0", ",", "environment", "=", "None", ",", ")", ":", "chan", "=", "self", ...
Start an interactive shell session on the SSH server. A new `.Channel` is opened and connected to a pseudo-terminal using the requested terminal type and size. :param str term: the terminal type to emulate (for example, ``"vt100"``) :param int width: the width (in character...
[ "Start", "an", "interactive", "shell", "session", "on", "the", "SSH", "server", ".", "A", "new", ".", "Channel", "is", "opened", "and", "connected", "to", "a", "pseudo", "-", "terminal", "using", "the", "requested", "terminal", "type", "and", "size", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L511-L539
32,403
Kaggle/kaggle-api
kaggle/models/kernel_push_request.py
KernelPushRequest.language
def language(self, language): """Sets the language of this KernelPushRequest. The language that the kernel is written in # noqa: E501 :param language: The language of this KernelPushRequest. # noqa: E501 :type: str """ if language is None: raise ValueError...
python
def language(self, language): """Sets the language of this KernelPushRequest. The language that the kernel is written in # noqa: E501 :param language: The language of this KernelPushRequest. # noqa: E501 :type: str """ if language is None: raise ValueError...
[ "def", "language", "(", "self", ",", "language", ")", ":", "if", "language", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `language`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"python\"", ",", "\"r\"", ",", "\...
Sets the language of this KernelPushRequest. The language that the kernel is written in # noqa: E501 :param language: The language of this KernelPushRequest. # noqa: E501 :type: str
[ "Sets", "the", "language", "of", "this", "KernelPushRequest", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/models/kernel_push_request.py#L229-L246
32,404
Kaggle/kaggle-api
kaggle/models/kernel_push_request.py
KernelPushRequest.kernel_type
def kernel_type(self, kernel_type): """Sets the kernel_type of this KernelPushRequest. The type of kernel. Cannot be changed once the kernel has been created # noqa: E501 :param kernel_type: The kernel_type of this KernelPushRequest. # noqa: E501 :type: str """ if ker...
python
def kernel_type(self, kernel_type): """Sets the kernel_type of this KernelPushRequest. The type of kernel. Cannot be changed once the kernel has been created # noqa: E501 :param kernel_type: The kernel_type of this KernelPushRequest. # noqa: E501 :type: str """ if ker...
[ "def", "kernel_type", "(", "self", ",", "kernel_type", ")", ":", "if", "kernel_type", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `kernel_type`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"script\"", ",", "\"noteb...
Sets the kernel_type of this KernelPushRequest. The type of kernel. Cannot be changed once the kernel has been created # noqa: E501 :param kernel_type: The kernel_type of this KernelPushRequest. # noqa: E501 :type: str
[ "Sets", "the", "kernel_type", "of", "this", "KernelPushRequest", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/models/kernel_push_request.py#L260-L277
32,405
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.read_config_environment
def read_config_environment(self, config_data=None, quiet=False): """read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a uniqu...
python
def read_config_environment(self, config_data=None, quiet=False): """read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a uniqu...
[ "def", "read_config_environment", "(", "self", ",", "config_data", "=", "None", ",", "quiet", "=", "False", ")", ":", "# Add all variables that start with KAGGLE_ to config data", "if", "config_data", "is", "None", ":", "config_data", "=", "{", "}", "for", "key", ...
read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a unique namespace. Parameters ========== config_d...
[ "read_config_environment", "is", "the", "second", "effort", "to", "get", "a", "username", "and", "key", "to", "authenticate", "to", "the", "Kaggle", "API", ".", "The", "environment", "keys", "are", "equivalent", "to", "the", "kaggle", ".", "json", "file", "b...
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L121-L142
32,406
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi._load_config
def _load_config(self, config_data): """the final step of the authenticate steps, where we load the values from config_data into the Configuration object. Parameters ========== config_data: a dictionary with configuration values (keys) to read ...
python
def _load_config(self, config_data): """the final step of the authenticate steps, where we load the values from config_data into the Configuration object. Parameters ========== config_data: a dictionary with configuration values (keys) to read ...
[ "def", "_load_config", "(", "self", ",", "config_data", ")", ":", "# Username and password are required.", "for", "item", "in", "[", "self", ".", "CONFIG_NAME_USER", ",", "self", ".", "CONFIG_NAME_KEY", "]", ":", "if", "item", "not", "in", "config_data", ":", ...
the final step of the authenticate steps, where we load the values from config_data into the Configuration object. Parameters ========== config_data: a dictionary with configuration values (keys) to read into self.config_values
[ "the", "final", "step", "of", "the", "authenticate", "steps", "where", "we", "load", "the", "values", "from", "config_data", "into", "the", "Configuration", "object", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L146-L199
32,407
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.read_config_file
def read_config_file(self, config_data=None, quiet=False): """read_config_file is the first effort to get a username and key to authenticate to the Kaggle API. Since we can get the username and password from the environment, it's not required. Parameters ========== ...
python
def read_config_file(self, config_data=None, quiet=False): """read_config_file is the first effort to get a username and key to authenticate to the Kaggle API. Since we can get the username and password from the environment, it's not required. Parameters ========== ...
[ "def", "read_config_file", "(", "self", ",", "config_data", "=", "None", ",", "quiet", "=", "False", ")", ":", "if", "config_data", "is", "None", ":", "config_data", "=", "{", "}", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "config", "...
read_config_file is the first effort to get a username and key to authenticate to the Kaggle API. Since we can get the username and password from the environment, it's not required. Parameters ========== config_data: the Configuration object to save a username and...
[ "read_config_file", "is", "the", "first", "effort", "to", "get", "a", "username", "and", "key", "to", "authenticate", "to", "the", "Kaggle", "API", ".", "Since", "we", "can", "get", "the", "username", "and", "password", "from", "the", "environment", "it", ...
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L201-L237
32,408
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi._read_config_file
def _read_config_file(self): """read in the configuration file, a json file defined at self.config""" try: with open(self.config, 'r') as f: config_data = json.load(f) except FileNotFoundError: config_data = {} return config_data
python
def _read_config_file(self): """read in the configuration file, a json file defined at self.config""" try: with open(self.config, 'r') as f: config_data = json.load(f) except FileNotFoundError: config_data = {} return config_data
[ "def", "_read_config_file", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "config", ",", "'r'", ")", "as", "f", ":", "config_data", "=", "json", ".", "load", "(", "f", ")", "except", "FileNotFoundError", ":", "config_data", "=", ...
read in the configuration file, a json file defined at self.config
[ "read", "in", "the", "configuration", "file", "a", "json", "file", "defined", "at", "self", ".", "config" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L239-L248
32,409
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi._write_config_file
def _write_config_file(self, config_data, indent=2): """write config data to file. Parameters ========== config_data: the Configuration object to save a username and password, if defined indent: number of tab indentations to use when writing j...
python
def _write_config_file(self, config_data, indent=2): """write config data to file. Parameters ========== config_data: the Configuration object to save a username and password, if defined indent: number of tab indentations to use when writing j...
[ "def", "_write_config_file", "(", "self", ",", "config_data", ",", "indent", "=", "2", ")", ":", "with", "open", "(", "self", ".", "config", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "config_data", ",", "f", ",", "indent", "=", "in...
write config data to file. Parameters ========== config_data: the Configuration object to save a username and password, if defined indent: number of tab indentations to use when writing json
[ "write", "config", "data", "to", "file", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L250-L260
32,410
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.get_default_download_dir
def get_default_download_dir(self, *subdirs): """ Get the download path for a file. If not defined, return default from config. Parameters ========== subdirs: a single (or list of) subfolders under the basepath """ # Look up value for key "path" i...
python
def get_default_download_dir(self, *subdirs): """ Get the download path for a file. If not defined, return default from config. Parameters ========== subdirs: a single (or list of) subfolders under the basepath """ # Look up value for key "path" i...
[ "def", "get_default_download_dir", "(", "self", ",", "*", "subdirs", ")", ":", "# Look up value for key \"path\" in the config", "path", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_PATH", ")", "# If not set in config, default to present working direct...
Get the download path for a file. If not defined, return default from config. Parameters ========== subdirs: a single (or list of) subfolders under the basepath
[ "Get", "the", "download", "path", "for", "a", "file", ".", "If", "not", "defined", "return", "default", "from", "config", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L321-L336
32,411
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.print_config_value
def print_config_value(self, name, prefix='- ', separator=': '): """print a single configuration value, based on a prefix and separator Parameters ========== name: the key of the config valur in self.config_values to print prefix: the prefix to print separ...
python
def print_config_value(self, name, prefix='- ', separator=': '): """print a single configuration value, based on a prefix and separator Parameters ========== name: the key of the config valur in self.config_values to print prefix: the prefix to print separ...
[ "def", "print_config_value", "(", "self", ",", "name", ",", "prefix", "=", "'- '", ",", "separator", "=", "': '", ")", ":", "value_out", "=", "'None'", "if", "name", "in", "self", ".", "config_values", "and", "self", ".", "config_values", "[", "name", "]...
print a single configuration value, based on a prefix and separator Parameters ========== name: the key of the config valur in self.config_values to print prefix: the prefix to print separator: the separator to use (default is : )
[ "print", "a", "single", "configuration", "value", "based", "on", "a", "prefix", "and", "separator" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L338-L351
32,412
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competitions_list
def competitions_list(self, group=None, category=None, sort_by=None, page=1, search=None): """ make call to list competitions, format the response, and return a list of C...
python
def competitions_list(self, group=None, category=None, sort_by=None, page=1, search=None): """ make call to list competitions, format the response, and return a list of C...
[ "def", "competitions_list", "(", "self", ",", "group", "=", "None", ",", "category", "=", "None", ",", "sort_by", "=", "None", ",", "page", "=", "1", ",", "search", "=", "None", ")", ":", "valid_groups", "=", "[", "'general'", ",", "'entered'", ",", ...
make call to list competitions, format the response, and return a list of Competition instances Parameters ========== page: the page to return (default is 1) search: a search term to use (default is empty string) sort_by: how to sort the result, ...
[ "make", "call", "to", "list", "competitions", "format", "the", "response", "and", "return", "a", "list", "of", "Competition", "instances" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L369-L415
32,413
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competitions_list_cli
def competitions_list_cli(self, group=None, category=None, sort_by=None, page=1, search=None, csv_display=False): """ a wrapper for ...
python
def competitions_list_cli(self, group=None, category=None, sort_by=None, page=1, search=None, csv_display=False): """ a wrapper for ...
[ "def", "competitions_list_cli", "(", "self", ",", "group", "=", "None", ",", "category", "=", "None", ",", "sort_by", "=", "None", ",", "page", "=", "1", ",", "search", "=", "None", ",", "csv_display", "=", "False", ")", ":", "competitions", "=", "self...
a wrapper for competitions_list for the client. Parameters ========== group: group to filter result to category: category to filter result to sort_by: how to sort the result, see valid_sort_by for options page: the page to return (default is 1) ...
[ "a", "wrapper", "for", "competitions_list", "for", "the", "client", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L417-L451
32,414
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_submit
def competition_submit(self, file_name, message, competition, quiet=False): """ submit a competition! Parameters ========== file_name: the competition metadata file message: the submission description competition: the competition name quie...
python
def competition_submit(self, file_name, message, competition, quiet=False): """ submit a competition! Parameters ========== file_name: the competition metadata file message: the submission description competition: the competition name quie...
[ "def", "competition_submit", "(", "self", ",", "file_name", ",", "message", ",", "competition", ",", "quiet", "=", "False", ")", ":", "if", "competition", "is", "None", ":", "competition", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_...
submit a competition! Parameters ========== file_name: the competition metadata file message: the submission description competition: the competition name quiet: suppress verbose output (default is False)
[ "submit", "a", "competition!" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L453-L507
32,415
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_submissions
def competition_submissions(self, competition): """ get the list of Submission for a particular competition Parameters ========== competition: the name of the competition """ submissions_result = self.process_response( self.competitions_submission...
python
def competition_submissions(self, competition): """ get the list of Submission for a particular competition Parameters ========== competition: the name of the competition """ submissions_result = self.process_response( self.competitions_submission...
[ "def", "competition_submissions", "(", "self", ",", "competition", ")", ":", "submissions_result", "=", "self", ".", "process_response", "(", "self", ".", "competitions_submissions_list_with_http_info", "(", "id", "=", "competition", ")", ")", "return", "[", "Submis...
get the list of Submission for a particular competition Parameters ========== competition: the name of the competition
[ "get", "the", "list", "of", "Submission", "for", "a", "particular", "competition" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L535-L544
32,416
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_submissions_cli
def competition_submissions_cli(self, competition=None, competition_opt=None, csv_display=False, quiet=False): """ wrapper to competition_submission, will return either...
python
def competition_submissions_cli(self, competition=None, competition_opt=None, csv_display=False, quiet=False): """ wrapper to competition_submission, will return either...
[ "def", "competition_submissions_cli", "(", "self", ",", "competition", "=", "None", ",", "competition_opt", "=", "None", ",", "csv_display", "=", "False", ",", "quiet", "=", "False", ")", ":", "competition", "=", "competition", "or", "competition_opt", "if", "...
wrapper to competition_submission, will return either json or csv to the user. Additional parameters are listed below, see competition_submissions for rest. Parameters ========== competition: the name of the competition. If None, look to config co...
[ "wrapper", "to", "competition_submission", "will", "return", "either", "json", "or", "csv", "to", "the", "user", ".", "Additional", "parameters", "are", "listed", "below", "see", "competition_submissions", "for", "rest", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L546-L582
32,417
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_list_files_cli
def competition_list_files_cli(self, competition, competition_opt=None, csv_display=False, quiet=False): """ List files for a competition, if it exists Paramet...
python
def competition_list_files_cli(self, competition, competition_opt=None, csv_display=False, quiet=False): """ List files for a competition, if it exists Paramet...
[ "def", "competition_list_files_cli", "(", "self", ",", "competition", ",", "competition_opt", "=", "None", ",", "csv_display", "=", "False", ",", "quiet", "=", "False", ")", ":", "competition", "=", "competition", "or", "competition_opt", "if", "competition", "i...
List files for a competition, if it exists Parameters ========== competition: the name of the competition. If None, look to config competition_opt: an alternative competition option provided by cli csv_display: if True, print comma separated values ...
[ "List", "files", "for", "a", "competition", "if", "it", "exists" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L594-L625
32,418
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_download_file
def competition_download_file(self, competition, file_name, path=None, force=False, quiet=False): """ download a competition file to a designa...
python
def competition_download_file(self, competition, file_name, path=None, force=False, quiet=False): """ download a competition file to a designa...
[ "def", "competition_download_file", "(", "self", ",", "competition", ",", "file_name", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "False", ")", ":", "if", "path", "is", "None", ":", "effective_path", "=", "self", ".", "get_d...
download a competition file to a designated location, or use a default location Paramters ========= competition: the name of the competition file_name: the configuration file name path: a path to download the file to force: force the d...
[ "download", "a", "competition", "file", "to", "a", "designated", "location", "or", "use", "a", "default", "location" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L627-L657
32,419
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_download_files
def competition_download_files(self, competition, path=None, force=False, quiet=True): """ a wrapper to competition_download_file to download all competition fi...
python
def competition_download_files(self, competition, path=None, force=False, quiet=True): """ a wrapper to competition_download_file to download all competition fi...
[ "def", "competition_download_files", "(", "self", ",", "competition", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "True", ")", ":", "files", "=", "self", ".", "competition_list_files", "(", "competition", ")", "if", "not", "fil...
a wrapper to competition_download_file to download all competition files. Parameters ========= competition: the name of the competition path: a path to download the file to force: force the download if the file already exists (default False) ...
[ "a", "wrapper", "to", "competition_download_file", "to", "download", "all", "competition", "files", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L659-L679
32,420
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_download_cli
def competition_download_cli(self, competition, competition_opt=None, file_name=None, path=None, force=False, quiet=False)...
python
def competition_download_cli(self, competition, competition_opt=None, file_name=None, path=None, force=False, quiet=False)...
[ "def", "competition_download_cli", "(", "self", ",", "competition", ",", "competition_opt", "=", "None", ",", "file_name", "=", "None", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "False", ")", ":", "competition", "=", "competi...
a wrapper to competition_download_files, but first will parse input from API client. Additional parameters are listed here, see competition_download for remaining. Parameters ========= competition: the name of the competition competition_opt: an a...
[ "a", "wrapper", "to", "competition_download_files", "but", "first", "will", "parse", "input", "from", "API", "client", ".", "Additional", "parameters", "are", "listed", "here", "see", "competition_download", "for", "remaining", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L681-L715
32,421
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_leaderboard_download
def competition_leaderboard_download(self, competition, path, quiet=True): """ Download competition leaderboards Parameters ========= competition: the name of the competition path: a path to download the file to quiet: suppress verbose output (default...
python
def competition_leaderboard_download(self, competition, path, quiet=True): """ Download competition leaderboards Parameters ========= competition: the name of the competition path: a path to download the file to quiet: suppress verbose output (default...
[ "def", "competition_leaderboard_download", "(", "self", ",", "competition", ",", "path", ",", "quiet", "=", "True", ")", ":", "response", "=", "self", ".", "process_response", "(", "self", ".", "competition_download_leaderboard_with_http_info", "(", "competition", "...
Download competition leaderboards Parameters ========= competition: the name of the competition path: a path to download the file to quiet: suppress verbose output (default is True)
[ "Download", "competition", "leaderboards" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L717-L738
32,422
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_leaderboard_view
def competition_leaderboard_view(self, competition): """ view a leaderboard based on a competition name Parameters ========== competition: the competition name to view leadboard for """ result = self.process_response( self.competition_view_leaderb...
python
def competition_leaderboard_view(self, competition): """ view a leaderboard based on a competition name Parameters ========== competition: the competition name to view leadboard for """ result = self.process_response( self.competition_view_leaderb...
[ "def", "competition_leaderboard_view", "(", "self", ",", "competition", ")", ":", "result", "=", "self", ".", "process_response", "(", "self", ".", "competition_view_leaderboard_with_http_info", "(", "competition", ")", ")", "return", "[", "LeaderboardEntry", "(", "...
view a leaderboard based on a competition name Parameters ========== competition: the competition name to view leadboard for
[ "view", "a", "leaderboard", "based", "on", "a", "competition", "name" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L740-L749
32,423
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_leaderboard_cli
def competition_leaderboard_cli(self, competition, competition_opt=None, path=None, view=False, download=False, ...
python
def competition_leaderboard_cli(self, competition, competition_opt=None, path=None, view=False, download=False, ...
[ "def", "competition_leaderboard_cli", "(", "self", ",", "competition", ",", "competition_opt", "=", "None", ",", "path", "=", "None", ",", "view", "=", "False", ",", "download", "=", "False", ",", "csv_display", "=", "False", ",", "quiet", "=", "False", ")...
a wrapper for competition_leaderbord_view that will print the results as a table or comma separated values Parameters ========== competition: the competition name to view leadboard for competition_opt: an alternative competition option provided by cli ...
[ "a", "wrapper", "for", "competition_leaderbord_view", "that", "will", "print", "the", "results", "as", "a", "table", "or", "comma", "separated", "values" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L751-L796
32,424
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_list
def dataset_list(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, mine=False, ...
python
def dataset_list(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, mine=False, ...
[ "def", "dataset_list", "(", "self", ",", "sort_by", "=", "None", ",", "size", "=", "None", ",", "file_type", "=", "None", ",", "license_name", "=", "None", ",", "tag_ids", "=", "None", ",", "search", "=", "None", ",", "user", "=", "None", ",", "mine"...
return a list of datasets! Parameters ========== sort_by: how to sort the result, see valid_sort_bys for options size: the size of the dataset, see valid_sizes for string options file_type: the format, see valid_file_types for string options licen...
[ "return", "a", "list", "of", "datasets!" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L798-L864
32,425
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_list_cli
def dataset_list_cli(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, ...
python
def dataset_list_cli(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, ...
[ "def", "dataset_list_cli", "(", "self", ",", "sort_by", "=", "None", ",", "size", "=", "None", ",", "file_type", "=", "None", ",", "license_name", "=", "None", ",", "tag_ids", "=", "None", ",", "search", "=", "None", ",", "user", "=", "None", ",", "m...
a wrapper to datasets_list for the client. Additional parameters are described here, see dataset_list for others. Parameters ========== sort_by: how to sort the result, see valid_sort_bys for options size: the size of the dataset, see valid_sizes for string o...
[ "a", "wrapper", "to", "datasets_list", "for", "the", "client", ".", "Additional", "parameters", "are", "described", "here", "see", "dataset_list", "for", "others", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L866-L902
32,426
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_view
def dataset_view(self, dataset): """ view metadata for a dataset. Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] """ if '/' in dataset: self.validate_dataset_stri...
python
def dataset_view(self, dataset): """ view metadata for a dataset. Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] """ if '/' in dataset: self.validate_dataset_stri...
[ "def", "dataset_view", "(", "self", ",", "dataset", ")", ":", "if", "'/'", "in", "dataset", ":", "self", ".", "validate_dataset_string", "(", "dataset", ")", "dataset_urls", "=", "dataset", ".", "split", "(", "'/'", ")", "owner_slug", "=", "dataset_urls", ...
view metadata for a dataset. Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name]
[ "view", "metadata", "for", "a", "dataset", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L904-L923
32,427
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_download_file
def dataset_download_file(self, dataset, file_name, path=None, force=False, quiet=True): """ download a single file for a dataset Parameters ...
python
def dataset_download_file(self, dataset, file_name, path=None, force=False, quiet=True): """ download a single file for a dataset Parameters ...
[ "def", "dataset_download_file", "(", "self", ",", "dataset", ",", "file_name", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "True", ")", ":", "if", "'/'", "in", "dataset", ":", "self", ".", "validate_dataset_string", "(", "dat...
download a single file for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] file_name: the dataset configuration file path: if defined, download to this location ...
[ "download", "a", "single", "file", "for", "a", "dataset" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1050-L1094
32,428
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_download_files
def dataset_download_files(self, dataset, path=None, force=False, quiet=True, unzip=False): """ download all files for a dataset Parameters ...
python
def dataset_download_files(self, dataset, path=None, force=False, quiet=True, unzip=False): """ download all files for a dataset Parameters ...
[ "def", "dataset_download_files", "(", "self", ",", "dataset", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "True", ",", "unzip", "=", "False", ")", ":", "if", "dataset", "is", "None", ":", "raise", "ValueError", "(", "'A dat...
download all files for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] path: the path to download the dataset to force: force the download if the file already exists...
[ "download", "all", "files", "for", "a", "dataset" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1096-L1157
32,429
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_upload_file
def dataset_upload_file(self, path, quiet): """ upload a dataset file Parameters ========== path: the complete path to upload quiet: suppress verbose output (default is False) """ file_name = os.path.basename(path) content_length = os.path...
python
def dataset_upload_file(self, path, quiet): """ upload a dataset file Parameters ========== path: the complete path to upload quiet: suppress verbose output (default is False) """ file_name = os.path.basename(path) content_length = os.path...
[ "def", "dataset_upload_file", "(", "self", ",", "path", ",", "quiet", ")", ":", "file_name", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "content_length", "=", "os", ".", "path", ".", "getsize", "(", "path", ")", "last_modified_date_utc", ...
upload a dataset file Parameters ========== path: the complete path to upload quiet: suppress verbose output (default is False)
[ "upload", "a", "dataset", "file" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1191-L1211
32,430
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_create_version
def dataset_create_version(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, dir_mode='skip'):...
python
def dataset_create_version(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, dir_mode='skip'):...
[ "def", "dataset_create_version", "(", "self", ",", "folder", ",", "version_notes", ",", "quiet", "=", "False", ",", "convert_to_csv", "=", "True", ",", "delete_old_versions", "=", "False", ",", "dir_mode", "=", "'skip'", ")", ":", "if", "not", "os", ".", "...
create a version of a dataset Parameters ========== folder: the folder with the dataset configuration / data files version_notes: notes to add for the version quiet: suppress verbose output (default is False) convert_to_csv: on upload, if data sho...
[ "create", "a", "version", "of", "a", "dataset" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1213-L1285
32,431
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.download_file
def download_file(self, response, outfile, quiet=True, chunk_size=1048576): """ download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress ve...
python
def download_file(self, response, outfile, quiet=True, chunk_size=1048576): """ download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress ve...
[ "def", "download_file", "(", "self", ",", "response", ",", "outfile", ",", "quiet", "=", "True", ",", "chunk_size", "=", "1048576", ")", ":", "outpath", "=", "os", ".", "path", ".", "dirname", "(", "outfile", ")", "if", "not", "os", ".", "path", ".",...
download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress verbose output (default is True) chunk_size: the size of the chunk to stream
[ "download", "a", "file", "to", "an", "output", "file", "based", "on", "a", "chunk", "size" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1466-L1500
32,432
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_list
def kernels_list(self, page=1, page_size=20, dataset=None, competition=None, parent_kernel=None, search=None, mine=False, user=None, ...
python
def kernels_list(self, page=1, page_size=20, dataset=None, competition=None, parent_kernel=None, search=None, mine=False, user=None, ...
[ "def", "kernels_list", "(", "self", ",", "page", "=", "1", ",", "page_size", "=", "20", ",", "dataset", "=", "None", ",", "competition", "=", "None", ",", "parent_kernel", "=", "None", ",", "search", "=", "None", ",", "mine", "=", "False", ",", "user...
list kernels based on a set of search criteria Parameters ========== page: the page of results to return (default is 1) page_size: results per page (default is 20) dataset: if defined, filter to this dataset (default None) competition: if defined,...
[ "list", "kernels", "based", "on", "a", "set", "of", "search", "criteria" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1502-L1590
32,433
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_push_cli
def kernels_push_cli(self, folder): """ client wrapper for kernels_push, with same arguments. """ folder = folder or os.getcwd() result = self.kernels_push(folder) if result is None: print('Kernel push error: see previous output') elif not result.error: ...
python
def kernels_push_cli(self, folder): """ client wrapper for kernels_push, with same arguments. """ folder = folder or os.getcwd() result = self.kernels_push(folder) if result is None: print('Kernel push error: see previous output') elif not result.error: ...
[ "def", "kernels_push_cli", "(", "self", ",", "folder", ")", ":", "folder", "=", "folder", "or", "os", ".", "getcwd", "(", ")", "result", "=", "self", ".", "kernels_push", "(", "folder", ")", "if", "result", "is", "None", ":", "print", "(", "'Kernel pus...
client wrapper for kernels_push, with same arguments.
[ "client", "wrapper", "for", "kernels_push", "with", "same", "arguments", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1790-L1827
32,434
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_pull_cli
def kernels_pull_cli(self, kernel, kernel_opt=None, path=None, metadata=False): """ client wrapper for kernels_pull """ kernel = kernel or kernel_opt effective_path = self.kernels_pull( ...
python
def kernels_pull_cli(self, kernel, kernel_opt=None, path=None, metadata=False): """ client wrapper for kernels_pull """ kernel = kernel or kernel_opt effective_path = self.kernels_pull( ...
[ "def", "kernels_pull_cli", "(", "self", ",", "kernel", ",", "kernel_opt", "=", "None", ",", "path", "=", "None", ",", "metadata", "=", "False", ")", ":", "kernel", "=", "kernel", "or", "kernel_opt", "effective_path", "=", "self", ".", "kernels_pull", "(", ...
client wrapper for kernels_pull
[ "client", "wrapper", "for", "kernels_pull" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1965-L1978
32,435
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.print_table
def print_table(self, items, fields): """ print a table of items, for a set of fields defined Parameters ========== items: a list of items to print fields: a list of fields to select from items """ formats = [] borders = [] for f i...
python
def print_table(self, items, fields): """ print a table of items, for a set of fields defined Parameters ========== items: a list of items to print fields: a list of fields to select from items """ formats = [] borders = [] for f i...
[ "def", "print_table", "(", "self", ",", "items", ",", "fields", ")", ":", "formats", "=", "[", "]", "borders", "=", "[", "]", "for", "f", "in", "fields", ":", "length", "=", "max", "(", "len", "(", "f", ")", ",", "max", "(", "[", "len", "(", ...
print a table of items, for a set of fields defined Parameters ========== items: a list of items to print fields: a list of fields to select from items
[ "print", "a", "table", "of", "items", "for", "a", "set", "of", "fields", "defined" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2113-L2139
32,436
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.print_csv
def print_csv(self, items, fields): """ print a set of fields in a set of items using a csv.writer Parameters ========== items: a list of items to print fields: a list of fields to select from items """ writer = csv.writer(sys.stdout) writ...
python
def print_csv(self, items, fields): """ print a set of fields in a set of items using a csv.writer Parameters ========== items: a list of items to print fields: a list of fields to select from items """ writer = csv.writer(sys.stdout) writ...
[ "def", "print_csv", "(", "self", ",", "items", ",", "fields", ")", ":", "writer", "=", "csv", ".", "writer", "(", "sys", ".", "stdout", ")", "writer", ".", "writerow", "(", "fields", ")", "for", "i", "in", "items", ":", "i_fields", "=", "[", "self"...
print a set of fields in a set of items using a csv.writer Parameters ========== items: a list of items to print fields: a list of fields to select from items
[ "print", "a", "set", "of", "fields", "in", "a", "set", "of", "items", "using", "a", "csv", ".", "writer" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2141-L2153
32,437
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.validate_resources
def validate_resources(self, folder, resources): """ validate resources is a wrapper to validate the existence of files and that there are no duplicates for a folder and set of resources. Parameters ========== folder: the folder to validate resources:...
python
def validate_resources(self, folder, resources): """ validate resources is a wrapper to validate the existence of files and that there are no duplicates for a folder and set of resources. Parameters ========== folder: the folder to validate resources:...
[ "def", "validate_resources", "(", "self", ",", "folder", ",", "resources", ")", ":", "self", ".", "validate_files_exist", "(", "folder", ",", "resources", ")", "self", ".", "validate_no_duplicate_paths", "(", "resources", ")" ]
validate resources is a wrapper to validate the existence of files and that there are no duplicates for a folder and set of resources. Parameters ========== folder: the folder to validate resources: one or more resources to validate within the folder
[ "validate", "resources", "is", "a", "wrapper", "to", "validate", "the", "existence", "of", "files", "and", "that", "there", "are", "no", "duplicates", "for", "a", "folder", "and", "set", "of", "resources", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2425-L2435
32,438
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.validate_files_exist
def validate_files_exist(self, folder, resources): """ ensure that one or more resource files exist in a folder Parameters ========== folder: the folder to validate resources: one or more resources to validate within the folder """ for item in res...
python
def validate_files_exist(self, folder, resources): """ ensure that one or more resource files exist in a folder Parameters ========== folder: the folder to validate resources: one or more resources to validate within the folder """ for item in res...
[ "def", "validate_files_exist", "(", "self", ",", "folder", ",", "resources", ")", ":", "for", "item", "in", "resources", ":", "file_name", "=", "item", ".", "get", "(", "'path'", ")", "full_path", "=", "os", ".", "path", ".", "join", "(", "folder", ","...
ensure that one or more resource files exist in a folder Parameters ========== folder: the folder to validate resources: one or more resources to validate within the folder
[ "ensure", "that", "one", "or", "more", "resource", "files", "exist", "in", "a", "folder" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2437-L2449
32,439
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.validate_no_duplicate_paths
def validate_no_duplicate_paths(self, resources): """ ensure that the user has not provided duplicate paths in a list of resources. Parameters ========== resources: one or more resources to validate not duplicated """ paths = set() for ite...
python
def validate_no_duplicate_paths(self, resources): """ ensure that the user has not provided duplicate paths in a list of resources. Parameters ========== resources: one or more resources to validate not duplicated """ paths = set() for ite...
[ "def", "validate_no_duplicate_paths", "(", "self", ",", "resources", ")", ":", "paths", "=", "set", "(", ")", "for", "item", "in", "resources", ":", "file_name", "=", "item", ".", "get", "(", "'path'", ")", "if", "file_name", "in", "paths", ":", "raise",...
ensure that the user has not provided duplicate paths in a list of resources. Parameters ========== resources: one or more resources to validate not duplicated
[ "ensure", "that", "the", "user", "has", "not", "provided", "duplicate", "paths", "in", "a", "list", "of", "resources", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2451-L2466
32,440
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.convert_to_dataset_file_metadata
def convert_to_dataset_file_metadata(self, file_data, path): """ convert a set of file_data to a metadata file at path Parameters ========== file_data: a dictionary of file data to write to file path: the path to write the metadata to """ as_metad...
python
def convert_to_dataset_file_metadata(self, file_data, path): """ convert a set of file_data to a metadata file at path Parameters ========== file_data: a dictionary of file data to write to file path: the path to write the metadata to """ as_metad...
[ "def", "convert_to_dataset_file_metadata", "(", "self", ",", "file_data", ",", "path", ")", ":", "as_metadata", "=", "{", "'path'", ":", "os", ".", "path", ".", "join", "(", "path", ",", "file_data", "[", "'name'", "]", ")", ",", "'description'", ":", "f...
convert a set of file_data to a metadata file at path Parameters ========== file_data: a dictionary of file data to write to file path: the path to write the metadata to
[ "convert", "a", "set", "of", "file_data", "to", "a", "metadata", "file", "at", "path" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2468-L2493
32,441
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
TqdmBufferedReader.read
def read(self, *args, **kwargs): """ read the buffer, passing named and non named arguments to the io.BufferedReader function. """ buf = io.BufferedReader.read(self, *args, **kwargs) self.increment(len(buf)) return buf
python
def read(self, *args, **kwargs): """ read the buffer, passing named and non named arguments to the io.BufferedReader function. """ buf = io.BufferedReader.read(self, *args, **kwargs) self.increment(len(buf)) return buf
[ "def", "read", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "buf", "=", "io", ".", "BufferedReader", ".", "read", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "increment", "(", "len", "(", "buf"...
read the buffer, passing named and non named arguments to the io.BufferedReader function.
[ "read", "the", "buffer", "passing", "named", "and", "non", "named", "arguments", "to", "the", "io", ".", "BufferedReader", "function", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2507-L2513
32,442
Kaggle/kaggle-api
kaggle/api_client.py
ApiClient.parameters_to_tuples
def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collection...
python
def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collection...
[ "def", "parameters_to_tuples", "(", "self", ",", "params", ",", "collection_formats", ")", ":", "new_params", "=", "[", "]", "if", "collection_formats", "is", "None", ":", "collection_formats", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iterit...
Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted
[ "Get", "parameters", "as", "list", "of", "tuples", "formatting", "collections", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api_client.py#L407-L435
32,443
Kaggle/kaggle-api
kaggle/api_client.py
ApiClient.__deserialize_file
def __deserialize_file(self, response): """Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path. """ fd, path = t...
python
def __deserialize_file(self, response): """Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path. """ fd, path = t...
[ "def", "__deserialize_file", "(", "self", ",", "response", ")", ":", "fd", ",", "path", "=", "tempfile", ".", "mkstemp", "(", "dir", "=", "self", ".", "configuration", ".", "temp_folder_path", ")", "os", ".", "close", "(", "fd", ")", "os", ".", "remove...
Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path.
[ "Deserializes", "body", "to", "file" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api_client.py#L521-L543
32,444
Kaggle/kaggle-api
kaggle/models/dataset_new_request.py
DatasetNewRequest.license_name
def license_name(self, license_name): """Sets the license_name of this DatasetNewRequest. The license that should be associated with the dataset # noqa: E501 :param license_name: The license_name of this DatasetNewRequest. # noqa: E501 :type: str """ allowed_values = ...
python
def license_name(self, license_name): """Sets the license_name of this DatasetNewRequest. The license that should be associated with the dataset # noqa: E501 :param license_name: The license_name of this DatasetNewRequest. # noqa: E501 :type: str """ allowed_values = ...
[ "def", "license_name", "(", "self", ",", "license_name", ")", ":", "allowed_values", "=", "[", "\"CC0-1.0\"", ",", "\"CC-BY-SA-4.0\"", ",", "\"GPL-2.0\"", ",", "\"ODbL-1.0\"", ",", "\"CC-BY-NC-SA-4.0\"", ",", "\"unknown\"", ",", "\"DbCL-1.0\"", ",", "\"CC-BY-SA-3.0\...
Sets the license_name of this DatasetNewRequest. The license that should be associated with the dataset # noqa: E501 :param license_name: The license_name of this DatasetNewRequest. # noqa: E501 :type: str
[ "Sets", "the", "license_name", "of", "this", "DatasetNewRequest", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/models/dataset_new_request.py#L194-L209
32,445
dmlc/gluon-nlp
scripts/sentiment_analysis/sentiment_analysis_cnn.py
train
def train(net, train_data, test_data): """Train textCNN model for sentiment analysis.""" start_pipeline_time = time.time() net, trainer = text_cnn.init(net, vocab, args.model_mode, context, args.lr) random.shuffle(train_data) sp = int(len(train_data)*0.9) train_dataloader = DataLoader(dataset=tr...
python
def train(net, train_data, test_data): """Train textCNN model for sentiment analysis.""" start_pipeline_time = time.time() net, trainer = text_cnn.init(net, vocab, args.model_mode, context, args.lr) random.shuffle(train_data) sp = int(len(train_data)*0.9) train_dataloader = DataLoader(dataset=tr...
[ "def", "train", "(", "net", ",", "train_data", ",", "test_data", ")", ":", "start_pipeline_time", "=", "time", ".", "time", "(", ")", "net", ",", "trainer", "=", "text_cnn", ".", "init", "(", "net", ",", "vocab", ",", "args", ".", "model_mode", ",", ...
Train textCNN model for sentiment analysis.
[ "Train", "textCNN", "model", "for", "sentiment", "analysis", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/sentiment_analysis_cnn.py#L114-L184
32,446
dmlc/gluon-nlp
scripts/bert/embedding.py
BertEmbedding.embedding
def embedding(self, sentences, oov_way='avg'): """ Get tokens, tokens embedding Parameters ---------- sentences : List[str] sentences for encoding. oov_way : str, default avg. use **avg**, **sum** or **last** to get token embedding for those out o...
python
def embedding(self, sentences, oov_way='avg'): """ Get tokens, tokens embedding Parameters ---------- sentences : List[str] sentences for encoding. oov_way : str, default avg. use **avg**, **sum** or **last** to get token embedding for those out o...
[ "def", "embedding", "(", "self", ",", "sentences", ",", "oov_way", "=", "'avg'", ")", ":", "data_iter", "=", "self", ".", "data_loader", "(", "sentences", "=", "sentences", ")", "batches", "=", "[", "]", "for", "token_ids", ",", "valid_length", ",", "tok...
Get tokens, tokens embedding Parameters ---------- sentences : List[str] sentences for encoding. oov_way : str, default avg. use **avg**, **sum** or **last** to get token embedding for those out of vocabulary words Returns ------- ...
[ "Get", "tokens", "tokens", "embedding" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/embedding.py#L111-L139
32,447
dmlc/gluon-nlp
scripts/bert/embedding.py
BertEmbedding.data_loader
def data_loader(self, sentences, shuffle=False): """Load, tokenize and prepare the input sentences.""" dataset = BertEmbeddingDataset(sentences, self.transform) return DataLoader(dataset=dataset, batch_size=self.batch_size, shuffle=shuffle)
python
def data_loader(self, sentences, shuffle=False): """Load, tokenize and prepare the input sentences.""" dataset = BertEmbeddingDataset(sentences, self.transform) return DataLoader(dataset=dataset, batch_size=self.batch_size, shuffle=shuffle)
[ "def", "data_loader", "(", "self", ",", "sentences", ",", "shuffle", "=", "False", ")", ":", "dataset", "=", "BertEmbeddingDataset", "(", "sentences", ",", "self", ".", "transform", ")", "return", "DataLoader", "(", "dataset", "=", "dataset", ",", "batch_siz...
Load, tokenize and prepare the input sentences.
[ "Load", "tokenize", "and", "prepare", "the", "input", "sentences", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/embedding.py#L141-L144
32,448
dmlc/gluon-nlp
src/gluonnlp/model/bert.py
get_bert_model
def get_bert_model(model_name=None, dataset_name=None, vocab=None, pretrained=True, ctx=mx.cpu(), use_pooler=True, use_decoder=True, use_classifier=True, output_attention=False, output_all_encodings=False, root=os.path.join(get_home_dir(), 'mod...
python
def get_bert_model(model_name=None, dataset_name=None, vocab=None, pretrained=True, ctx=mx.cpu(), use_pooler=True, use_decoder=True, use_classifier=True, output_attention=False, output_all_encodings=False, root=os.path.join(get_home_dir(), 'mod...
[ "def", "get_bert_model", "(", "model_name", "=", "None", ",", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "True", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "use_pooler", "=", "True", ",", "use_decoder", "=", ...
Any BERT pretrained model. Parameters ---------- model_name : str or None, default None Options include 'bert_24_1024_16' and 'bert_12_768_12'. dataset_name : str or None, default None Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased' for both bert_24_10...
[ "Any", "BERT", "pretrained", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L630-L709
32,449
dmlc/gluon-nlp
src/gluonnlp/model/bert.py
BERTLayerNorm.hybrid_forward
def hybrid_forward(self, F, data, gamma, beta): """forward computation.""" # TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at: # https://github.com/apache/incubator-mxnet/issues/14073 if self._dtype: data = data.astype('float32') g...
python
def hybrid_forward(self, F, data, gamma, beta): """forward computation.""" # TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at: # https://github.com/apache/incubator-mxnet/issues/14073 if self._dtype: data = data.astype('float32') g...
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "data", ",", "gamma", ",", "beta", ")", ":", "# TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at:", "# https://github.com/apache/incubator-mxnet/issues/14073", "if", "self", ".", "_dtype", "...
forward computation.
[ "forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L59-L70
32,450
dmlc/gluon-nlp
src/gluonnlp/model/bert.py
BERTModel._get_classifier
def _get_classifier(self, prefix): """ Construct a decoder for the next sentence prediction task """ with self.name_scope(): classifier = nn.Dense(2, prefix=prefix) return classifier
python
def _get_classifier(self, prefix): """ Construct a decoder for the next sentence prediction task """ with self.name_scope(): classifier = nn.Dense(2, prefix=prefix) return classifier
[ "def", "_get_classifier", "(", "self", ",", "prefix", ")", ":", "with", "self", ".", "name_scope", "(", ")", ":", "classifier", "=", "nn", ".", "Dense", "(", "2", ",", "prefix", "=", "prefix", ")", "return", "classifier" ]
Construct a decoder for the next sentence prediction task
[ "Construct", "a", "decoder", "for", "the", "next", "sentence", "prediction", "task" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L364-L368
32,451
dmlc/gluon-nlp
src/gluonnlp/model/bert.py
BERTModel._get_decoder
def _get_decoder(self, units, vocab_size, embed, prefix): """ Construct a decoder for the masked language model task """ with self.name_scope(): decoder = nn.HybridSequential(prefix=prefix) decoder.add(nn.Dense(units, flatten=False)) decoder.add(GELU()) de...
python
def _get_decoder(self, units, vocab_size, embed, prefix): """ Construct a decoder for the masked language model task """ with self.name_scope(): decoder = nn.HybridSequential(prefix=prefix) decoder.add(nn.Dense(units, flatten=False)) decoder.add(GELU()) de...
[ "def", "_get_decoder", "(", "self", ",", "units", ",", "vocab_size", ",", "embed", ",", "prefix", ")", ":", "with", "self", ".", "name_scope", "(", ")", ":", "decoder", "=", "nn", ".", "HybridSequential", "(", "prefix", "=", "prefix", ")", "decoder", "...
Construct a decoder for the masked language model task
[ "Construct", "a", "decoder", "for", "the", "masked", "language", "model", "task" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L370-L380
32,452
dmlc/gluon-nlp
src/gluonnlp/model/bert.py
BERTModel._get_embed
def _get_embed(self, embed, vocab_size, embed_size, initializer, dropout, prefix): """ Construct an embedding block. """ if embed is None: assert embed_size is not None, '"embed_size" cannot be None if "word_embed" or ' \ 'token_type_embed is not gi...
python
def _get_embed(self, embed, vocab_size, embed_size, initializer, dropout, prefix): """ Construct an embedding block. """ if embed is None: assert embed_size is not None, '"embed_size" cannot be None if "word_embed" or ' \ 'token_type_embed is not gi...
[ "def", "_get_embed", "(", "self", ",", "embed", ",", "vocab_size", ",", "embed_size", ",", "initializer", ",", "dropout", ",", "prefix", ")", ":", "if", "embed", "is", "None", ":", "assert", "embed_size", "is", "not", "None", ",", "'\"embed_size\" cannot be ...
Construct an embedding block.
[ "Construct", "an", "embedding", "block", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L382-L395
32,453
dmlc/gluon-nlp
src/gluonnlp/model/bert.py
BERTModel._get_pooler
def _get_pooler(self, units, prefix): """ Construct pooler. The pooler slices and projects the hidden output of first token in the sequence for segment level classification. """ with self.name_scope(): pooler = nn.Dense(units=units, flatten=False, activation='tanh',...
python
def _get_pooler(self, units, prefix): """ Construct pooler. The pooler slices and projects the hidden output of first token in the sequence for segment level classification. """ with self.name_scope(): pooler = nn.Dense(units=units, flatten=False, activation='tanh',...
[ "def", "_get_pooler", "(", "self", ",", "units", ",", "prefix", ")", ":", "with", "self", ".", "name_scope", "(", ")", ":", "pooler", "=", "nn", ".", "Dense", "(", "units", "=", "units", ",", "flatten", "=", "False", ",", "activation", "=", "'tanh'",...
Construct pooler. The pooler slices and projects the hidden output of first token in the sequence for segment level classification.
[ "Construct", "pooler", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L397-L407
32,454
dmlc/gluon-nlp
src/gluonnlp/model/bert.py
BERTModel._encode_sequence
def _encode_sequence(self, inputs, token_types, valid_length=None): """Generate the representation given the input sequences. This is used for pre-training or fine-tuning a BERT model. """ # embedding word_embedding = self.word_embed(inputs) type_embedding = self.token_t...
python
def _encode_sequence(self, inputs, token_types, valid_length=None): """Generate the representation given the input sequences. This is used for pre-training or fine-tuning a BERT model. """ # embedding word_embedding = self.word_embed(inputs) type_embedding = self.token_t...
[ "def", "_encode_sequence", "(", "self", ",", "inputs", ",", "token_types", ",", "valid_length", "=", "None", ")", ":", "# embedding", "word_embedding", "=", "self", ".", "word_embed", "(", "inputs", ")", "type_embedding", "=", "self", ".", "token_type_embed", ...
Generate the representation given the input sequences. This is used for pre-training or fine-tuning a BERT model.
[ "Generate", "the", "representation", "given", "the", "input", "sequences", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L440-L451
32,455
dmlc/gluon-nlp
src/gluonnlp/model/bert.py
BERTModel._decode
def _decode(self, sequence, masked_positions): """Generate unnormalized prediction for the masked language model task. This is only used for pre-training the BERT model. Inputs: - **sequence**: input tensor of sequence encodings. Shape (batch_size, seq_length, units)....
python
def _decode(self, sequence, masked_positions): """Generate unnormalized prediction for the masked language model task. This is only used for pre-training the BERT model. Inputs: - **sequence**: input tensor of sequence encodings. Shape (batch_size, seq_length, units)....
[ "def", "_decode", "(", "self", ",", "sequence", ",", "masked_positions", ")", ":", "batch_size", "=", "sequence", ".", "shape", "[", "0", "]", "num_masked_positions", "=", "masked_positions", ".", "shape", "[", "1", "]", "ctx", "=", "masked_positions", ".", ...
Generate unnormalized prediction for the masked language model task. This is only used for pre-training the BERT model. Inputs: - **sequence**: input tensor of sequence encodings. Shape (batch_size, seq_length, units). - **masked_positions**: input tensor of posit...
[ "Generate", "unnormalized", "prediction", "for", "the", "masked", "language", "model", "task", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L461-L490
32,456
dmlc/gluon-nlp
scripts/machine_translation/bleu.py
_ngrams
def _ngrams(segment, n): """Extracts n-grams from an input segment. Parameters ---------- segment: list Text segment from which n-grams will be extracted. n: int Order of n-gram. Returns ------- ngram_counts: Counter Contain all the nth n-grams in segment with a...
python
def _ngrams(segment, n): """Extracts n-grams from an input segment. Parameters ---------- segment: list Text segment from which n-grams will be extracted. n: int Order of n-gram. Returns ------- ngram_counts: Counter Contain all the nth n-grams in segment with a...
[ "def", "_ngrams", "(", "segment", ",", "n", ")", ":", "ngram_counts", "=", "Counter", "(", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "segment", ")", "-", "n", "+", "1", ")", ":", "ngram", "=", "tuple", "(", "segment", "[", "i",...
Extracts n-grams from an input segment. Parameters ---------- segment: list Text segment from which n-grams will be extracted. n: int Order of n-gram. Returns ------- ngram_counts: Counter Contain all the nth n-grams in segment with a count of how many times each n-...
[ "Extracts", "n", "-", "grams", "from", "an", "input", "segment", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L32-L51
32,457
dmlc/gluon-nlp
scripts/machine_translation/bleu.py
_bpe_to_words
def _bpe_to_words(sentence, delimiter='@@'): """Convert a sequence of bpe words into sentence.""" words = [] word = '' delimiter_len = len(delimiter) for subwords in sentence: if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter: word += subwords[:-delimit...
python
def _bpe_to_words(sentence, delimiter='@@'): """Convert a sequence of bpe words into sentence.""" words = [] word = '' delimiter_len = len(delimiter) for subwords in sentence: if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter: word += subwords[:-delimit...
[ "def", "_bpe_to_words", "(", "sentence", ",", "delimiter", "=", "'@@'", ")", ":", "words", "=", "[", "]", "word", "=", "''", "delimiter_len", "=", "len", "(", "delimiter", ")", "for", "subwords", "in", "sentence", ":", "if", "len", "(", "subwords", ")"...
Convert a sequence of bpe words into sentence.
[ "Convert", "a", "sequence", "of", "bpe", "words", "into", "sentence", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L61-L73
32,458
dmlc/gluon-nlp
scripts/machine_translation/bleu.py
compute_bleu
def compute_bleu(reference_corpus_list, translation_corpus, tokenized=True, tokenizer='13a', max_n=4, smooth=False, lower_case=False, bpe=False, split_compound_word=False): r"""Compute bleu score of translation against references. Parameters ---------- reference_corpus...
python
def compute_bleu(reference_corpus_list, translation_corpus, tokenized=True, tokenizer='13a', max_n=4, smooth=False, lower_case=False, bpe=False, split_compound_word=False): r"""Compute bleu score of translation against references. Parameters ---------- reference_corpus...
[ "def", "compute_bleu", "(", "reference_corpus_list", ",", "translation_corpus", ",", "tokenized", "=", "True", ",", "tokenizer", "=", "'13a'", ",", "max_n", "=", "4", ",", "smooth", "=", "False", ",", "lower_case", "=", "False", ",", "bpe", "=", "False", "...
r"""Compute bleu score of translation against references. Parameters ---------- reference_corpus_list: list of list(list(str)) or list of list(str) list of list(list(str)): tokenized references list of list(str): plain text List of references for each translation. translation_co...
[ "r", "Compute", "bleu", "score", "of", "translation", "against", "references", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L158-L249
32,459
dmlc/gluon-nlp
scripts/machine_translation/bleu.py
_compute_precision
def _compute_precision(references, translation, n): """Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int Number ...
python
def _compute_precision(references, translation, n): """Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int Number ...
[ "def", "_compute_precision", "(", "references", ",", "translation", ",", "n", ")", ":", "matches", "=", "0", "candidates", "=", "0", "ref_ngram_counts", "=", "Counter", "(", ")", "for", "reference", "in", "references", ":", "ref_ngram_counts", "|=", "_ngrams",...
Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int Number of matched nth order n-grams candidates Number ...
[ "Compute", "ngram", "precision", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L252-L284
32,460
dmlc/gluon-nlp
scripts/machine_translation/bleu.py
_brevity_penalty
def _brevity_penalty(ref_length, trans_length): """Calculate brevity penalty. Parameters ---------- ref_length: int Sum of all closest references'lengths for every translations in a corpus trans_length: int Sum of all translations's lengths in a corpus. Returns ------- ...
python
def _brevity_penalty(ref_length, trans_length): """Calculate brevity penalty. Parameters ---------- ref_length: int Sum of all closest references'lengths for every translations in a corpus trans_length: int Sum of all translations's lengths in a corpus. Returns ------- ...
[ "def", "_brevity_penalty", "(", "ref_length", ",", "trans_length", ")", ":", "if", "trans_length", ">", "ref_length", ":", "return", "1", "# If translation is empty, brevity penalty = 0 should result in BLEU = 0.0", "elif", "trans_length", "==", "0", ":", "return", "0", ...
Calculate brevity penalty. Parameters ---------- ref_length: int Sum of all closest references'lengths for every translations in a corpus trans_length: int Sum of all translations's lengths in a corpus. Returns ------- bleu's brevity penalty: float
[ "Calculate", "brevity", "penalty", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L287-L307
32,461
dmlc/gluon-nlp
scripts/machine_translation/bleu.py
_closest_ref_length
def _closest_ref_length(references, trans_length): """Find the reference that has the closest length to the translation. Parameters ---------- references: list(list(str)) A list of references. trans_length: int Length of the translation. Returns ------- closest_ref_len:...
python
def _closest_ref_length(references, trans_length): """Find the reference that has the closest length to the translation. Parameters ---------- references: list(list(str)) A list of references. trans_length: int Length of the translation. Returns ------- closest_ref_len:...
[ "def", "_closest_ref_length", "(", "references", ",", "trans_length", ")", ":", "ref_lengths", "=", "(", "len", "(", "reference", ")", "for", "reference", "in", "references", ")", "closest_ref_len", "=", "min", "(", "ref_lengths", ",", "key", "=", "lambda", ...
Find the reference that has the closest length to the translation. Parameters ---------- references: list(list(str)) A list of references. trans_length: int Length of the translation. Returns ------- closest_ref_len: int Length of the reference that is closest to th...
[ "Find", "the", "reference", "that", "has", "the", "closest", "length", "to", "the", "translation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L310-L329
32,462
dmlc/gluon-nlp
scripts/machine_translation/bleu.py
_smoothing
def _smoothing(precision_fractions, c=1): """Compute the smoothed precision for all the orders. Parameters ---------- precision_fractions: list(tuple) Contain a list of (precision_numerator, precision_denominator) pairs c: int, default 1 Smoothing constant to use Returns --...
python
def _smoothing(precision_fractions, c=1): """Compute the smoothed precision for all the orders. Parameters ---------- precision_fractions: list(tuple) Contain a list of (precision_numerator, precision_denominator) pairs c: int, default 1 Smoothing constant to use Returns --...
[ "def", "_smoothing", "(", "precision_fractions", ",", "c", "=", "1", ")", ":", "ratios", "=", "[", "0", "]", "*", "len", "(", "precision_fractions", ")", "for", "i", ",", "precision_fraction", "in", "enumerate", "(", "precision_fractions", ")", ":", "if", ...
Compute the smoothed precision for all the orders. Parameters ---------- precision_fractions: list(tuple) Contain a list of (precision_numerator, precision_denominator) pairs c: int, default 1 Smoothing constant to use Returns ------- ratios: list of floats Contain ...
[ "Compute", "the", "smoothed", "precision", "for", "all", "the", "orders", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L332-L354
32,463
dmlc/gluon-nlp
scripts/word_embeddings/data.py
preprocess_dataset
def preprocess_dataset(data, min_freq=5, max_vocab_size=None): """Dataset preprocessing helper. Parameters ---------- data : mx.data.Dataset Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9 min_freq : int, default 5 Minimum token frequency for a token to be inclu...
python
def preprocess_dataset(data, min_freq=5, max_vocab_size=None): """Dataset preprocessing helper. Parameters ---------- data : mx.data.Dataset Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9 min_freq : int, default 5 Minimum token frequency for a token to be inclu...
[ "def", "preprocess_dataset", "(", "data", ",", "min_freq", "=", "5", ",", "max_vocab_size", "=", "None", ")", ":", "with", "print_time", "(", "'count and construct vocabulary'", ")", ":", "counter", "=", "nlp", ".", "data", ".", "count_tokens", "(", "itertools...
Dataset preprocessing helper. Parameters ---------- data : mx.data.Dataset Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9 min_freq : int, default 5 Minimum token frequency for a token to be included in the vocabulary and returned DataStream. max_vocab_s...
[ "Dataset", "preprocessing", "helper", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L47-L86
32,464
dmlc/gluon-nlp
scripts/word_embeddings/data.py
wiki
def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None): """Wikipedia dump helper. Parameters ---------- wiki_root : str Parameter for WikiDumpStream wiki_date : str Parameter for WikiDumpStream wiki_language : str Parameter for WikiDumpStream max_vocab_si...
python
def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None): """Wikipedia dump helper. Parameters ---------- wiki_root : str Parameter for WikiDumpStream wiki_date : str Parameter for WikiDumpStream wiki_language : str Parameter for WikiDumpStream max_vocab_si...
[ "def", "wiki", "(", "wiki_root", ",", "wiki_date", ",", "wiki_language", ",", "max_vocab_size", "=", "None", ")", ":", "data", "=", "WikiDumpStream", "(", "root", "=", "os", ".", "path", ".", "expanduser", "(", "wiki_root", ")", ",", "language", "=", "wi...
Wikipedia dump helper. Parameters ---------- wiki_root : str Parameter for WikiDumpStream wiki_date : str Parameter for WikiDumpStream wiki_language : str Parameter for WikiDumpStream max_vocab_size : int, optional Specifies a maximum size for the vocabulary. ...
[ "Wikipedia", "dump", "helper", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L89-L131
32,465
dmlc/gluon-nlp
scripts/word_embeddings/data.py
cbow_fasttext_batch
def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): """Create a batch for CBOW training objective with subwords.""" _, contexts_row, contexts_col = contexts data, row, col = subword_lookup(contexts_row, contexts_col) centers = mx.nd.array(c...
python
def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): """Create a batch for CBOW training objective with subwords.""" _, contexts_row, contexts_col = contexts data, row, col = subword_lookup(contexts_row, contexts_col) centers = mx.nd.array(c...
[ "def", "cbow_fasttext_batch", "(", "centers", ",", "contexts", ",", "num_tokens", ",", "subword_lookup", ",", "dtype", ",", "index_dtype", ")", ":", "_", ",", "contexts_row", ",", "contexts_col", "=", "contexts", "data", ",", "row", ",", "col", "=", "subword...
Create a batch for CBOW training objective with subwords.
[ "Create", "a", "batch", "for", "CBOW", "training", "objective", "with", "subwords", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L322-L331
32,466
dmlc/gluon-nlp
scripts/word_embeddings/data.py
skipgram_fasttext_batch
def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): """Create a batch for SG training objective with subwords.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) data, row, col = subword_lookup(centers) centers = mx.nd.array(...
python
def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): """Create a batch for SG training objective with subwords.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) data, row, col = subword_lookup(centers) centers = mx.nd.array(...
[ "def", "skipgram_fasttext_batch", "(", "centers", ",", "contexts", ",", "num_tokens", ",", "subword_lookup", ",", "dtype", ",", "index_dtype", ")", ":", "contexts", "=", "mx", ".", "nd", ".", "array", "(", "contexts", "[", "2", "]", ",", "dtype", "=", "i...
Create a batch for SG training objective with subwords.
[ "Create", "a", "batch", "for", "SG", "training", "objective", "with", "subwords", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L334-L343
32,467
dmlc/gluon-nlp
scripts/word_embeddings/data.py
cbow_batch
def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for CBOW training objective.""" contexts_data, contexts_row, contexts_col = contexts centers = mx.nd.array(centers, dtype=index_dtype) contexts = mx.nd.sparse.csr_matrix( (contexts_data, (contexts_row, contexts_...
python
def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for CBOW training objective.""" contexts_data, contexts_row, contexts_col = contexts centers = mx.nd.array(centers, dtype=index_dtype) contexts = mx.nd.sparse.csr_matrix( (contexts_data, (contexts_row, contexts_...
[ "def", "cbow_batch", "(", "centers", ",", "contexts", ",", "num_tokens", ",", "dtype", ",", "index_dtype", ")", ":", "contexts_data", ",", "contexts_row", ",", "contexts_col", "=", "contexts", "centers", "=", "mx", ".", "nd", ".", "array", "(", "centers", ...
Create a batch for CBOW training objective.
[ "Create", "a", "batch", "for", "CBOW", "training", "objective", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L346-L353
32,468
dmlc/gluon-nlp
scripts/word_embeddings/data.py
skipgram_batch
def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for SG training objective.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) indptr = mx.nd.arange(len(centers) + 1) centers = mx.nd.array(centers, dtype=index_dtype) centers_csr = mx.nd.sparse.csr_matri...
python
def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for SG training objective.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) indptr = mx.nd.arange(len(centers) + 1) centers = mx.nd.array(centers, dtype=index_dtype) centers_csr = mx.nd.sparse.csr_matri...
[ "def", "skipgram_batch", "(", "centers", ",", "contexts", ",", "num_tokens", ",", "dtype", ",", "index_dtype", ")", ":", "contexts", "=", "mx", ".", "nd", ".", "array", "(", "contexts", "[", "2", "]", ",", "dtype", "=", "index_dtype", ")", "indptr", "=...
Create a batch for SG training objective.
[ "Create", "a", "batch", "for", "SG", "training", "objective", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L356-L364
32,469
dmlc/gluon-nlp
scripts/word_embeddings/data.py
skipgram_lookup
def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for SkipGram. Parameters ---------- indices : numpy.ndarray Array containing numbers in [0, vocabulary_size). The element at position idx is taken to be the word that occ...
python
def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for SkipGram. Parameters ---------- indices : numpy.ndarray Array containing numbers in [0, vocabulary_size). The element at position idx is taken to be the word that occ...
[ "def", "skipgram_lookup", "(", "indices", ",", "subwordidxs", ",", "subwordidxsptr", ",", "offset", "=", "0", ")", ":", "row", "=", "[", "]", "col", "=", "[", "]", "data", "=", "[", "]", "for", "i", ",", "idx", "in", "enumerate", "(", "indices", ")...
Get a sparse COO array of words and subwords for SkipGram. Parameters ---------- indices : numpy.ndarray Array containing numbers in [0, vocabulary_size). The element at position idx is taken to be the word that occurs at row idx in the SkipGram batch. offset : int Offse...
[ "Get", "a", "sparse", "COO", "array", "of", "words", "and", "subwords", "for", "SkipGram", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L376-L427
32,470
dmlc/gluon-nlp
scripts/word_embeddings/data.py
cbow_lookup
def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for CBOW. Parameters ---------- context_row : numpy.ndarray of dtype int64 Array of same length as context_col containing numbers in [0, batc...
python
def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for CBOW. Parameters ---------- context_row : numpy.ndarray of dtype int64 Array of same length as context_col containing numbers in [0, batc...
[ "def", "cbow_lookup", "(", "context_row", ",", "context_col", ",", "subwordidxs", ",", "subwordidxsptr", ",", "offset", "=", "0", ")", ":", "row", "=", "[", "]", "col", "=", "[", "]", "data", "=", "[", "]", "num_rows", "=", "np", ".", "max", "(", "...
Get a sparse COO array of words and subwords for CBOW. Parameters ---------- context_row : numpy.ndarray of dtype int64 Array of same length as context_col containing numbers in [0, batch_size). For each idx, context_row[idx] specifies the row that context_col[idx] occurs in a spars...
[ "Get", "a", "sparse", "COO", "array", "of", "words", "and", "subwords", "for", "CBOW", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L431-L501
32,471
dmlc/gluon-nlp
src/gluonnlp/data/translation.py
_TranslationDataset.src_vocab
def src_vocab(self): """Source Vocabulary of the Dataset. Returns ------- src_vocab : Vocab Source vocabulary. """ if self._src_vocab is None: src_vocab_file_name, src_vocab_hash = \ self._data_file[self._pair_key]['vocab' + '_' + ...
python
def src_vocab(self): """Source Vocabulary of the Dataset. Returns ------- src_vocab : Vocab Source vocabulary. """ if self._src_vocab is None: src_vocab_file_name, src_vocab_hash = \ self._data_file[self._pair_key]['vocab' + '_' + ...
[ "def", "src_vocab", "(", "self", ")", ":", "if", "self", ".", "_src_vocab", "is", "None", ":", "src_vocab_file_name", ",", "src_vocab_hash", "=", "self", ".", "_data_file", "[", "self", ".", "_pair_key", "]", "[", "'vocab'", "+", "'_'", "+", "self", ".",...
Source Vocabulary of the Dataset. Returns ------- src_vocab : Vocab Source vocabulary.
[ "Source", "Vocabulary", "of", "the", "Dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/translation.py#L119-L133
32,472
dmlc/gluon-nlp
src/gluonnlp/data/translation.py
_TranslationDataset.tgt_vocab
def tgt_vocab(self): """Target Vocabulary of the Dataset. Returns ------- tgt_vocab : Vocab Target vocabulary. """ if self._tgt_vocab is None: tgt_vocab_file_name, tgt_vocab_hash = \ self._data_file[self._pair_key]['vocab' + '_' + ...
python
def tgt_vocab(self): """Target Vocabulary of the Dataset. Returns ------- tgt_vocab : Vocab Target vocabulary. """ if self._tgt_vocab is None: tgt_vocab_file_name, tgt_vocab_hash = \ self._data_file[self._pair_key]['vocab' + '_' + ...
[ "def", "tgt_vocab", "(", "self", ")", ":", "if", "self", ".", "_tgt_vocab", "is", "None", ":", "tgt_vocab_file_name", ",", "tgt_vocab_hash", "=", "self", ".", "_data_file", "[", "self", ".", "_pair_key", "]", "[", "'vocab'", "+", "'_'", "+", "self", ".",...
Target Vocabulary of the Dataset. Returns ------- tgt_vocab : Vocab Target vocabulary.
[ "Target", "Vocabulary", "of", "the", "Dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/translation.py#L136-L150
32,473
dmlc/gluon-nlp
scripts/machine_translation/train_gnmt.py
evaluate
def evaluate(data_loader): """Evaluate given the data loader Parameters ---------- data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_out : list of list of str The translation output """ translation_out = [] all_inst_ids ...
python
def evaluate(data_loader): """Evaluate given the data loader Parameters ---------- data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_out : list of list of str The translation output """ translation_out = [] all_inst_ids ...
[ "def", "evaluate", "(", "data_loader", ")", ":", "translation_out", "=", "[", "]", "all_inst_ids", "=", "[", "]", "avg_loss_denom", "=", "0", "avg_loss", "=", "0.0", "for", "_", ",", "(", "src_seq", ",", "tgt_seq", ",", "src_valid_length", ",", "tgt_valid_...
Evaluate given the data loader Parameters ---------- data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_out : list of list of str The translation output
[ "Evaluate", "given", "the", "data", "loader" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/train_gnmt.py#L147-L190
32,474
dmlc/gluon-nlp
src/gluonnlp/model/train/__init__.py
get_cache_model
def get_cache_model(name, dataset_name='wikitext-2', window=2000, theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs): r"""Returns a cache model using a pre-trained language model. We implement the neural cache language model proposed in the following work:: @article{grave2016improving...
python
def get_cache_model(name, dataset_name='wikitext-2', window=2000, theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs): r"""Returns a cache model using a pre-trained language model. We implement the neural cache language model proposed in the following work:: @article{grave2016improving...
[ "def", "get_cache_model", "(", "name", ",", "dataset_name", "=", "'wikitext-2'", ",", "window", "=", "2000", ",", "theta", "=", "0.6", ",", "lambdas", "=", "0.2", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "*", "*", "kwargs", ")", ":", "lm_m...
r"""Returns a cache model using a pre-trained language model. We implement the neural cache language model proposed in the following work:: @article{grave2016improving, title={Improving neural language models with a continuous cache}, author={Grave, Edouard and Joulin, Armand and Usunier, ...
[ "r", "Returns", "a", "cache", "model", "using", "a", "pre", "-", "trained", "language", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/__init__.py#L36-L98
32,475
dmlc/gluon-nlp
src/gluonnlp/data/dataset.py
NumpyDataset.get_field
def get_field(self, field): """Return the dataset corresponds to the provided key. Example:: a = np.ones((2,2)) b = np.zeros((2,2)) np.savez('data.npz', a=a, b=b) dataset = NumpyDataset('data.npz') data_a = dataset.get_field('a') d...
python
def get_field(self, field): """Return the dataset corresponds to the provided key. Example:: a = np.ones((2,2)) b = np.zeros((2,2)) np.savez('data.npz', a=a, b=b) dataset = NumpyDataset('data.npz') data_a = dataset.get_field('a') d...
[ "def", "get_field", "(", "self", ",", "field", ")", ":", "idx", "=", "self", ".", "_keys", ".", "index", "(", "field", ")", "return", "self", ".", "_data", "[", "idx", "]" ]
Return the dataset corresponds to the provided key. Example:: a = np.ones((2,2)) b = np.zeros((2,2)) np.savez('data.npz', a=a, b=b) dataset = NumpyDataset('data.npz') data_a = dataset.get_field('a') data_b = dataset.get_field('b') ...
[ "Return", "the", "dataset", "corresponds", "to", "the", "provided", "key", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/dataset.py#L259-L276
32,476
dmlc/gluon-nlp
scripts/bert/bert_qa_evaluate.py
get_F1_EM
def get_F1_EM(dataset, predict_data): """Calculate the F1 and EM scores of the predicted results. Use only with the SQuAD1.1 dataset. Parameters ---------- dataset_file: string Path to the data file. predict_data: dict All final predictions. Returns ------- scores: ...
python
def get_F1_EM(dataset, predict_data): """Calculate the F1 and EM scores of the predicted results. Use only with the SQuAD1.1 dataset. Parameters ---------- dataset_file: string Path to the data file. predict_data: dict All final predictions. Returns ------- scores: ...
[ "def", "get_F1_EM", "(", "dataset", ",", "predict_data", ")", ":", "f1", "=", "exact_match", "=", "total", "=", "0", "for", "record", "in", "dataset", ":", "total", "+=", "1", "if", "record", "[", "1", "]", "not", "in", "predict_data", ":", "message", ...
Calculate the F1 and EM scores of the predicted results. Use only with the SQuAD1.1 dataset. Parameters ---------- dataset_file: string Path to the data file. predict_data: dict All final predictions. Returns ------- scores: dict F1 and EM scores.
[ "Calculate", "the", "F1", "and", "EM", "scores", "of", "the", "predicted", "results", ".", "Use", "only", "with", "the", "SQuAD1", ".", "1", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_evaluate.py#L374-L409
32,477
dmlc/gluon-nlp
scripts/bert/finetune_classifier.py
preprocess_data
def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, pad=False): """Data preparation function.""" # transformation trans = BERTDatasetTransform( tokenizer, max_len, labels=task.get_labels(), pad=pad, pair=task.is_pair, label_dtype='float32...
python
def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, pad=False): """Data preparation function.""" # transformation trans = BERTDatasetTransform( tokenizer, max_len, labels=task.get_labels(), pad=pad, pair=task.is_pair, label_dtype='float32...
[ "def", "preprocess_data", "(", "tokenizer", ",", "task", ",", "batch_size", ",", "dev_batch_size", ",", "max_len", ",", "pad", "=", "False", ")", ":", "# transformation", "trans", "=", "BERTDatasetTransform", "(", "tokenizer", ",", "max_len", ",", "labels", "=...
Data preparation function.
[ "Data", "preparation", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L247-L301
32,478
dmlc/gluon-nlp
scripts/bert/finetune_classifier.py
log_train
def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate): """Generate and print out the log message for training. """ metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] train_...
python
def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate): """Generate and print out the log message for training. """ metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] train_...
[ "def", "log_train", "(", "batch_id", ",", "batch_num", ",", "metric", ",", "step_loss", ",", "log_interval", ",", "epoch_id", ",", "learning_rate", ")", ":", "metric_nm", ",", "metric_val", "=", "metric", ".", "get", "(", ")", "if", "not", "isinstance", "(...
Generate and print out the log message for training.
[ "Generate", "and", "print", "out", "the", "log", "message", "for", "training", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L333-L346
32,479
dmlc/gluon-nlp
scripts/bert/finetune_classifier.py
log_inference
def log_inference(batch_id, batch_num, metric, step_loss, log_interval): """Generate and print out the log message for inference. """ metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] eval_str = '[Batch %d/%d] ...
python
def log_inference(batch_id, batch_num, metric, step_loss, log_interval): """Generate and print out the log message for inference. """ metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] eval_str = '[Batch %d/%d] ...
[ "def", "log_inference", "(", "batch_id", ",", "batch_num", ",", "metric", ",", "step_loss", ",", "log_interval", ")", ":", "metric_nm", ",", "metric_val", "=", "metric", ".", "get", "(", ")", "if", "not", "isinstance", "(", "metric_nm", ",", "list", ")", ...
Generate and print out the log message for inference.
[ "Generate", "and", "print", "out", "the", "log", "message", "for", "inference", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L349-L361
32,480
dmlc/gluon-nlp
scripts/bert/finetune_classifier.py
inference
def inference(metric): """Inference function.""" logging.info('Now we are doing BERT classification inference on %s!', ctx) model = BERTClassifier(bert, dropout=0.1, num_classes=len(task.get_labels())) model.hybridize(static_alloc=True) model.load_parameters(model_parameters, ctx=ctx) metric.r...
python
def inference(metric): """Inference function.""" logging.info('Now we are doing BERT classification inference on %s!', ctx) model = BERTClassifier(bert, dropout=0.1, num_classes=len(task.get_labels())) model.hybridize(static_alloc=True) model.load_parameters(model_parameters, ctx=ctx) metric.r...
[ "def", "inference", "(", "metric", ")", ":", "logging", ".", "info", "(", "'Now we are doing BERT classification inference on %s!'", ",", "ctx", ")", "model", "=", "BERTClassifier", "(", "bert", ",", "dropout", "=", "0.1", ",", "num_classes", "=", "len", "(", ...
Inference function.
[ "Inference", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L462-L492
32,481
dmlc/gluon-nlp
scripts/question_answering/data_processing.py
preprocess_dataset
def preprocess_dataset(dataset, question_max_length, context_max_length): """Process SQuAD dataset by creating NDArray version of data :param Dataset dataset: SQuAD dataset :param int question_max_length: Maximum length of question (padded or trimmed to that size) :param int context_max_length: Maximum...
python
def preprocess_dataset(dataset, question_max_length, context_max_length): """Process SQuAD dataset by creating NDArray version of data :param Dataset dataset: SQuAD dataset :param int question_max_length: Maximum length of question (padded or trimmed to that size) :param int context_max_length: Maximum...
[ "def", "preprocess_dataset", "(", "dataset", ",", "question_max_length", ",", "context_max_length", ")", ":", "vocab_provider", "=", "VocabProvider", "(", "dataset", ")", "transformer", "=", "SQuADTransform", "(", "vocab_provider", ",", "question_max_length", ",", "co...
Process SQuAD dataset by creating NDArray version of data :param Dataset dataset: SQuAD dataset :param int question_max_length: Maximum length of question (padded or trimmed to that size) :param int context_max_length: Maximum length of context (padded or trimmed to that size) Returns ------- ...
[ "Process", "SQuAD", "dataset", "by", "creating", "NDArray", "version", "of", "data" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/question_answering/data_processing.py#L34-L51
32,482
dmlc/gluon-nlp
scripts/question_answering/data_processing.py
SQuADTransform._get_answer_spans
def _get_answer_spans(answer_list, answer_start_list): """Find all answer spans from the context, returning start_index and end_index :param list[str] answer_list: List of all answers :param list[int] answer_start_list: List of all answers' start indices Returns ------- ...
python
def _get_answer_spans(answer_list, answer_start_list): """Find all answer spans from the context, returning start_index and end_index :param list[str] answer_list: List of all answers :param list[int] answer_start_list: List of all answers' start indices Returns ------- ...
[ "def", "_get_answer_spans", "(", "answer_list", ",", "answer_start_list", ")", ":", "return", "[", "(", "answer_start_list", "[", "i", "]", ",", "answer_start_list", "[", "i", "]", "+", "len", "(", "answer", ")", ")", "for", "i", ",", "answer", "in", "en...
Find all answer spans from the context, returning start_index and end_index :param list[str] answer_list: List of all answers :param list[int] answer_start_list: List of all answers' start indices Returns ------- List[Tuple] list of Tuple(answer_start_index answer_e...
[ "Find", "all", "answer", "spans", "from", "the", "context", "returning", "start_index", "and", "end_index" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/question_answering/data_processing.py#L98-L110
32,483
dmlc/gluon-nlp
scripts/question_answering/data_processing.py
VocabProvider.get_word_level_vocab
def get_word_level_vocab(self): """Provides word level vocabulary Returns ------- Vocab Word level vocabulary """ def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'): return list(filter(None, re.split(token_delim + '|' + seq_delim, s...
python
def get_word_level_vocab(self): """Provides word level vocabulary Returns ------- Vocab Word level vocabulary """ def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'): return list(filter(None, re.split(token_delim + '|' + seq_delim, s...
[ "def", "get_word_level_vocab", "(", "self", ")", ":", "def", "simple_tokenize", "(", "source_str", ",", "token_delim", "=", "' '", ",", "seq_delim", "=", "'\\n'", ")", ":", "return", "list", "(", "filter", "(", "None", ",", "re", ".", "split", "(", "toke...
Provides word level vocabulary Returns ------- Vocab Word level vocabulary
[ "Provides", "word", "level", "vocabulary" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/question_answering/data_processing.py#L130-L142
32,484
dmlc/gluon-nlp
src/gluonnlp/data/transforms.py
BERTBasicTokenizer._clean_text
def _clean_text(self, text): """Performs invalid character removal and whitespace cleanup on text.""" output = [] for char in text: cp = ord(char) if cp in (0, 0xfffd) or self._is_control(char): continue if self._is_whitespace(char): ...
python
def _clean_text(self, text): """Performs invalid character removal and whitespace cleanup on text.""" output = [] for char in text: cp = ord(char) if cp in (0, 0xfffd) or self._is_control(char): continue if self._is_whitespace(char): ...
[ "def", "_clean_text", "(", "self", ",", "text", ")", ":", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cp", "=", "ord", "(", "char", ")", "if", "cp", "in", "(", "0", ",", "0xfffd", ")", "or", "self", ".", "_is_control", "(", "cha...
Performs invalid character removal and whitespace cleanup on text.
[ "Performs", "invalid", "character", "removal", "and", "whitespace", "cleanup", "on", "text", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L780-L791
32,485
dmlc/gluon-nlp
src/gluonnlp/data/transforms.py
BERTBasicTokenizer._is_control
def _is_control(self, char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char in ['\t', '\n', '\r']: return False cat = unicodedata.category(char) if cat.start...
python
def _is_control(self, char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char in ['\t', '\n', '\r']: return False cat = unicodedata.category(char) if cat.start...
[ "def", "_is_control", "(", "self", ",", "char", ")", ":", "# These are technically control characters but we count them as whitespace", "# characters.", "if", "char", "in", "[", "'\\t'", ",", "'\\n'", ",", "'\\r'", "]", ":", "return", "False", "cat", "=", "unicodeda...
Checks whether `chars` is a control character.
[ "Checks", "whether", "chars", "is", "a", "control", "character", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L793-L802
32,486
dmlc/gluon-nlp
src/gluonnlp/data/transforms.py
BERTBasicTokenizer._run_split_on_punc
def _run_split_on_punc(self, text): """Splits punctuation on a piece of text.""" chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if self._is_punctuation(char): output.append([char]) ...
python
def _run_split_on_punc(self, text): """Splits punctuation on a piece of text.""" chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if self._is_punctuation(char): output.append([char]) ...
[ "def", "_run_split_on_punc", "(", "self", ",", "text", ")", ":", "chars", "=", "list", "(", "text", ")", "i", "=", "0", "start_new_word", "=", "True", "output", "=", "[", "]", "while", "i", "<", "len", "(", "chars", ")", ":", "char", "=", "chars", ...
Splits punctuation on a piece of text.
[ "Splits", "punctuation", "on", "a", "piece", "of", "text", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L850-L868
32,487
dmlc/gluon-nlp
src/gluonnlp/data/transforms.py
BERTBasicTokenizer._is_whitespace
def _is_whitespace(self, char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char in [' ', '\t', '\n', '\r']: return True c...
python
def _is_whitespace(self, char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char in [' ', '\t', '\n', '\r']: return True c...
[ "def", "_is_whitespace", "(", "self", ",", "char", ")", ":", "# \\t, \\n, and \\r are technically contorl characters but we treat them", "# as whitespace since they are generally considered as such.", "if", "char", "in", "[", "' '", ",", "'\\t'", ",", "'\\n'", ",", "'\\r'", ...
Checks whether `chars` is a whitespace character.
[ "Checks", "whether", "chars", "is", "a", "whitespace", "character", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L888-L897
32,488
dmlc/gluon-nlp
src/gluonnlp/data/transforms.py
BERTSentenceTransform._truncate_seq_pair
def _truncate_seq_pair(self, tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tok...
python
def _truncate_seq_pair(self, tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tok...
[ "def", "_truncate_seq_pair", "(", "self", ",", "tokens_a", ",", "tokens_b", ",", "max_length", ")", ":", "# This is a simple heuristic which will always truncate the longer sequence", "# one token at a time. This makes more sense than truncating an equal percent", "# of tokens from each,...
Truncates a sequence pair in place to the maximum length.
[ "Truncates", "a", "sequence", "pair", "in", "place", "to", "the", "maximum", "length", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L1144-L1157
32,489
dmlc/gluon-nlp
scripts/word_embeddings/evaluate_pretrained.py
get_args
def get_args(): """Construct the argument parser.""" parser = argparse.ArgumentParser( description='Word embedding evaluation with Gluon.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Embeddings arguments group = parser.add_argument_group('Embedding arguments') group.a...
python
def get_args(): """Construct the argument parser.""" parser = argparse.ArgumentParser( description='Word embedding evaluation with Gluon.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Embeddings arguments group = parser.add_argument_group('Embedding arguments') group.a...
[ "def", "get_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Word embedding evaluation with Gluon.'", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", "# Embeddings arguments", "group", ...
Construct the argument parser.
[ "Construct", "the", "argument", "parser", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluate_pretrained.py#L40-L97
32,490
dmlc/gluon-nlp
scripts/word_embeddings/evaluate_pretrained.py
load_embedding_from_path
def load_embedding_from_path(args): """Load a TokenEmbedding.""" if args.embedding_path.endswith('.bin'): with utils.print_time('load fastText model.'): model = \ nlp.model.train.FasttextEmbeddingModel.load_fasttext_format( args.embedding_path) idx...
python
def load_embedding_from_path(args): """Load a TokenEmbedding.""" if args.embedding_path.endswith('.bin'): with utils.print_time('load fastText model.'): model = \ nlp.model.train.FasttextEmbeddingModel.load_fasttext_format( args.embedding_path) idx...
[ "def", "load_embedding_from_path", "(", "args", ")", ":", "if", "args", ".", "embedding_path", ".", "endswith", "(", "'.bin'", ")", ":", "with", "utils", ".", "print_time", "(", "'load fastText model.'", ")", ":", "model", "=", "nlp", ".", "model", ".", "t...
Load a TokenEmbedding.
[ "Load", "a", "TokenEmbedding", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluate_pretrained.py#L134-L163
32,491
dmlc/gluon-nlp
scripts/bert/fp16_utils.py
grad_global_norm
def grad_global_norm(parameters, max_norm): """Calculate the 2-norm of gradients of parameters, and how much they should be scaled down such that their 2-norm does not exceed `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grad...
python
def grad_global_norm(parameters, max_norm): """Calculate the 2-norm of gradients of parameters, and how much they should be scaled down such that their 2-norm does not exceed `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grad...
[ "def", "grad_global_norm", "(", "parameters", ",", "max_norm", ")", ":", "# collect gradient arrays", "arrays", "=", "[", "]", "idx", "=", "0", "for", "p", "in", "parameters", ":", "if", "p", ".", "grad_req", "!=", "'null'", ":", "p_grads", "=", "p", "."...
Calculate the 2-norm of gradients of parameters, and how much they should be scaled down such that their 2-norm does not exceed `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients are summed first before c...
[ "Calculate", "the", "2", "-", "norm", "of", "gradients", "of", "parameters", "and", "how", "much", "they", "should", "be", "scaled", "down", "such", "that", "their", "2", "-", "norm", "does", "not", "exceed", "max_norm", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L26-L107
32,492
dmlc/gluon-nlp
scripts/bert/fp16_utils.py
FP16Trainer.backward
def backward(self, loss): """backward propagation with loss""" with mx.autograd.record(): if isinstance(loss, (tuple, list)): ls = [l * self._scaler.loss_scale for l in loss] else: ls = loss * self._scaler.loss_scale mx.autograd.backward(ls...
python
def backward(self, loss): """backward propagation with loss""" with mx.autograd.record(): if isinstance(loss, (tuple, list)): ls = [l * self._scaler.loss_scale for l in loss] else: ls = loss * self._scaler.loss_scale mx.autograd.backward(ls...
[ "def", "backward", "(", "self", ",", "loss", ")", ":", "with", "mx", ".", "autograd", ".", "record", "(", ")", ":", "if", "isinstance", "(", "loss", ",", "(", "tuple", ",", "list", ")", ")", ":", "ls", "=", "[", "l", "*", "self", ".", "_scaler"...
backward propagation with loss
[ "backward", "propagation", "with", "loss" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L138-L145
32,493
dmlc/gluon-nlp
scripts/bert/fp16_utils.py
LossScaler.has_overflow
def has_overflow(self, params): """ detect inf and nan """ is_not_finite = 0 for param in params: if param.grad_req != 'null': grad = param.list_grad()[0] is_not_finite += mx.nd.contrib.isnan(grad).sum() is_not_finite += mx.nd.contrib.i...
python
def has_overflow(self, params): """ detect inf and nan """ is_not_finite = 0 for param in params: if param.grad_req != 'null': grad = param.list_grad()[0] is_not_finite += mx.nd.contrib.isnan(grad).sum() is_not_finite += mx.nd.contrib.i...
[ "def", "has_overflow", "(", "self", ",", "params", ")", ":", "is_not_finite", "=", "0", "for", "param", "in", "params", ":", "if", "param", ".", "grad_req", "!=", "'null'", ":", "grad", "=", "param", ".", "list_grad", "(", ")", "[", "0", "]", "is_not...
detect inf and nan
[ "detect", "inf", "and", "nan" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L187-L199
32,494
dmlc/gluon-nlp
scripts/bert/fp16_utils.py
DynamicLossScaler.update_scale
def update_scale(self, overflow): """dynamically update loss scale""" iter_since_rescale = self._num_steps - self._last_rescale_iter if overflow: self._last_overflow_iter = self._num_steps self._overflows_since_rescale += 1 percentage = self._overflows_since_r...
python
def update_scale(self, overflow): """dynamically update loss scale""" iter_since_rescale = self._num_steps - self._last_rescale_iter if overflow: self._last_overflow_iter = self._num_steps self._overflows_since_rescale += 1 percentage = self._overflows_since_r...
[ "def", "update_scale", "(", "self", ",", "overflow", ")", ":", "iter_since_rescale", "=", "self", ".", "_num_steps", "-", "self", ".", "_last_rescale_iter", "if", "overflow", ":", "self", ".", "_last_overflow_iter", "=", "self", ".", "_num_steps", "self", ".",...
dynamically update loss scale
[ "dynamically", "update", "loss", "scale" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L236-L253
32,495
dmlc/gluon-nlp
src/gluonnlp/data/sampler.py
FixedBucketSampler.stats
def stats(self): """Return a string representing the statistics of the bucketing sampler. Returns ------- ret : str String representing the statistics of the buckets. """ ret = '{name}:\n' \ ' sample_num={sample_num}, batch_num={batch_num}\n' \ ...
python
def stats(self): """Return a string representing the statistics of the bucketing sampler. Returns ------- ret : str String representing the statistics of the buckets. """ ret = '{name}:\n' \ ' sample_num={sample_num}, batch_num={batch_num}\n' \ ...
[ "def", "stats", "(", "self", ")", ":", "ret", "=", "'{name}:\\n'", "' sample_num={sample_num}, batch_num={batch_num}\\n'", "' key={bucket_keys}\\n'", "' cnt={bucket_counts}\\n'", "' batch_size={bucket_batch_sizes}'", ".", "format", "(", "name", "=", "self", ".", "__class_...
Return a string representing the statistics of the bucketing sampler. Returns ------- ret : str String representing the statistics of the buckets.
[ "Return", "a", "string", "representing", "the", "statistics", "of", "the", "bucketing", "sampler", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/sampler.py#L420-L439
32,496
dmlc/gluon-nlp
scripts/language_model/large_word_language_model.py
evaluate
def evaluate(): """ Evaluate loop for the trained model """ print(eval_model) eval_model.initialize(mx.init.Xavier(), ctx=context[0]) eval_model.hybridize(static_alloc=True, static_shape=True) epoch = args.from_epoch if args.from_epoch else 0 while epoch < args.epochs: checkpoint_name = ...
python
def evaluate(): """ Evaluate loop for the trained model """ print(eval_model) eval_model.initialize(mx.init.Xavier(), ctx=context[0]) eval_model.hybridize(static_alloc=True, static_shape=True) epoch = args.from_epoch if args.from_epoch else 0 while epoch < args.epochs: checkpoint_name = ...
[ "def", "evaluate", "(", ")", ":", "print", "(", "eval_model", ")", "eval_model", ".", "initialize", "(", "mx", ".", "init", ".", "Xavier", "(", ")", ",", "ctx", "=", "context", "[", "0", "]", ")", "eval_model", ".", "hybridize", "(", "static_alloc", ...
Evaluate loop for the trained model
[ "Evaluate", "loop", "for", "the", "trained", "model" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/large_word_language_model.py#L345-L367
32,497
dmlc/gluon-nlp
scripts/sentiment_analysis/process_data.py
load_dataset
def load_dataset(data_name): """Load sentiment dataset.""" if data_name == 'MR' or data_name == 'Subj': train_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, []) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vo...
python
def load_dataset(data_name): """Load sentiment dataset.""" if data_name == 'MR' or data_name == 'Subj': train_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, []) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vo...
[ "def", "load_dataset", "(", "data_name", ")", ":", "if", "data_name", "==", "'MR'", "or", "data_name", "==", "'Subj'", ":", "train_dataset", ",", "output_size", "=", "_load_file", "(", "data_name", ")", "vocab", ",", "max_len", "=", "_build_vocab", "(", "dat...
Load sentiment dataset.
[ "Load", "sentiment", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/process_data.py#L120-L133
32,498
dmlc/gluon-nlp
scripts/natural_language_inference/dataset.py
read_dataset
def read_dataset(args, dataset): """ Read dataset from tokenized files. """ path = os.path.join(vars(args)[dataset]) logger.info('reading data from {}'.format(path)) examples = [line.strip().split('\t') for line in open(path)] if args.max_num_examples > 0: examples = examples[:args.m...
python
def read_dataset(args, dataset): """ Read dataset from tokenized files. """ path = os.path.join(vars(args)[dataset]) logger.info('reading data from {}'.format(path)) examples = [line.strip().split('\t') for line in open(path)] if args.max_num_examples > 0: examples = examples[:args.m...
[ "def", "read_dataset", "(", "args", ",", "dataset", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "vars", "(", "args", ")", "[", "dataset", "]", ")", "logger", ".", "info", "(", "'reading data from {}'", ".", "format", "(", "path", ")",...
Read dataset from tokenized files.
[ "Read", "dataset", "from", "tokenized", "files", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L35-L51
32,499
dmlc/gluon-nlp
scripts/natural_language_inference/dataset.py
build_vocab
def build_vocab(dataset): """ Build vocab given a dataset. """ counter = nlp.data.count_tokens([w for e in dataset for s in e[:2] for w in s], to_lower=True) vocab = nlp.Vocab(counter) return vocab
python
def build_vocab(dataset): """ Build vocab given a dataset. """ counter = nlp.data.count_tokens([w for e in dataset for s in e[:2] for w in s], to_lower=True) vocab = nlp.Vocab(counter) return vocab
[ "def", "build_vocab", "(", "dataset", ")", ":", "counter", "=", "nlp", ".", "data", ".", "count_tokens", "(", "[", "w", "for", "e", "in", "dataset", "for", "s", "in", "e", "[", ":", "2", "]", "for", "w", "in", "s", "]", ",", "to_lower", "=", "T...
Build vocab given a dataset.
[ "Build", "vocab", "given", "a", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L53-L60