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 objects anytime you're
done using them, instead of relying on garbage collection.
"""
if self._transport is None:
return
self._transport.close()
self._transport = None
if self._agent is not None:
self._agent.close()
self._agent = None | 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 objects anytime you're
done using them, instead of relying on garbage collection.
"""
if self._transport is None:
return
self._transport.close()
self._transport = None
if self._agent is not None:
self._agent.close()
self._agent = None | [
"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 using them, instead of relying on garbage collection. | [
"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
streams are returned as Python ``file``-like objects representing
stdin, stdout, and stderr.
:param str command: the command to execute
:param int bufsize:
interpreted the same way as by the built-in ``file()`` function in
Python
:param int timeout:
set command's channel timeout. See `.Channel.settimeout`
:param bool get_pty:
Request a pseudo-terminal from the server (default ``False``).
See `.Channel.get_pty`
:param dict environment:
a dict of shell environment variables, to be merged into the
default environment that the remote command executes within.
.. warning::
Servers may silently reject some environment variables; see the
warning in `.Channel.set_environment_variable` for details.
:return:
the stdin, stdout, and stderr of the executing command, as a
3-tuple
:raises: `.SSHException` -- if the server fails to execute the command
.. versionchanged:: 1.10
Added the ``get_pty`` kwarg.
"""
chan = self._transport.open_session(timeout=timeout)
if get_pty:
chan.get_pty()
chan.settimeout(timeout)
if environment:
chan.update_environment(environment)
chan.exec_command(command)
stdin = chan.makefile("wb", bufsize)
stdout = chan.makefile("r", bufsize)
stderr = chan.makefile_stderr("r", bufsize)
return stdin, stdout, stderr | 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
streams are returned as Python ``file``-like objects representing
stdin, stdout, and stderr.
:param str command: the command to execute
:param int bufsize:
interpreted the same way as by the built-in ``file()`` function in
Python
:param int timeout:
set command's channel timeout. See `.Channel.settimeout`
:param bool get_pty:
Request a pseudo-terminal from the server (default ``False``).
See `.Channel.get_pty`
:param dict environment:
a dict of shell environment variables, to be merged into the
default environment that the remote command executes within.
.. warning::
Servers may silently reject some environment variables; see the
warning in `.Channel.set_environment_variable` for details.
:return:
the stdin, stdout, and stderr of the executing command, as a
3-tuple
:raises: `.SSHException` -- if the server fails to execute the command
.. versionchanged:: 1.10
Added the ``get_pty`` kwarg.
"""
chan = self._transport.open_session(timeout=timeout)
if get_pty:
chan.get_pty()
chan.settimeout(timeout)
if environment:
chan.update_environment(environment)
chan.exec_command(command)
stdin = chan.makefile("wb", bufsize)
stdout = chan.makefile("r", bufsize)
stderr = chan.makefile_stderr("r", bufsize)
return stdin, stdout, stderr | [
"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 int bufsize:
interpreted the same way as by the built-in ``file()`` function in
Python
:param int timeout:
set command's channel timeout. See `.Channel.settimeout`
:param bool get_pty:
Request a pseudo-terminal from the server (default ``False``).
See `.Channel.get_pty`
:param dict environment:
a dict of shell environment variables, to be merged into the
default environment that the remote command executes within.
.. warning::
Servers may silently reject some environment variables; see the
warning in `.Channel.set_environment_variable` for details.
:return:
the stdin, stdout, and stderr of the executing command, as a
3-tuple
:raises: `.SSHException` -- if the server fails to execute the command
.. versionchanged:: 1.10
Added the ``get_pty`` kwarg. | [
"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 using the requested
terminal type and size.
:param str term:
the terminal type to emulate (for example, ``"vt100"``)
:param int width: the width (in characters) of the terminal window
:param int height: the height (in characters) of the terminal window
:param int width_pixels: the width (in pixels) of the terminal window
:param int height_pixels: the height (in pixels) of the terminal window
:param dict environment: the command's environment
:return: a new `.Channel` connected to the remote shell
:raises: `.SSHException` -- if the server fails to invoke a shell
"""
chan = self._transport.open_session()
chan.get_pty(term, width, height, width_pixels, height_pixels)
chan.invoke_shell()
return chan | 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 using the requested
terminal type and size.
:param str term:
the terminal type to emulate (for example, ``"vt100"``)
:param int width: the width (in characters) of the terminal window
:param int height: the height (in characters) of the terminal window
:param int width_pixels: the width (in pixels) of the terminal window
:param int height_pixels: the height (in pixels) of the terminal window
:param dict environment: the command's environment
:return: a new `.Channel` connected to the remote shell
:raises: `.SSHException` -- if the server fails to invoke a shell
"""
chan = self._transport.open_session()
chan.get_pty(term, width, height, width_pixels, height_pixels)
chan.invoke_shell()
return chan | [
"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 characters) of the terminal window
:param int height: the height (in characters) of the terminal window
:param int width_pixels: the width (in pixels) of the terminal window
:param int height_pixels: the height (in pixels) of the terminal window
:param dict environment: the command's environment
:return: a new `.Channel` connected to the remote shell
:raises: `.SSHException` -- if the server fails to invoke a shell | [
"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("Invalid value for `language`, must not be `None`") # noqa: E501
allowed_values = ["python", "r", "rmarkdown"] # noqa: E501
if language not in allowed_values:
raise ValueError(
"Invalid value for `language` ({0}), must be one of {1}" # noqa: E501
.format(language, allowed_values)
)
self._language = language | 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("Invalid value for `language`, must not be `None`") # noqa: E501
allowed_values = ["python", "r", "rmarkdown"] # noqa: E501
if language not in allowed_values:
raise ValueError(
"Invalid value for `language` ({0}), must be one of {1}" # noqa: E501
.format(language, allowed_values)
)
self._language = language | [
"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 kernel_type is None:
raise ValueError("Invalid value for `kernel_type`, must not be `None`") # noqa: E501
allowed_values = ["script", "notebook"] # noqa: E501
if kernel_type not in allowed_values:
raise ValueError(
"Invalid value for `kernel_type` ({0}), must be one of {1}" # noqa: E501
.format(kernel_type, allowed_values)
)
self._kernel_type = kernel_type | 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 kernel_type is None:
raise ValueError("Invalid value for `kernel_type`, must not be `None`") # noqa: E501
allowed_values = ["script", "notebook"] # noqa: E501
if kernel_type not in allowed_values:
raise ValueError(
"Invalid value for `kernel_type` ({0}), must be one of {1}" # noqa: E501
.format(kernel_type, allowed_values)
)
self._kernel_type = kernel_type | [
"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 unique namespace.
Parameters
==========
config_data: a partially loaded configuration dictionary (optional)
quiet: suppress verbose print of output (default is False)
"""
# Add all variables that start with KAGGLE_ to config data
if config_data is None:
config_data = {}
for key, val in os.environ.items():
if key.startswith('KAGGLE_'):
config_key = key.replace('KAGGLE_', '', 1).lower()
config_data[config_key] = val
return config_data | 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 unique namespace.
Parameters
==========
config_data: a partially loaded configuration dictionary (optional)
quiet: suppress verbose print of output (default is False)
"""
# Add all variables that start with KAGGLE_ to config data
if config_data is None:
config_data = {}
for key, val in os.environ.items():
if key.startswith('KAGGLE_'):
config_key = key.replace('KAGGLE_', '', 1).lower()
config_data[config_key] = val
return config_data | [
"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_data: a partially loaded configuration dictionary (optional)
quiet: suppress verbose print of output (default is 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",
"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
into self.config_values
"""
# Username and password are required.
for item in [self.CONFIG_NAME_USER, self.CONFIG_NAME_KEY]:
if item not in config_data:
raise ValueError('Error: Missing %s in configuration.' % item)
configuration = Configuration()
# Add to the final configuration (required)
configuration.username = config_data[self.CONFIG_NAME_USER]
configuration.password = config_data[self.CONFIG_NAME_KEY]
# Proxy
if self.CONFIG_NAME_PROXY in config_data:
configuration.proxy = config_data[self.CONFIG_NAME_PROXY]
# Cert File
if self.CONFIG_NAME_SSL_CA_CERT in config_data:
configuration.ssl_ca_cert = config_data[self.
CONFIG_NAME_SSL_CA_CERT]
# Keep config values with class instance, and load api client!
self.config_values = config_data
try:
self.api_client = ApiClient(configuration)
except Exception as error:
if 'Proxy' in type(error).__name__:
raise ValueError(
'The specified proxy ' +
config_data[self.CONFIG_NAME_PROXY] +
' is not valid, please check your proxy settings')
else:
raise ValueError(
'Unauthorized: you must download an API key or export '
'credentials to the environment. Please see\n ' +
'https://github.com/Kaggle/kaggle-api#api-credentials ' +
'for instructions.') | 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
into self.config_values
"""
# Username and password are required.
for item in [self.CONFIG_NAME_USER, self.CONFIG_NAME_KEY]:
if item not in config_data:
raise ValueError('Error: Missing %s in configuration.' % item)
configuration = Configuration()
# Add to the final configuration (required)
configuration.username = config_data[self.CONFIG_NAME_USER]
configuration.password = config_data[self.CONFIG_NAME_KEY]
# Proxy
if self.CONFIG_NAME_PROXY in config_data:
configuration.proxy = config_data[self.CONFIG_NAME_PROXY]
# Cert File
if self.CONFIG_NAME_SSL_CA_CERT in config_data:
configuration.ssl_ca_cert = config_data[self.
CONFIG_NAME_SSL_CA_CERT]
# Keep config values with class instance, and load api client!
self.config_values = config_data
try:
self.api_client = ApiClient(configuration)
except Exception as error:
if 'Proxy' in type(error).__name__:
raise ValueError(
'The specified proxy ' +
config_data[self.CONFIG_NAME_PROXY] +
' is not valid, please check your proxy settings')
else:
raise ValueError(
'Unauthorized: you must download an API key or export '
'credentials to the environment. Please see\n ' +
'https://github.com/Kaggle/kaggle-api#api-credentials ' +
'for instructions.') | [
"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
==========
config_data: the Configuration object to save a username and
password, if defined
quiet: suppress verbose print of output (default is False)
"""
if config_data is None:
config_data = {}
if os.path.exists(self.config):
try:
if os.name != 'nt':
permissions = os.stat(self.config).st_mode
if (permissions & 4) or (permissions & 32):
print(
'Warning: Your Kaggle API key is readable by other '
'users on this system! To fix this, you can run ' +
'\'chmod 600 {}\''.format(self.config))
with open(self.config) as f:
config_data = json.load(f)
except:
pass
else:
# Warn the user that configuration will be reliant on environment
if not quiet:
print('No Kaggle API config file found, will use environment.')
return config_data | 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
==========
config_data: the Configuration object to save a username and
password, if defined
quiet: suppress verbose print of output (default is False)
"""
if config_data is None:
config_data = {}
if os.path.exists(self.config):
try:
if os.name != 'nt':
permissions = os.stat(self.config).st_mode
if (permissions & 4) or (permissions & 32):
print(
'Warning: Your Kaggle API key is readable by other '
'users on this system! To fix this, you can run ' +
'\'chmod 600 {}\''.format(self.config))
with open(self.config) as f:
config_data = json.load(f)
except:
pass
else:
# Warn the user that configuration will be reliant on environment
if not quiet:
print('No Kaggle API config file found, will use environment.')
return config_data | [
"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
password, if defined
quiet: suppress verbose print of output (default is 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",
... | 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 json
"""
with open(self.config, 'w') as f:
json.dump(config_data, f, indent=indent) | 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 json
"""
with open(self.config, 'w') as f:
json.dump(config_data, f, indent=indent) | [
"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" in the config
path = self.get_config_value(self.CONFIG_NAME_PATH)
# If not set in config, default to present working directory
if path is None:
return os.getcwd()
return os.path.join(path, *subdirs) | 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" in the config
path = self.get_config_value(self.CONFIG_NAME_PATH)
# If not set in config, default to present working directory
if path is None:
return os.getcwd()
return os.path.join(path, *subdirs) | [
"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
separator: the separator to use (default is : )
"""
value_out = 'None'
if name in self.config_values and self.config_values[name] is not None:
value_out = self.config_values[name]
print(prefix + name + separator + value_out) | 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
separator: the separator to use (default is : )
"""
value_out = 'None'
if name in self.config_values and self.config_values[name] is not None:
value_out = self.config_values[name]
print(prefix + name + separator + value_out) | [
"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 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, see valid_sort_by for options
category: category to filter result to
group: group to filter result to
"""
valid_groups = ['general', 'entered', 'inClass']
if group and group not in valid_groups:
raise ValueError('Invalid group specified. Valid options are ' +
str(valid_groups))
valid_categories = [
'all', 'featured', 'research', 'recruitment', 'gettingStarted',
'masters', 'playground'
]
if category and category not in valid_categories:
raise ValueError('Invalid category specified. Valid options are ' +
str(valid_categories))
valid_sort_by = [
'grouped', 'prize', 'earliestDeadline', 'latestDeadline',
'numberOfTeams', 'recentlyCreated'
]
if sort_by and sort_by not in valid_sort_by:
raise ValueError('Invalid sort_by specified. Valid options are ' +
str(valid_sort_by))
competitions_list_result = self.process_response(
self.competitions_list_with_http_info(
group=group or '',
category=category or '',
sort_by=sort_by or '',
page=page,
search=search or ''))
return [Competition(c) for c in competitions_list_result] | 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 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, see valid_sort_by for options
category: category to filter result to
group: group to filter result to
"""
valid_groups = ['general', 'entered', 'inClass']
if group and group not in valid_groups:
raise ValueError('Invalid group specified. Valid options are ' +
str(valid_groups))
valid_categories = [
'all', 'featured', 'research', 'recruitment', 'gettingStarted',
'masters', 'playground'
]
if category and category not in valid_categories:
raise ValueError('Invalid category specified. Valid options are ' +
str(valid_categories))
valid_sort_by = [
'grouped', 'prize', 'earliestDeadline', 'latestDeadline',
'numberOfTeams', 'recentlyCreated'
]
if sort_by and sort_by not in valid_sort_by:
raise ValueError('Invalid sort_by specified. Valid options are ' +
str(valid_sort_by))
competitions_list_result = self.process_response(
self.competitions_list_with_http_info(
group=group or '',
category=category or '',
sort_by=sort_by or '',
page=page,
search=search or ''))
return [Competition(c) for c in competitions_list_result] | [
"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, see valid_sort_by for options
category: category to filter result to
group: group to filter result to | [
"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 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)
search: a search term to use (default is empty string)
csv_display: if True, print comma separated values
"""
competitions = self.competitions_list(
group=group,
category=category,
sort_by=sort_by,
page=page,
search=search)
fields = [
'ref', 'deadline', 'category', 'reward', 'teamCount',
'userHasEntered'
]
if competitions:
if csv_display:
self.print_csv(competitions, fields)
else:
self.print_table(competitions, fields)
else:
print('No competitions found') | python | def competitions_list_cli(self,
group=None,
category=None,
sort_by=None,
page=1,
search=None,
csv_display=False):
""" 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)
search: a search term to use (default is empty string)
csv_display: if True, print comma separated values
"""
competitions = self.competitions_list(
group=group,
category=category,
sort_by=sort_by,
page=page,
search=search)
fields = [
'ref', 'deadline', 'category', 'reward', 'teamCount',
'userHasEntered'
]
if competitions:
if csv_display:
self.print_csv(competitions, fields)
else:
self.print_table(competitions, fields)
else:
print('No competitions found') | [
"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)
search: a search term to use (default is empty string)
csv_display: if True, print comma separated values | [
"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
quiet: suppress verbose output (default is False)
"""
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
url_result = self.process_response(
self.competitions_submissions_url_with_http_info(
id=competition,
file_name=os.path.basename(file_name),
content_length=os.path.getsize(file_name),
last_modified_date_utc=int(os.path.getmtime(file_name))))
# Temporary while new worker is gradually turned on. 'isComplete'
# exists on the old DTO but not the new, so this is an hacky but
# easy solution to figure out which submission logic to use
if 'isComplete' in url_result:
# Old submissions path
url_result_list = url_result['createUrl'].split('/')
upload_result = self.process_response(
self.competitions_submissions_upload_with_http_info(
file=file_name,
guid=url_result_list[-3],
content_length=url_result_list[-2],
last_modified_date_utc=url_result_list[-1]))
upload_result_token = upload_result['token']
else:
# New submissions path!
success = self.upload_complete(file_name,
url_result['createUrl'], quiet)
if not success:
# Actual error is printed during upload_complete. Not
# ideal but changing would not be backwards compatible
return "Could not submit to competition"
upload_result_token = url_result['token']
submit_result = self.process_response(
self.competitions_submissions_submit_with_http_info(
id=competition,
blob_file_tokens=upload_result_token,
submission_description=message))
return SubmitResult(submit_result) | 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
quiet: suppress verbose output (default is False)
"""
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
url_result = self.process_response(
self.competitions_submissions_url_with_http_info(
id=competition,
file_name=os.path.basename(file_name),
content_length=os.path.getsize(file_name),
last_modified_date_utc=int(os.path.getmtime(file_name))))
# Temporary while new worker is gradually turned on. 'isComplete'
# exists on the old DTO but not the new, so this is an hacky but
# easy solution to figure out which submission logic to use
if 'isComplete' in url_result:
# Old submissions path
url_result_list = url_result['createUrl'].split('/')
upload_result = self.process_response(
self.competitions_submissions_upload_with_http_info(
file=file_name,
guid=url_result_list[-3],
content_length=url_result_list[-2],
last_modified_date_utc=url_result_list[-1]))
upload_result_token = upload_result['token']
else:
# New submissions path!
success = self.upload_complete(file_name,
url_result['createUrl'], quiet)
if not success:
# Actual error is printed during upload_complete. Not
# ideal but changing would not be backwards compatible
return "Could not submit to competition"
upload_result_token = url_result['token']
submit_result = self.process_response(
self.competitions_submissions_submit_with_http_info(
id=competition,
blob_file_tokens=upload_result_token,
submission_description=message))
return SubmitResult(submit_result) | [
"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_submissions_list_with_http_info(id=competition))
return [Submission(s) for s in submissions_result] | 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_submissions_list_with_http_info(id=competition))
return [Submission(s) for s in submissions_result] | [
"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 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
competition_opt: an alternative competition option provided by cli
csv_display: if True, print comma separated values
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
submissions = self.competition_submissions(competition)
fields = [
'fileName', 'date', 'description', 'status', 'publicScore',
'privateScore'
]
if submissions:
if csv_display:
self.print_csv(submissions, fields)
else:
self.print_table(submissions, fields)
else:
print('No submissions found') | python | def competition_submissions_cli(self,
competition=None,
competition_opt=None,
csv_display=False,
quiet=False):
""" 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
competition_opt: an alternative competition option provided by cli
csv_display: if True, print comma separated values
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
submissions = self.competition_submissions(competition)
fields = [
'fileName', 'date', 'description', 'status', 'publicScore',
'privateScore'
]
if submissions:
if csv_display:
self.print_csv(submissions, fields)
else:
self.print_table(submissions, fields)
else:
print('No submissions found') | [
"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
competition_opt: an alternative competition option provided by cli
csv_display: if True, print comma separated values
quiet: suppress verbose output (default is False) | [
"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
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
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
files = self.competition_list_files(competition)
fields = ['name', 'size', 'creationDate']
if files:
if csv_display:
self.print_csv(files, fields)
else:
self.print_table(files, fields)
else:
print('No files found') | python | def competition_list_files_cli(self,
competition,
competition_opt=None,
csv_display=False,
quiet=False):
""" 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
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
files = self.competition_list_files(competition)
fields = ['name', 'size', 'creationDate']
if files:
if csv_display:
self.print_csv(files, fields)
else:
self.print_table(files, fields)
else:
print('No files found') | [
"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
quiet: suppress verbose output (default is False) | [
"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 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 download if the file already exists (default False)
quiet: suppress verbose output (default is False)
"""
if path is None:
effective_path = self.get_default_download_dir(
'competitions', competition)
else:
effective_path = path
response = self.process_response(
self.competitions_data_download_file_with_http_info(
id=competition, file_name=file_name, _preload_content=False))
url = response.retries.history[0].redirect_location.split('?')[0]
outfile = os.path.join(effective_path, url.split('/')[-1])
if force or self.download_needed(response, outfile, quiet):
self.download_file(response, outfile, quiet) | python | def competition_download_file(self,
competition,
file_name,
path=None,
force=False,
quiet=False):
""" 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 download if the file already exists (default False)
quiet: suppress verbose output (default is False)
"""
if path is None:
effective_path = self.get_default_download_dir(
'competitions', competition)
else:
effective_path = path
response = self.process_response(
self.competitions_data_download_file_with_http_info(
id=competition, file_name=file_name, _preload_content=False))
url = response.retries.history[0].redirect_location.split('?')[0]
outfile = os.path.join(effective_path, url.split('/')[-1])
if force or self.download_needed(response, outfile, quiet):
self.download_file(response, outfile, quiet) | [
"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 download if the file already exists (default False)
quiet: suppress verbose output (default is False) | [
"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
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)
quiet: suppress verbose output (default is True)
"""
files = self.competition_list_files(competition)
if not files:
print('This competition does not have any available data files')
for file_name in files:
self.competition_download_file(competition, file_name.ref, path,
force, quiet) | python | def competition_download_files(self,
competition,
path=None,
force=False,
quiet=True):
""" 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)
quiet: suppress verbose output (default is True)
"""
files = self.competition_list_files(competition)
if not files:
print('This competition does not have any available data files')
for file_name in files:
self.competition_download_file(competition, file_name.ref, path,
force, quiet) | [
"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)
quiet: suppress verbose output (default is True) | [
"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):
""" 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 alternative competition option provided by cli
file_name: the configuration file name
path: a path to download the file to
force: force the download if the file already exists (default False)
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
if file_name is None:
self.competition_download_files(competition, path, force,
quiet)
else:
self.competition_download_file(competition, file_name, path,
force, quiet) | python | def competition_download_cli(self,
competition,
competition_opt=None,
file_name=None,
path=None,
force=False,
quiet=False):
""" 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 alternative competition option provided by cli
file_name: the configuration file name
path: a path to download the file to
force: force the download if the file already exists (default False)
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
else:
if file_name is None:
self.competition_download_files(competition, path, force,
quiet)
else:
self.competition_download_file(competition, file_name, path,
force, quiet) | [
"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 alternative competition option provided by cli
file_name: the configuration file name
path: a path to download the file to
force: force the download if the file already exists (default False)
quiet: suppress verbose output (default is False) | [
"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 is True)
"""
response = self.process_response(
self.competition_download_leaderboard_with_http_info(
competition, _preload_content=False))
if path is None:
effective_path = self.get_default_download_dir(
'competitions', competition)
else:
effective_path = path
file_name = competition + '.zip'
outfile = os.path.join(effective_path, file_name)
self.download_file(response, outfile, quiet) | 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 is True)
"""
response = self.process_response(
self.competition_download_leaderboard_with_http_info(
competition, _preload_content=False))
if path is None:
effective_path = self.get_default_download_dir(
'competitions', competition)
else:
effective_path = path
file_name = competition + '.zip'
outfile = os.path.join(effective_path, file_name)
self.download_file(response, outfile, quiet) | [
"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_leaderboard_with_http_info(competition))
return [LeaderboardEntry(e) for e in result['submissions']] | 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_leaderboard_with_http_info(competition))
return [LeaderboardEntry(e) for e in result['submissions']] | [
"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,
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
path: a path to download to, if download is True
view: if True, show the results in the terminal as csv or table
download: if True, download the entire leaderboard
csv_display: if True, print comma separated values instead of table
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if not view and not download:
raise ValueError('Either --show or --download must be specified')
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
if download:
self.competition_leaderboard_download(competition, path, quiet)
if view:
results = self.competition_leaderboard_view(competition)
fields = ['teamId', 'teamName', 'submissionDate', 'score']
if results:
if csv_display:
self.print_csv(results, fields)
else:
self.print_table(results, fields)
else:
print('No results found') | python | 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
path: a path to download to, if download is True
view: if True, show the results in the terminal as csv or table
download: if True, download the entire leaderboard
csv_display: if True, print comma separated values instead of table
quiet: suppress verbose output (default is False)
"""
competition = competition or competition_opt
if not view and not download:
raise ValueError('Either --show or --download must be specified')
if competition is None:
competition = self.get_config_value(self.CONFIG_NAME_COMPETITION)
if competition is not None and not quiet:
print('Using competition: ' + competition)
if competition is None:
raise ValueError('No competition specified')
if download:
self.competition_leaderboard_download(competition, path, quiet)
if view:
results = self.competition_leaderboard_view(competition)
fields = ['teamId', 'teamName', 'submissionDate', 'score']
if results:
if csv_display:
self.print_csv(results, fields)
else:
self.print_table(results, fields)
else:
print('No results found') | [
"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
path: a path to download to, if download is True
view: if True, show the results in the terminal as csv or table
download: if True, download the entire leaderboard
csv_display: if True, print comma separated values instead of table
quiet: suppress verbose output (default is False) | [
"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,
page=1):
""" 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
license_name: string descriptor for license, see valid_license_names
tag_ids: tag identifiers to filter the search
search: a search term to use (default is empty string)
user: username to filter the search to
mine: boolean if True, group is changed to "my" to return personal
page: the page to return (default is 1)
"""
valid_sort_bys = ['hottest', 'votes', 'updated', 'active', 'published']
if sort_by and sort_by not in valid_sort_bys:
raise ValueError('Invalid sort by specified. Valid options are ' +
str(valid_sort_bys))
valid_sizes = ['all', 'small', 'medium', 'large']
if size and size not in valid_sizes:
raise ValueError('Invalid size specified. Valid options are ' +
str(valid_sizes))
valid_file_types = ['all', 'csv', 'sqlite', 'json', 'bigQuery']
if file_type and file_type not in valid_file_types:
raise ValueError('Invalid file type specified. Valid options are '
+ str(valid_file_types))
valid_license_names = ['all', 'cc', 'gpl', 'odb', 'other']
if license_name and license_name not in valid_license_names:
raise ValueError('Invalid license specified. Valid options are ' +
str(valid_license_names))
if int(page) <= 0:
raise ValueError('Page number must be >= 1')
group = 'public'
if mine:
group = 'my'
if user:
raise ValueError('Cannot specify both mine and a user')
if user:
group = 'user'
datasets_list_result = self.process_response(
self.datasets_list_with_http_info(
group=group,
sort_by=sort_by or 'hottest',
size=size or 'all',
filetype=file_type or 'all',
license=license_name or 'all',
tagids=tag_ids or '',
search=search or '',
user=user or '',
page=page))
return [Dataset(d) for d in datasets_list_result] | 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,
page=1):
""" 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
license_name: string descriptor for license, see valid_license_names
tag_ids: tag identifiers to filter the search
search: a search term to use (default is empty string)
user: username to filter the search to
mine: boolean if True, group is changed to "my" to return personal
page: the page to return (default is 1)
"""
valid_sort_bys = ['hottest', 'votes', 'updated', 'active', 'published']
if sort_by and sort_by not in valid_sort_bys:
raise ValueError('Invalid sort by specified. Valid options are ' +
str(valid_sort_bys))
valid_sizes = ['all', 'small', 'medium', 'large']
if size and size not in valid_sizes:
raise ValueError('Invalid size specified. Valid options are ' +
str(valid_sizes))
valid_file_types = ['all', 'csv', 'sqlite', 'json', 'bigQuery']
if file_type and file_type not in valid_file_types:
raise ValueError('Invalid file type specified. Valid options are '
+ str(valid_file_types))
valid_license_names = ['all', 'cc', 'gpl', 'odb', 'other']
if license_name and license_name not in valid_license_names:
raise ValueError('Invalid license specified. Valid options are ' +
str(valid_license_names))
if int(page) <= 0:
raise ValueError('Page number must be >= 1')
group = 'public'
if mine:
group = 'my'
if user:
raise ValueError('Cannot specify both mine and a user')
if user:
group = 'user'
datasets_list_result = self.process_response(
self.datasets_list_with_http_info(
group=group,
sort_by=sort_by or 'hottest',
size=size or 'all',
filetype=file_type or 'all',
license=license_name or 'all',
tagids=tag_ids or '',
search=search or '',
user=user or '',
page=page))
return [Dataset(d) for d in datasets_list_result] | [
"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
license_name: string descriptor for license, see valid_license_names
tag_ids: tag identifiers to filter the search
search: a search term to use (default is empty string)
user: username to filter the search to
mine: boolean if True, group is changed to "my" to return personal
page: the page to return (default is 1) | [
"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,
mine=False,
page=1,
csv_display=False):
""" 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 options
file_type: the format, see valid_file_types for string options
license_name: string descriptor for license, see valid_license_names
tag_ids: tag identifiers to filter the search
search: a search term to use (default is empty string)
user: username to filter the search to
mine: boolean if True, group is changed to "my" to return personal
page: the page to return (default is 1)
csv_display: if True, print comma separated values instead of table
"""
datasets = self.dataset_list(sort_by, size, file_type, license_name,
tag_ids, search, user, mine, page)
fields = ['ref', 'title', 'size', 'lastUpdated', 'downloadCount']
if datasets:
if csv_display:
self.print_csv(datasets, fields)
else:
self.print_table(datasets, fields)
else:
print('No datasets found') | python | def dataset_list_cli(self,
sort_by=None,
size=None,
file_type=None,
license_name=None,
tag_ids=None,
search=None,
user=None,
mine=False,
page=1,
csv_display=False):
""" 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 options
file_type: the format, see valid_file_types for string options
license_name: string descriptor for license, see valid_license_names
tag_ids: tag identifiers to filter the search
search: a search term to use (default is empty string)
user: username to filter the search to
mine: boolean if True, group is changed to "my" to return personal
page: the page to return (default is 1)
csv_display: if True, print comma separated values instead of table
"""
datasets = self.dataset_list(sort_by, size, file_type, license_name,
tag_ids, search, user, mine, page)
fields = ['ref', 'title', 'size', 'lastUpdated', 'downloadCount']
if datasets:
if csv_display:
self.print_csv(datasets, fields)
else:
self.print_table(datasets, fields)
else:
print('No datasets found') | [
"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 options
file_type: the format, see valid_file_types for string options
license_name: string descriptor for license, see valid_license_names
tag_ids: tag identifiers to filter the search
search: a search term to use (default is empty string)
user: username to filter the search to
mine: boolean if True, group is changed to "my" to return personal
page: the page to return (default is 1)
csv_display: if True, print comma separated values instead of table | [
"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_string(dataset)
dataset_urls = dataset.split('/')
owner_slug = dataset_urls[0]
dataset_slug = dataset_urls[1]
else:
owner_slug = self.get_config_value(self.CONFIG_NAME_USER)
dataset_slug = dataset
result = self.process_response(
self.datasets_view_with_http_info(owner_slug, dataset_slug))
return Dataset(result) | 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_string(dataset)
dataset_urls = dataset.split('/')
owner_slug = dataset_urls[0]
dataset_slug = dataset_urls[1]
else:
owner_slug = self.get_config_value(self.CONFIG_NAME_USER)
dataset_slug = dataset
result = self.process_response(
self.datasets_view_with_http_info(owner_slug, dataset_slug))
return Dataset(result) | [
"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
==========
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
force: force the download if the file already exists (default False)
quiet: suppress verbose output (default is True)
"""
if '/' in dataset:
self.validate_dataset_string(dataset)
dataset_urls = dataset.split('/')
owner_slug = dataset_urls[0]
dataset_slug = dataset_urls[1]
else:
owner_slug = self.get_config_value(self.CONFIG_NAME_USER)
dataset_slug = dataset
if path is None:
effective_path = self.get_default_download_dir(
'datasets', owner_slug, dataset_slug)
else:
effective_path = path
response = self.process_response(
self.datasets_download_file_with_http_info(
owner_slug=owner_slug,
dataset_slug=dataset_slug,
file_name=file_name,
_preload_content=False))
url = response.retries.history[0].redirect_location.split('?')[0]
outfile = os.path.join(effective_path, url.split('/')[-1])
if force or self.download_needed(response, outfile, quiet):
self.download_file(response, outfile, quiet)
return True
else:
return False | python | def dataset_download_file(self,
dataset,
file_name,
path=None,
force=False,
quiet=True):
""" 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
force: force the download if the file already exists (default False)
quiet: suppress verbose output (default is True)
"""
if '/' in dataset:
self.validate_dataset_string(dataset)
dataset_urls = dataset.split('/')
owner_slug = dataset_urls[0]
dataset_slug = dataset_urls[1]
else:
owner_slug = self.get_config_value(self.CONFIG_NAME_USER)
dataset_slug = dataset
if path is None:
effective_path = self.get_default_download_dir(
'datasets', owner_slug, dataset_slug)
else:
effective_path = path
response = self.process_response(
self.datasets_download_file_with_http_info(
owner_slug=owner_slug,
dataset_slug=dataset_slug,
file_name=file_name,
_preload_content=False))
url = response.retries.history[0].redirect_location.split('?')[0]
outfile = os.path.join(effective_path, url.split('/')[-1])
if force or self.download_needed(response, outfile, quiet):
self.download_file(response, outfile, quiet)
return True
else:
return False | [
"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
force: force the download if the file already exists (default False)
quiet: suppress verbose output (default is True) | [
"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
==========
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 (default False)
quiet: suppress verbose output (default is True)
unzip: if True, unzip files upon download (default is False)
"""
if dataset is None:
raise ValueError('A dataset must be specified')
if '/' in dataset:
self.validate_dataset_string(dataset)
dataset_urls = dataset.split('/')
owner_slug = dataset_urls[0]
dataset_slug = dataset_urls[1]
else:
owner_slug = self.get_config_value(self.CONFIG_NAME_USER)
dataset_slug = dataset
if path is None:
effective_path = self.get_default_download_dir(
'datasets', owner_slug, dataset_slug)
else:
effective_path = path
response = self.process_response(
self.datasets_download_with_http_info(
owner_slug=owner_slug,
dataset_slug=dataset_slug,
_preload_content=False))
outfile = os.path.join(effective_path, dataset_slug + '.zip')
if force or self.download_needed(response, outfile, quiet):
self.download_file(response, outfile, quiet)
downloaded = True
else:
downloaded = False
if downloaded:
outfile = os.path.join(effective_path, dataset_slug + '.zip')
if unzip:
try:
with zipfile.ZipFile(outfile) as z:
z.extractall(effective_path)
except zipfile.BadZipFile as e:
raise ValueError(
'Bad zip file, please report on '
'www.github.com/kaggle/kaggle-api', e)
try:
os.remove(outfile)
except OSError as e:
print('Could not delete zip file, got %s' % e) | python | def dataset_download_files(self,
dataset,
path=None,
force=False,
quiet=True,
unzip=False):
""" 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 (default False)
quiet: suppress verbose output (default is True)
unzip: if True, unzip files upon download (default is False)
"""
if dataset is None:
raise ValueError('A dataset must be specified')
if '/' in dataset:
self.validate_dataset_string(dataset)
dataset_urls = dataset.split('/')
owner_slug = dataset_urls[0]
dataset_slug = dataset_urls[1]
else:
owner_slug = self.get_config_value(self.CONFIG_NAME_USER)
dataset_slug = dataset
if path is None:
effective_path = self.get_default_download_dir(
'datasets', owner_slug, dataset_slug)
else:
effective_path = path
response = self.process_response(
self.datasets_download_with_http_info(
owner_slug=owner_slug,
dataset_slug=dataset_slug,
_preload_content=False))
outfile = os.path.join(effective_path, dataset_slug + '.zip')
if force or self.download_needed(response, outfile, quiet):
self.download_file(response, outfile, quiet)
downloaded = True
else:
downloaded = False
if downloaded:
outfile = os.path.join(effective_path, dataset_slug + '.zip')
if unzip:
try:
with zipfile.ZipFile(outfile) as z:
z.extractall(effective_path)
except zipfile.BadZipFile as e:
raise ValueError(
'Bad zip file, please report on '
'www.github.com/kaggle/kaggle-api', e)
try:
os.remove(outfile)
except OSError as e:
print('Could not delete zip file, got %s' % e) | [
"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 (default False)
quiet: suppress verbose output (default is True)
unzip: if True, unzip files upon download (default is False) | [
"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.getsize(path)
last_modified_date_utc = int(os.path.getmtime(path))
result = FileUploadInfo(
self.process_response(
self.datasets_upload_file_with_http_info(
file_name, content_length, last_modified_date_utc)))
success = self.upload_complete(path, result.createUrl, quiet)
if success:
return result.token
return None | 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.getsize(path)
last_modified_date_utc = int(os.path.getmtime(path))
result = FileUploadInfo(
self.process_response(
self.datasets_upload_file_with_http_info(
file_name, content_length, last_modified_date_utc)))
success = self.upload_complete(path, result.createUrl, quiet)
if success:
return result.token
return None | [
"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'):
""" 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 should be converted to csv
delete_old_versions: if True, do that (default False)
dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload
"""
if not os.path.isdir(folder):
raise ValueError('Invalid folder: ' + folder)
meta_file = self.get_dataset_metadata_file(folder)
# read json
with open(meta_file) as f:
meta_data = json.load(f)
ref = self.get_or_default(meta_data, 'id', None)
id_no = self.get_or_default(meta_data, 'id_no', None)
if not ref and not id_no:
raise ValueError('ID or slug must be specified in the metadata')
subtitle = meta_data.get('subtitle')
if subtitle and (len(subtitle) < 20 or len(subtitle) > 80):
raise ValueError(
'Subtitle length must be between 20 and 80 characters')
resources = meta_data.get('resources')
if resources:
self.validate_resources(folder, resources)
description = meta_data.get('description')
keywords = self.get_or_default(meta_data, 'keywords', [])
request = DatasetNewVersionRequest(
version_notes=version_notes,
subtitle=subtitle,
description=description,
files=[],
convert_to_csv=convert_to_csv,
category_ids=keywords,
delete_old_versions=delete_old_versions)
self.upload_files(request, resources, folder, quiet, dir_mode)
if id_no:
result = DatasetNewVersionResponse(
self.process_response(
self.datasets_create_version_by_id_with_http_info(
id_no, request)))
else:
if ref == self.config_values[
self.CONFIG_NAME_USER] + '/INSERT_SLUG_HERE':
raise ValueError(
'Default slug detected, please change values before '
'uploading')
self.validate_dataset_string(ref)
ref_list = ref.split('/')
owner_slug = ref_list[0]
dataset_slug = ref_list[1]
result = DatasetNewVersionResponse(
self.process_response(
self.datasets_create_version_with_http_info(
owner_slug, dataset_slug, request)))
return result | python | def dataset_create_version(self,
folder,
version_notes,
quiet=False,
convert_to_csv=True,
delete_old_versions=False,
dir_mode='skip'):
""" 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 should be converted to csv
delete_old_versions: if True, do that (default False)
dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload
"""
if not os.path.isdir(folder):
raise ValueError('Invalid folder: ' + folder)
meta_file = self.get_dataset_metadata_file(folder)
# read json
with open(meta_file) as f:
meta_data = json.load(f)
ref = self.get_or_default(meta_data, 'id', None)
id_no = self.get_or_default(meta_data, 'id_no', None)
if not ref and not id_no:
raise ValueError('ID or slug must be specified in the metadata')
subtitle = meta_data.get('subtitle')
if subtitle and (len(subtitle) < 20 or len(subtitle) > 80):
raise ValueError(
'Subtitle length must be between 20 and 80 characters')
resources = meta_data.get('resources')
if resources:
self.validate_resources(folder, resources)
description = meta_data.get('description')
keywords = self.get_or_default(meta_data, 'keywords', [])
request = DatasetNewVersionRequest(
version_notes=version_notes,
subtitle=subtitle,
description=description,
files=[],
convert_to_csv=convert_to_csv,
category_ids=keywords,
delete_old_versions=delete_old_versions)
self.upload_files(request, resources, folder, quiet, dir_mode)
if id_no:
result = DatasetNewVersionResponse(
self.process_response(
self.datasets_create_version_by_id_with_http_info(
id_no, request)))
else:
if ref == self.config_values[
self.CONFIG_NAME_USER] + '/INSERT_SLUG_HERE':
raise ValueError(
'Default slug detected, please change values before '
'uploading')
self.validate_dataset_string(ref)
ref_list = ref.split('/')
owner_slug = ref_list[0]
dataset_slug = ref_list[1]
result = DatasetNewVersionResponse(
self.process_response(
self.datasets_create_version_with_http_info(
owner_slug, dataset_slug, request)))
return result | [
"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 should be converted to csv
delete_old_versions: if True, do that (default False)
dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload | [
"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 verbose output (default is True)
chunk_size: the size of the chunk to stream
"""
outpath = os.path.dirname(outfile)
if not os.path.exists(outpath):
os.makedirs(outpath)
size = int(response.headers['Content-Length'])
size_read = 0
if not quiet:
print('Downloading ' + os.path.basename(outfile) + ' to ' +
outpath)
with tqdm(
total=size,
unit='B',
unit_scale=True,
unit_divisor=1024,
disable=quiet) as pbar:
with open(outfile, 'wb') as out:
while True:
data = response.read(chunk_size)
if not data:
break
out.write(data)
size_read = min(size, size_read + chunk_size)
pbar.update(len(data))
if not quiet:
print('\n', end='') | 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 verbose output (default is True)
chunk_size: the size of the chunk to stream
"""
outpath = os.path.dirname(outfile)
if not os.path.exists(outpath):
os.makedirs(outpath)
size = int(response.headers['Content-Length'])
size_read = 0
if not quiet:
print('Downloading ' + os.path.basename(outfile) + ' to ' +
outpath)
with tqdm(
total=size,
unit='B',
unit_scale=True,
unit_divisor=1024,
disable=quiet) as pbar:
with open(outfile, 'wb') as out:
while True:
data = response.read(chunk_size)
if not data:
break
out.write(data)
size_read = min(size, size_read + chunk_size)
pbar.update(len(data))
if not quiet:
print('\n', end='') | [
"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,
language=None,
kernel_type=None,
output_type=None,
sort_by=None):
""" 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, filter to this competition (default None)
parent_kernel: if defined, filter to those with specified parent
search: a custom search string to pass to the list query
mine: if true, group is specified as "my" to return personal kernels
user: filter results to a specific user
language: the programming language of the kernel
kernel_type: the type of kernel, one of valid_kernel_types (str)
output_type: the output type, one of valid_output_types (str)
sort_by: if defined, sort results by this string (valid_sort_by)
"""
if int(page) <= 0:
raise ValueError('Page number must be >= 1')
page_size = int(page_size)
if page_size <= 0:
raise ValueError('Page size must be >= 1')
if page_size > 100:
page_size = 100
valid_languages = ['all', 'python', 'r', 'sqlite', 'julia']
if language and language not in valid_languages:
raise ValueError('Invalid language specified. Valid options are ' +
str(valid_languages))
valid_kernel_types = ['all', 'script', 'notebook']
if kernel_type and kernel_type not in valid_kernel_types:
raise ValueError(
'Invalid kernel type specified. Valid options are ' +
str(valid_kernel_types))
valid_output_types = ['all', 'visualization', 'data']
if output_type and output_type not in valid_output_types:
raise ValueError(
'Invalid output type specified. Valid options are ' +
str(valid_output_types))
valid_sort_by = [
'hotness', 'commentCount', 'dateCreated', 'dateRun', 'relevance',
'scoreAscending', 'scoreDescending', 'viewCount', 'voteCount'
]
if sort_by and sort_by not in valid_sort_by:
raise ValueError(
'Invalid sort by type specified. Valid options are ' +
str(valid_sort_by))
if sort_by == 'relevance' and search == '':
raise ValueError('Cannot sort by relevance without a search term.')
self.validate_dataset_string(dataset)
self.validate_kernel_string(parent_kernel)
group = 'everyone'
if mine:
group = 'profile'
kernels_list_result = self.process_response(
self.kernels_list_with_http_info(
page=page,
page_size=page_size,
group=group,
user=user or '',
language=language or 'all',
kernel_type=kernel_type or 'all',
output_type=output_type or 'all',
sort_by=sort_by or 'hotness',
dataset=dataset or '',
competition=competition or '',
parent_kernel=parent_kernel or '',
search=search or ''))
return [Kernel(k) for k in kernels_list_result] | python | def kernels_list(self,
page=1,
page_size=20,
dataset=None,
competition=None,
parent_kernel=None,
search=None,
mine=False,
user=None,
language=None,
kernel_type=None,
output_type=None,
sort_by=None):
""" 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, filter to this competition (default None)
parent_kernel: if defined, filter to those with specified parent
search: a custom search string to pass to the list query
mine: if true, group is specified as "my" to return personal kernels
user: filter results to a specific user
language: the programming language of the kernel
kernel_type: the type of kernel, one of valid_kernel_types (str)
output_type: the output type, one of valid_output_types (str)
sort_by: if defined, sort results by this string (valid_sort_by)
"""
if int(page) <= 0:
raise ValueError('Page number must be >= 1')
page_size = int(page_size)
if page_size <= 0:
raise ValueError('Page size must be >= 1')
if page_size > 100:
page_size = 100
valid_languages = ['all', 'python', 'r', 'sqlite', 'julia']
if language and language not in valid_languages:
raise ValueError('Invalid language specified. Valid options are ' +
str(valid_languages))
valid_kernel_types = ['all', 'script', 'notebook']
if kernel_type and kernel_type not in valid_kernel_types:
raise ValueError(
'Invalid kernel type specified. Valid options are ' +
str(valid_kernel_types))
valid_output_types = ['all', 'visualization', 'data']
if output_type and output_type not in valid_output_types:
raise ValueError(
'Invalid output type specified. Valid options are ' +
str(valid_output_types))
valid_sort_by = [
'hotness', 'commentCount', 'dateCreated', 'dateRun', 'relevance',
'scoreAscending', 'scoreDescending', 'viewCount', 'voteCount'
]
if sort_by and sort_by not in valid_sort_by:
raise ValueError(
'Invalid sort by type specified. Valid options are ' +
str(valid_sort_by))
if sort_by == 'relevance' and search == '':
raise ValueError('Cannot sort by relevance without a search term.')
self.validate_dataset_string(dataset)
self.validate_kernel_string(parent_kernel)
group = 'everyone'
if mine:
group = 'profile'
kernels_list_result = self.process_response(
self.kernels_list_with_http_info(
page=page,
page_size=page_size,
group=group,
user=user or '',
language=language or 'all',
kernel_type=kernel_type or 'all',
output_type=output_type or 'all',
sort_by=sort_by or 'hotness',
dataset=dataset or '',
competition=competition or '',
parent_kernel=parent_kernel or '',
search=search or ''))
return [Kernel(k) for k in kernels_list_result] | [
"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, filter to this competition (default None)
parent_kernel: if defined, filter to those with specified parent
search: a custom search string to pass to the list query
mine: if true, group is specified as "my" to return personal kernels
user: filter results to a specific user
language: the programming language of the kernel
kernel_type: the type of kernel, one of valid_kernel_types (str)
output_type: the output type, one of valid_output_types (str)
sort_by: if defined, sort results by this string (valid_sort_by) | [
"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:
if result.invalidTags:
print(
'The following are not valid tags and could not be added '
'to the kernel: ' + str(result.invalidTags))
if result.invalidDatasetSources:
print(
'The following are not valid dataset sources and could not '
'be added to the kernel: ' +
str(result.invalidDatasetSources))
if result.invalidCompetitionSources:
print(
'The following are not valid competition sources and could '
'not be added to the kernel: ' +
str(result.invalidCompetitionSources))
if result.invalidKernelSources:
print(
'The following are not valid kernel sources and could not '
'be added to the kernel: ' +
str(result.invalidKernelSources))
if result.versionNumber:
print('Kernel version %s successfully pushed. Please check '
'progress at %s' % (result.versionNumber, result.url))
else:
# Shouldn't happen but didn't test exhaustively
print('Kernel version successfully pushed. Please check '
'progress at %s' % result.url)
else:
print('Kernel push error: ' + 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:
if result.invalidTags:
print(
'The following are not valid tags and could not be added '
'to the kernel: ' + str(result.invalidTags))
if result.invalidDatasetSources:
print(
'The following are not valid dataset sources and could not '
'be added to the kernel: ' +
str(result.invalidDatasetSources))
if result.invalidCompetitionSources:
print(
'The following are not valid competition sources and could '
'not be added to the kernel: ' +
str(result.invalidCompetitionSources))
if result.invalidKernelSources:
print(
'The following are not valid kernel sources and could not '
'be added to the kernel: ' +
str(result.invalidKernelSources))
if result.versionNumber:
print('Kernel version %s successfully pushed. Please check '
'progress at %s' % (result.versionNumber, result.url))
else:
# Shouldn't happen but didn't test exhaustively
print('Kernel version successfully pushed. Please check '
'progress at %s' % result.url)
else:
print('Kernel push error: ' + 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(
kernel, path=path, metadata=metadata, quiet=False)
if metadata:
print('Source code and metadata downloaded to ' + effective_path)
else:
print('Source code downloaded to ' + effective_path) | 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(
kernel, path=path, metadata=metadata, quiet=False)
if metadata:
print('Source code and metadata downloaded to ' + effective_path)
else:
print('Source code downloaded to ' + effective_path) | [
"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 in fields:
length = max(
len(f), max([len(self.string(getattr(i, f))) for i in items]))
justify = '>' if isinstance(getattr(
items[0], f), int) or f == 'size' or f == 'reward' else '<'
formats.append('{:' + justify + self.string(length + 2) + '}')
borders.append('-' * length + ' ')
row_format = u''.join(formats)
headers = [f + ' ' for f in fields]
print(row_format.format(*headers))
print(row_format.format(*borders))
for i in items:
i_fields = [self.string(getattr(i, f)) + ' ' for f in fields]
try:
print(row_format.format(*i_fields))
except UnicodeEncodeError:
print(row_format.format(*i_fields).encode('utf-8')) | 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 in fields:
length = max(
len(f), max([len(self.string(getattr(i, f))) for i in items]))
justify = '>' if isinstance(getattr(
items[0], f), int) or f == 'size' or f == 'reward' else '<'
formats.append('{:' + justify + self.string(length + 2) + '}')
borders.append('-' * length + ' ')
row_format = u''.join(formats)
headers = [f + ' ' for f in fields]
print(row_format.format(*headers))
print(row_format.format(*borders))
for i in items:
i_fields = [self.string(getattr(i, f)) + ' ' for f in fields]
try:
print(row_format.format(*i_fields))
except UnicodeEncodeError:
print(row_format.format(*i_fields).encode('utf-8')) | [
"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)
writer.writerow(fields)
for i in items:
i_fields = [self.string(getattr(i, f)) for f in fields]
writer.writerow(i_fields) | 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)
writer.writerow(fields)
for i in items:
i_fields = [self.string(getattr(i, f)) for f in fields]
writer.writerow(i_fields) | [
"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: one or more resources to validate within the folder
"""
self.validate_files_exist(folder, resources)
self.validate_no_duplicate_paths(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: one or more resources to validate within the folder
"""
self.validate_files_exist(folder, resources)
self.validate_no_duplicate_paths(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 resources:
file_name = item.get('path')
full_path = os.path.join(folder, file_name)
if not os.path.isfile(full_path):
raise ValueError('%s does not exist' % full_path) | 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 resources:
file_name = item.get('path')
full_path = os.path.join(folder, file_name)
if not os.path.isfile(full_path):
raise ValueError('%s does not exist' % full_path) | [
"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 item in resources:
file_name = item.get('path')
if file_name in paths:
raise ValueError(
'%s path was specified more than once in the metadata' %
file_name)
paths.add(file_name) | 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 item in resources:
file_name = item.get('path')
if file_name in paths:
raise ValueError(
'%s path was specified more than once in the metadata' %
file_name)
paths.add(file_name) | [
"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_metadata = {
'path': os.path.join(path, file_data['name']),
'description': file_data['description']
}
schema = {}
fields = []
for column in file_data['columns']:
field = {
'name': column['name'],
'title': column['description'],
'type': column['type']
}
fields.append(field)
schema['fields'] = fields
as_metadata['schema'] = schema
return as_metadata | 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_metadata = {
'path': os.path.join(path, file_data['name']),
'description': file_data['description']
}
schema = {}
fields = []
for column in file_data['columns']:
field = {
'name': column['name'],
'title': column['description'],
'type': column['type']
}
fields.append(field)
schema['fields'] = fields
as_metadata['schema'] = schema
return as_metadata | [
"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, collections formatted
"""
new_params = []
if collection_formats is None:
collection_formats = {}
for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, value) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(str(value) for value in v)))
else:
new_params.append((k, v))
return new_params | 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, collections formatted
"""
new_params = []
if collection_formats is None:
collection_formats = {}
for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, value) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(str(value) for value in v)))
else:
new_params.append((k, v))
return new_params | [
"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 = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
f.write(response.data)
return path | 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 = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
f.write(response.data)
return path | [
"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 = ["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", "copyright-authors", "other", "reddit-api", "world-bank"] # noqa: E501
if license_name not in allowed_values:
raise ValueError(
"Invalid value for `license_name` ({0}), must be one of {1}" # noqa: E501
.format(license_name, allowed_values)
)
self._license_name = license_name | 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 = ["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", "copyright-authors", "other", "reddit-api", "world-bank"] # noqa: E501
if license_name not in allowed_values:
raise ValueError(
"Invalid value for `license_name` ({0}), must be one of {1}" # noqa: E501
.format(license_name, allowed_values)
)
self._license_name = license_name | [
"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=train_data[:sp],
batch_size=args.batch_size,
shuffle=True)
val_dataloader = DataLoader(dataset=train_data[sp:],
batch_size=args.batch_size,
shuffle=False)
test_dataloader = DataLoader(dataset=test_data,
batch_size=args.batch_size,
shuffle=False)
# Training/Testing.
best_val_acc = 0
for epoch in range(args.epochs):
# Epoch training stats.
start_epoch_time = time.time()
epoch_L = 0.0
epoch_sent_num = 0
epoch_wc = 0
# Log interval training stats.
start_log_interval_time = time.time()
log_interval_wc = 0
log_interval_sent_num = 0
log_interval_L = 0.0
for i, (data, label) in enumerate(train_dataloader):
data = mx.nd.transpose(data.as_in_context(context))
label = label.as_in_context(context)
wc = max_len
log_interval_wc += wc
epoch_wc += wc
log_interval_sent_num += data.shape[1]
epoch_sent_num += data.shape[1]
with autograd.record():
output = net(data)
L = loss(output, label).mean()
L.backward()
# Update parameter.
trainer.step(1)
log_interval_L += L.asscalar()
epoch_L += L.asscalar()
if (i + 1) % args.log_interval == 0:
print('[Epoch %d Batch %d/%d] avg loss %g, throughput %gK wps' % (
epoch, i + 1, len(train_dataloader),
log_interval_L / log_interval_sent_num,
log_interval_wc / 1000 / (time.time() - start_log_interval_time)))
# Clear log interval training stats.
start_log_interval_time = time.time()
log_interval_wc = 0
log_interval_sent_num = 0
log_interval_L = 0
end_epoch_time = time.time()
val_avg_L, val_acc = evaluate(net, val_dataloader)
print('[Epoch %d] train avg loss %g, '
'test acc %.4f, test avg loss %g, throughput %gK wps' % (
epoch, epoch_L / epoch_sent_num,
val_acc, val_avg_L,
epoch_wc / 1000 / (end_epoch_time - start_epoch_time)))
if val_acc >= best_val_acc:
print('Observed Improvement.')
best_val_acc = val_acc
test_avg_L, test_acc = evaluate(net, test_dataloader)
print('Test loss %g, test acc %.4f'%(test_avg_L, test_acc))
print('Total time cost %.2fs'%(time.time()-start_pipeline_time))
return test_acc | 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=train_data[:sp],
batch_size=args.batch_size,
shuffle=True)
val_dataloader = DataLoader(dataset=train_data[sp:],
batch_size=args.batch_size,
shuffle=False)
test_dataloader = DataLoader(dataset=test_data,
batch_size=args.batch_size,
shuffle=False)
# Training/Testing.
best_val_acc = 0
for epoch in range(args.epochs):
# Epoch training stats.
start_epoch_time = time.time()
epoch_L = 0.0
epoch_sent_num = 0
epoch_wc = 0
# Log interval training stats.
start_log_interval_time = time.time()
log_interval_wc = 0
log_interval_sent_num = 0
log_interval_L = 0.0
for i, (data, label) in enumerate(train_dataloader):
data = mx.nd.transpose(data.as_in_context(context))
label = label.as_in_context(context)
wc = max_len
log_interval_wc += wc
epoch_wc += wc
log_interval_sent_num += data.shape[1]
epoch_sent_num += data.shape[1]
with autograd.record():
output = net(data)
L = loss(output, label).mean()
L.backward()
# Update parameter.
trainer.step(1)
log_interval_L += L.asscalar()
epoch_L += L.asscalar()
if (i + 1) % args.log_interval == 0:
print('[Epoch %d Batch %d/%d] avg loss %g, throughput %gK wps' % (
epoch, i + 1, len(train_dataloader),
log_interval_L / log_interval_sent_num,
log_interval_wc / 1000 / (time.time() - start_log_interval_time)))
# Clear log interval training stats.
start_log_interval_time = time.time()
log_interval_wc = 0
log_interval_sent_num = 0
log_interval_L = 0
end_epoch_time = time.time()
val_avg_L, val_acc = evaluate(net, val_dataloader)
print('[Epoch %d] train avg loss %g, '
'test acc %.4f, test avg loss %g, throughput %gK wps' % (
epoch, epoch_L / epoch_sent_num,
val_acc, val_avg_L,
epoch_wc / 1000 / (end_epoch_time - start_epoch_time)))
if val_acc >= best_val_acc:
print('Observed Improvement.')
best_val_acc = val_acc
test_avg_L, test_acc = evaluate(net, test_dataloader)
print('Test loss %g, test acc %.4f'%(test_avg_L, test_acc))
print('Total time cost %.2fs'%(time.time()-start_pipeline_time))
return test_acc | [
"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 of
vocabulary words
Returns
-------
List[(List[str], List[ndarray])]
List of tokens, and tokens embedding
"""
data_iter = self.data_loader(sentences=sentences)
batches = []
for token_ids, valid_length, token_types in data_iter:
token_ids = token_ids.as_in_context(self.ctx)
valid_length = valid_length.as_in_context(self.ctx)
token_types = token_types.as_in_context(self.ctx)
sequence_outputs = self.bert(token_ids, token_types,
valid_length.astype(self.dtype))
for token_id, sequence_output in zip(token_ids.asnumpy(),
sequence_outputs.asnumpy()):
batches.append((token_id, sequence_output))
return self.oov(batches, oov_way) | 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 of
vocabulary words
Returns
-------
List[(List[str], List[ndarray])]
List of tokens, and tokens embedding
"""
data_iter = self.data_loader(sentences=sentences)
batches = []
for token_ids, valid_length, token_types in data_iter:
token_ids = token_ids.as_in_context(self.ctx)
valid_length = valid_length.as_in_context(self.ctx)
token_types = token_types.as_in_context(self.ctx)
sequence_outputs = self.bert(token_ids, token_types,
valid_length.astype(self.dtype))
for token_id, sequence_output in zip(token_ids.asnumpy(),
sequence_outputs.asnumpy()):
batches.append((token_id, sequence_output))
return self.oov(batches, oov_way) | [
"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
-------
List[(List[str], List[ndarray])]
List of tokens, and tokens embedding | [
"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(), 'models'), **kwargs):
"""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_1024_16 and bert_12_768_12.
'wiki_cn_cased', 'wiki_multilingual_uncased' and 'wiki_multilingual_cased'
for bert_12_768_12 only.
vocab : gluonnlp.vocab.BERTVocab or None, default None
Vocabulary for the dataset. Must be provided if dataset is not specified.
pretrained : bool, default True
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
use_pooler : bool, default True
Whether to include the pooler which converts the encoded sequence tensor of shape
(batch_size, seq_length, units) to a tensor of shape (batch_size, units)
for for segment level classification task.
use_decoder : bool, default True
Whether to include the decoder for masked language model prediction.
use_classifier : bool, default True
Whether to include the classifier for next sentence classification.
output_attention : bool, default False
Whether to include attention weights of each encoding cell to the output.
output_all_encodings : bool, default False
Whether to output encodings of all encoder cells.
Returns
-------
BERTModel, gluonnlp.vocab.BERTVocab
"""
predefined_args = bert_hparams[model_name]
mutable_args = ['use_residual', 'dropout', 'embed_dropout', 'word_embed']
mutable_args = frozenset(mutable_args)
assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \
'Cannot override predefined model settings.'
predefined_args.update(kwargs)
# encoder
encoder = BERTEncoder(attention_cell=predefined_args['attention_cell'],
num_layers=predefined_args['num_layers'],
units=predefined_args['units'],
hidden_size=predefined_args['hidden_size'],
max_length=predefined_args['max_length'],
num_heads=predefined_args['num_heads'],
scaled=predefined_args['scaled'],
dropout=predefined_args['dropout'],
output_attention=output_attention,
output_all_encodings=output_all_encodings,
use_residual=predefined_args['use_residual'])
# bert_vocab
from ..vocab import BERTVocab
if dataset_name in ['wiki_cn', 'wiki_multilingual']:
warnings.warn('wiki_cn/wiki_multilingual will be deprecated.'
' Please use wiki_cn_cased/wiki_multilingual_uncased instead.')
bert_vocab = _load_vocab(dataset_name, vocab, root, cls=BERTVocab)
# BERT
net = BERTModel(encoder, len(bert_vocab),
token_type_vocab_size=predefined_args['token_type_vocab_size'],
units=predefined_args['units'],
embed_size=predefined_args['embed_size'],
embed_dropout=predefined_args['embed_dropout'],
word_embed=predefined_args['word_embed'],
use_pooler=use_pooler, use_decoder=use_decoder,
use_classifier=use_classifier)
if pretrained:
ignore_extra = not (use_pooler and use_decoder and use_classifier)
_load_pretrained_params(net, model_name, dataset_name, root, ctx,
ignore_extra=ignore_extra)
return net, bert_vocab | 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(), 'models'), **kwargs):
"""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_1024_16 and bert_12_768_12.
'wiki_cn_cased', 'wiki_multilingual_uncased' and 'wiki_multilingual_cased'
for bert_12_768_12 only.
vocab : gluonnlp.vocab.BERTVocab or None, default None
Vocabulary for the dataset. Must be provided if dataset is not specified.
pretrained : bool, default True
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
use_pooler : bool, default True
Whether to include the pooler which converts the encoded sequence tensor of shape
(batch_size, seq_length, units) to a tensor of shape (batch_size, units)
for for segment level classification task.
use_decoder : bool, default True
Whether to include the decoder for masked language model prediction.
use_classifier : bool, default True
Whether to include the classifier for next sentence classification.
output_attention : bool, default False
Whether to include attention weights of each encoding cell to the output.
output_all_encodings : bool, default False
Whether to output encodings of all encoder cells.
Returns
-------
BERTModel, gluonnlp.vocab.BERTVocab
"""
predefined_args = bert_hparams[model_name]
mutable_args = ['use_residual', 'dropout', 'embed_dropout', 'word_embed']
mutable_args = frozenset(mutable_args)
assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \
'Cannot override predefined model settings.'
predefined_args.update(kwargs)
# encoder
encoder = BERTEncoder(attention_cell=predefined_args['attention_cell'],
num_layers=predefined_args['num_layers'],
units=predefined_args['units'],
hidden_size=predefined_args['hidden_size'],
max_length=predefined_args['max_length'],
num_heads=predefined_args['num_heads'],
scaled=predefined_args['scaled'],
dropout=predefined_args['dropout'],
output_attention=output_attention,
output_all_encodings=output_all_encodings,
use_residual=predefined_args['use_residual'])
# bert_vocab
from ..vocab import BERTVocab
if dataset_name in ['wiki_cn', 'wiki_multilingual']:
warnings.warn('wiki_cn/wiki_multilingual will be deprecated.'
' Please use wiki_cn_cased/wiki_multilingual_uncased instead.')
bert_vocab = _load_vocab(dataset_name, vocab, root, cls=BERTVocab)
# BERT
net = BERTModel(encoder, len(bert_vocab),
token_type_vocab_size=predefined_args['token_type_vocab_size'],
units=predefined_args['units'],
embed_size=predefined_args['embed_size'],
embed_dropout=predefined_args['embed_dropout'],
word_embed=predefined_args['word_embed'],
use_pooler=use_pooler, use_decoder=use_decoder,
use_classifier=use_classifier)
if pretrained:
ignore_extra = not (use_pooler and use_decoder and use_classifier)
_load_pretrained_params(net, model_name, dataset_name, root, ctx,
ignore_extra=ignore_extra)
return net, bert_vocab | [
"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_1024_16 and bert_12_768_12.
'wiki_cn_cased', 'wiki_multilingual_uncased' and 'wiki_multilingual_cased'
for bert_12_768_12 only.
vocab : gluonnlp.vocab.BERTVocab or None, default None
Vocabulary for the dataset. Must be provided if dataset is not specified.
pretrained : bool, default True
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
use_pooler : bool, default True
Whether to include the pooler which converts the encoded sequence tensor of shape
(batch_size, seq_length, units) to a tensor of shape (batch_size, units)
for for segment level classification task.
use_decoder : bool, default True
Whether to include the decoder for masked language model prediction.
use_classifier : bool, default True
Whether to include the classifier for next sentence classification.
output_attention : bool, default False
Whether to include attention weights of each encoding cell to the output.
output_all_encodings : bool, default False
Whether to output encodings of all encoder cells.
Returns
-------
BERTModel, gluonnlp.vocab.BERTVocab | [
"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')
gamma = gamma.astype('float32')
beta = beta.astype('float32')
norm_data = F.LayerNorm(data, gamma=gamma, beta=beta, axis=self._axis, eps=self._epsilon)
if self._dtype:
norm_data = norm_data.astype(self._dtype)
return norm_data | 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')
gamma = gamma.astype('float32')
beta = beta.astype('float32')
norm_data = F.LayerNorm(data, gamma=gamma, beta=beta, axis=self._axis, eps=self._epsilon)
if self._dtype:
norm_data = norm_data.astype(self._dtype)
return norm_data | [
"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())
decoder.add(BERTLayerNorm(in_channels=units))
decoder.add(nn.Dense(vocab_size, flatten=False, params=embed.collect_params()))
assert decoder[3].weight == list(embed.collect_params().values())[0], \
'The weights of word embedding are not tied with those of decoder'
return decoder | 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())
decoder.add(BERTLayerNorm(in_channels=units))
decoder.add(nn.Dense(vocab_size, flatten=False, params=embed.collect_params()))
assert decoder[3].weight == list(embed.collect_params().values())[0], \
'The weights of word embedding are not tied with those of decoder'
return decoder | [
"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 given.'
with self.name_scope():
embed = nn.HybridSequential(prefix=prefix)
with embed.name_scope():
embed.add(nn.Embedding(input_dim=vocab_size, output_dim=embed_size,
weight_initializer=initializer))
if dropout:
embed.add(nn.Dropout(rate=dropout))
assert isinstance(embed, Block)
return embed | 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 given.'
with self.name_scope():
embed = nn.HybridSequential(prefix=prefix)
with embed.name_scope():
embed.add(nn.Embedding(input_dim=vocab_size, output_dim=embed_size,
weight_initializer=initializer))
if dropout:
embed.add(nn.Dropout(rate=dropout))
assert isinstance(embed, Block)
return embed | [
"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',
prefix=prefix)
return pooler | 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',
prefix=prefix)
return pooler | [
"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_type_embed(token_types)
embedding = word_embedding + type_embedding
# encoding
outputs, additional_outputs = self.encoder(embedding, None, valid_length)
return outputs, additional_outputs | 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_type_embed(token_types)
embedding = word_embedding + type_embedding
# encoding
outputs, additional_outputs = self.encoder(embedding, None, valid_length)
return outputs, additional_outputs | [
"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).
- **masked_positions**: input tensor of position of tokens for masked LM decoding.
Shape (batch_size, num_masked_positions). For each sample in the batch, the values
in this tensor must not be out of bound considering the length of the sequence.
Outputs:
- **masked_lm_outputs**: output tensor of token predictions for target masked_positions.
Shape (batch_size, num_masked_positions, vocab_size).
"""
batch_size = sequence.shape[0]
num_masked_positions = masked_positions.shape[1]
ctx = masked_positions.context
dtype = masked_positions.dtype
# batch_idx = [0,0,0,1,1,1,2,2,2...]
# masked_positions = [1,2,4,0,3,4,2,3,5...]
batch_idx = mx.nd.arange(0, batch_size, repeat=num_masked_positions, dtype=dtype, ctx=ctx)
batch_idx = batch_idx.reshape((1, -1))
masked_positions = masked_positions.reshape((1, -1))
position_idx = mx.nd.Concat(batch_idx, masked_positions, dim=0)
encoded = mx.nd.gather_nd(sequence, position_idx)
encoded = encoded.reshape((batch_size, num_masked_positions, sequence.shape[-1]))
decoded = self.decoder(encoded)
return decoded | 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).
- **masked_positions**: input tensor of position of tokens for masked LM decoding.
Shape (batch_size, num_masked_positions). For each sample in the batch, the values
in this tensor must not be out of bound considering the length of the sequence.
Outputs:
- **masked_lm_outputs**: output tensor of token predictions for target masked_positions.
Shape (batch_size, num_masked_positions, vocab_size).
"""
batch_size = sequence.shape[0]
num_masked_positions = masked_positions.shape[1]
ctx = masked_positions.context
dtype = masked_positions.dtype
# batch_idx = [0,0,0,1,1,1,2,2,2...]
# masked_positions = [1,2,4,0,3,4,2,3,5...]
batch_idx = mx.nd.arange(0, batch_size, repeat=num_masked_positions, dtype=dtype, ctx=ctx)
batch_idx = batch_idx.reshape((1, -1))
masked_positions = masked_positions.reshape((1, -1))
position_idx = mx.nd.Concat(batch_idx, masked_positions, dim=0)
encoded = mx.nd.gather_nd(sequence, position_idx)
encoded = encoded.reshape((batch_size, num_masked_positions, sequence.shape[-1]))
decoded = self.decoder(encoded)
return decoded | [
"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 position of tokens for masked LM decoding.
Shape (batch_size, num_masked_positions). For each sample in the batch, the values
in this tensor must not be out of bound considering the length of the sequence.
Outputs:
- **masked_lm_outputs**: output tensor of token predictions for target masked_positions.
Shape (batch_size, num_masked_positions, vocab_size). | [
"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 count of how many times each n-gram occurred.
"""
ngram_counts = Counter()
for i in range(0, len(segment) - n + 1):
ngram = tuple(segment[i:i + n])
ngram_counts[ngram] += 1
return ngram_counts | 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 count of how many times each n-gram occurred.
"""
ngram_counts = Counter()
for i in range(0, len(segment) - n + 1):
ngram = tuple(segment[i:i + n])
ngram_counts[ngram] += 1
return ngram_counts | [
"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-gram occurred. | [
"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[:-delimiter_len]
else:
word += subwords
words.append(word)
word = ''
return words | 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[:-delimiter_len]
else:
word += subwords
words.append(word)
word = ''
return words | [
"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_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_corpus: list(list(str)) or list(str)
list(list(str)): tokenized translation
list(str): plain text
Translations to score.
tokenized: bool, default True
Whether the inputs has been tokenized.
tokenizer: str or None, default '13a'
'13a': follow the tokenizer in mteval-v13a.pl
'intl': follow the international tokenizer in mteval-v14.pl
None: identity mapping on the string.
This option is ignored if tokenized is True
max_n: int, default 4
Maximum n-gram order to use when computing BLEU score.
smooth: bool, default False
Whether or not to compute smoothed bleu score.
lower_case: bool, default False
Whether or not to use lower case of tokens
split_compound_word: bool, default False
Whether or not to split compound words
"rich-text format" --> rich ##AT##-##AT## text format.
bpe: bool, default False
Whether or not the inputs are in BPE format
Returns
-------
5-Tuple with the BLEU score, n-gram precisions, brevity penalty,
reference length, and translation length
"""
precision_numerators = [0 for _ in range(max_n)]
precision_denominators = [0 for _ in range(max_n)]
ref_length, trans_length = 0, 0
for references in reference_corpus_list:
assert len(references) == len(translation_corpus), \
'The number of translations and their references do not match'
if tokenized:
assert isinstance(reference_corpus_list[0][0], LIST_TYPES) and \
isinstance(translation_corpus[0], LIST_TYPES), \
'references and translation should have format of list of list(list(str)) ' \
'and list(list(str)), respectively, when tokenized is True.'
else:
assert isinstance(reference_corpus_list[0][0], six.string_types) and \
isinstance(translation_corpus[0], six.string_types), \
'references and translation should have format of list(list(str)) ' \
'and list(str), respectively, when tokenized is False.'
for references, translation in zip(zip(*reference_corpus_list), translation_corpus):
if not tokenized:
references = [TOKENIZERS[tokenizer](reference).split() for reference in references]
translation = TOKENIZERS[tokenizer](translation).split()
if bpe:
references = [_bpe_to_words(reference) for reference in references]
translation = _bpe_to_words(translation)
if split_compound_word:
references = [_split_compound_word(reference) for reference in references]
translation = _split_compound_word(translation)
if lower_case:
references = [[w.lower() for w in reference] for reference in references]
translation = [w.lower() for w in translation]
trans_len = len(translation)
trans_length += trans_len
ref_length += _closest_ref_length(references, trans_len)
for n in range(max_n):
matches, candidates = _compute_precision(references, translation, n + 1)
precision_numerators[n] += matches
precision_denominators[n] += candidates
precision_fractions = [(precision_numerators[n], precision_denominators[n])
for n in range(max_n)]
smooth_const = 0
if smooth:
smooth_const = 1
precisions = _smoothing(precision_fractions, smooth_const)
if min(precisions) > 0:
precision_log_average = sum(math.log(p) for p in precisions) / max_n
precision_exp_log_average = math.exp(precision_log_average)
else:
precision_exp_log_average = 0
bp = _brevity_penalty(ref_length, trans_length)
bleu = precision_exp_log_average*bp
return bleu, precisions, bp, ref_length, trans_length | 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_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_corpus: list(list(str)) or list(str)
list(list(str)): tokenized translation
list(str): plain text
Translations to score.
tokenized: bool, default True
Whether the inputs has been tokenized.
tokenizer: str or None, default '13a'
'13a': follow the tokenizer in mteval-v13a.pl
'intl': follow the international tokenizer in mteval-v14.pl
None: identity mapping on the string.
This option is ignored if tokenized is True
max_n: int, default 4
Maximum n-gram order to use when computing BLEU score.
smooth: bool, default False
Whether or not to compute smoothed bleu score.
lower_case: bool, default False
Whether or not to use lower case of tokens
split_compound_word: bool, default False
Whether or not to split compound words
"rich-text format" --> rich ##AT##-##AT## text format.
bpe: bool, default False
Whether or not the inputs are in BPE format
Returns
-------
5-Tuple with the BLEU score, n-gram precisions, brevity penalty,
reference length, and translation length
"""
precision_numerators = [0 for _ in range(max_n)]
precision_denominators = [0 for _ in range(max_n)]
ref_length, trans_length = 0, 0
for references in reference_corpus_list:
assert len(references) == len(translation_corpus), \
'The number of translations and their references do not match'
if tokenized:
assert isinstance(reference_corpus_list[0][0], LIST_TYPES) and \
isinstance(translation_corpus[0], LIST_TYPES), \
'references and translation should have format of list of list(list(str)) ' \
'and list(list(str)), respectively, when tokenized is True.'
else:
assert isinstance(reference_corpus_list[0][0], six.string_types) and \
isinstance(translation_corpus[0], six.string_types), \
'references and translation should have format of list(list(str)) ' \
'and list(str), respectively, when tokenized is False.'
for references, translation in zip(zip(*reference_corpus_list), translation_corpus):
if not tokenized:
references = [TOKENIZERS[tokenizer](reference).split() for reference in references]
translation = TOKENIZERS[tokenizer](translation).split()
if bpe:
references = [_bpe_to_words(reference) for reference in references]
translation = _bpe_to_words(translation)
if split_compound_word:
references = [_split_compound_word(reference) for reference in references]
translation = _split_compound_word(translation)
if lower_case:
references = [[w.lower() for w in reference] for reference in references]
translation = [w.lower() for w in translation]
trans_len = len(translation)
trans_length += trans_len
ref_length += _closest_ref_length(references, trans_len)
for n in range(max_n):
matches, candidates = _compute_precision(references, translation, n + 1)
precision_numerators[n] += matches
precision_denominators[n] += candidates
precision_fractions = [(precision_numerators[n], precision_denominators[n])
for n in range(max_n)]
smooth_const = 0
if smooth:
smooth_const = 1
precisions = _smoothing(precision_fractions, smooth_const)
if min(precisions) > 0:
precision_log_average = sum(math.log(p) for p in precisions) / max_n
precision_exp_log_average = math.exp(precision_log_average)
else:
precision_exp_log_average = 0
bp = _brevity_penalty(ref_length, trans_length)
bleu = precision_exp_log_average*bp
return bleu, precisions, bp, ref_length, trans_length | [
"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_corpus: list(list(str)) or list(str)
list(list(str)): tokenized translation
list(str): plain text
Translations to score.
tokenized: bool, default True
Whether the inputs has been tokenized.
tokenizer: str or None, default '13a'
'13a': follow the tokenizer in mteval-v13a.pl
'intl': follow the international tokenizer in mteval-v14.pl
None: identity mapping on the string.
This option is ignored if tokenized is True
max_n: int, default 4
Maximum n-gram order to use when computing BLEU score.
smooth: bool, default False
Whether or not to compute smoothed bleu score.
lower_case: bool, default False
Whether or not to use lower case of tokens
split_compound_word: bool, default False
Whether or not to split compound words
"rich-text format" --> rich ##AT##-##AT## text format.
bpe: bool, default False
Whether or not the inputs are in BPE format
Returns
-------
5-Tuple with the BLEU score, n-gram precisions, brevity penalty,
reference length, and translation length | [
"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 of matched nth order n-grams
candidates
Number of possible nth order n-grams
"""
matches = 0
candidates = 0
ref_ngram_counts = Counter()
for reference in references:
ref_ngram_counts |= _ngrams(reference, n)
trans_ngram_counts = _ngrams(translation, n)
overlap_ngram_counts = trans_ngram_counts & ref_ngram_counts
matches += sum(overlap_ngram_counts.values())
possible_matches = len(translation) - n + 1
if possible_matches > 0:
candidates += possible_matches
return matches, candidates | 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 of matched nth order n-grams
candidates
Number of possible nth order n-grams
"""
matches = 0
candidates = 0
ref_ngram_counts = Counter()
for reference in references:
ref_ngram_counts |= _ngrams(reference, n)
trans_ngram_counts = _ngrams(translation, n)
overlap_ngram_counts = trans_ngram_counts & ref_ngram_counts
matches += sum(overlap_ngram_counts.values())
possible_matches = len(translation) - n + 1
if possible_matches > 0:
candidates += possible_matches
return matches, candidates | [
"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 of possible nth order n-grams | [
"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
-------
bleu's brevity penalty: float
"""
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
else:
return math.exp(1 - float(ref_length) / trans_length) | 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
-------
bleu's brevity penalty: float
"""
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
else:
return math.exp(1 - float(ref_length) / trans_length) | [
"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: int
Length of the reference that is closest to the translation.
"""
ref_lengths = (len(reference) for reference in references)
closest_ref_len = min(ref_lengths,
key=lambda ref_length: (abs(ref_length - trans_length), ref_length))
return 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: int
Length of the reference that is closest to the translation.
"""
ref_lengths = (len(reference) for reference in references)
closest_ref_len = min(ref_lengths,
key=lambda ref_length: (abs(ref_length - trans_length), ref_length))
return 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 the translation. | [
"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
-------
ratios: list of floats
Contain the smoothed precision_fractions.
"""
ratios = [0] * len(precision_fractions)
for i, precision_fraction in enumerate(precision_fractions):
if precision_fraction[1] > 0:
ratios[i] = float(precision_fraction[0] + c) / (precision_fraction[1] + c)
else:
ratios[i] = 0.0
return ratios | 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
-------
ratios: list of floats
Contain the smoothed precision_fractions.
"""
ratios = [0] * len(precision_fractions)
for i, precision_fraction in enumerate(precision_fractions):
if precision_fraction[1] > 0:
ratios[i] = float(precision_fraction[0] + c) / (precision_fraction[1] + c)
else:
ratios[i] = 0.0
return ratios | [
"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 the smoothed precision_fractions. | [
"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 included in the vocabulary
and returned DataStream.
max_vocab_size : int, optional
Specifies a maximum size for the vocabulary.
Returns
-------
gluonnlp.data.DataStream
Each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
gluonnlp.Vocab
Vocabulary of all tokens in Text8 that occur at least min_freq times of
maximum size max_vocab_size.
idx_to_counts : list of int
Mapping from token indices to their occurrence-counts in the Text8
dataset.
"""
with print_time('count and construct vocabulary'):
counter = nlp.data.count_tokens(itertools.chain.from_iterable(data))
vocab = nlp.Vocab(counter, unknown_token=None, padding_token=None,
bos_token=None, eos_token=None, min_freq=min_freq,
max_size=max_vocab_size)
idx_to_counts = [counter[w] for w in vocab.idx_to_token]
def code(sentence):
return [vocab[token] for token in sentence if token in vocab]
with print_time('code data'):
data = data.transform(code, lazy=False)
data = nlp.data.SimpleDataStream([data])
return data, vocab, idx_to_counts | 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 included in the vocabulary
and returned DataStream.
max_vocab_size : int, optional
Specifies a maximum size for the vocabulary.
Returns
-------
gluonnlp.data.DataStream
Each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
gluonnlp.Vocab
Vocabulary of all tokens in Text8 that occur at least min_freq times of
maximum size max_vocab_size.
idx_to_counts : list of int
Mapping from token indices to their occurrence-counts in the Text8
dataset.
"""
with print_time('count and construct vocabulary'):
counter = nlp.data.count_tokens(itertools.chain.from_iterable(data))
vocab = nlp.Vocab(counter, unknown_token=None, padding_token=None,
bos_token=None, eos_token=None, min_freq=min_freq,
max_size=max_vocab_size)
idx_to_counts = [counter[w] for w in vocab.idx_to_token]
def code(sentence):
return [vocab[token] for token in sentence if token in vocab]
with print_time('code data'):
data = data.transform(code, lazy=False)
data = nlp.data.SimpleDataStream([data])
return data, vocab, idx_to_counts | [
"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_size : int, optional
Specifies a maximum size for the vocabulary.
Returns
-------
gluonnlp.data.DataStream
Each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
gluonnlp.Vocab
Vocabulary of all tokens in Text8 that occur at least min_freq times of
maximum size max_vocab_size.
idx_to_counts : list of int
Mapping from token indices to their occurrence-counts in the Text8
dataset. | [
"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_size : int, optional
Specifies a maximum size for the vocabulary.
Returns
-------
gluonnlp.data.DataStream
Each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
gluonnlp.Vocab
Vocabulary of all tokens in the Wikipedia corpus as provided by
WikiDumpStream but with maximum size max_vocab_size.
idx_to_counts : list of int
Mapping from token indices to their occurrence-counts in the Wikipedia
corpus.
"""
data = WikiDumpStream(
root=os.path.expanduser(wiki_root), language=wiki_language,
date=wiki_date)
vocab = data.vocab
if max_vocab_size:
for token in vocab.idx_to_token[max_vocab_size:]:
vocab.token_to_idx.pop(token)
vocab.idx_to_token = vocab.idx_to_token[:max_vocab_size]
idx_to_counts = data.idx_to_counts
def code(shard):
return [[vocab[token] for token in sentence if token in vocab]
for sentence in shard]
data = data.transform(code)
return data, vocab, idx_to_counts | 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_size : int, optional
Specifies a maximum size for the vocabulary.
Returns
-------
gluonnlp.data.DataStream
Each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
gluonnlp.Vocab
Vocabulary of all tokens in the Wikipedia corpus as provided by
WikiDumpStream but with maximum size max_vocab_size.
idx_to_counts : list of int
Mapping from token indices to their occurrence-counts in the Wikipedia
corpus.
"""
data = WikiDumpStream(
root=os.path.expanduser(wiki_root), language=wiki_language,
date=wiki_date)
vocab = data.vocab
if max_vocab_size:
for token in vocab.idx_to_token[max_vocab_size:]:
vocab.token_to_idx.pop(token)
vocab.idx_to_token = vocab.idx_to_token[:max_vocab_size]
idx_to_counts = data.idx_to_counts
def code(shard):
return [[vocab[token] for token in sentence if token in vocab]
for sentence in shard]
data = data.transform(code)
return data, vocab, idx_to_counts | [
"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.
Returns
-------
gluonnlp.data.DataStream
Each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
gluonnlp.Vocab
Vocabulary of all tokens in the Wikipedia corpus as provided by
WikiDumpStream but with maximum size max_vocab_size.
idx_to_counts : list of int
Mapping from token indices to their occurrence-counts in the Wikipedia
corpus. | [
"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(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(data, (row, col)), dtype=dtype,
shape=(len(centers), num_tokens)) # yapf: disable
return centers, contexts | 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(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(data, (row, col)), dtype=dtype,
shape=(len(centers), num_tokens)) # yapf: disable
return centers, contexts | [
"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(centers, dtype=index_dtype)
centers_csr = mx.nd.sparse.csr_matrix(
(data, (row, col)), dtype=dtype,
shape=(len(centers), num_tokens)) # yapf: disable
return centers_csr, contexts, centers | 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(centers, dtype=index_dtype)
centers_csr = mx.nd.sparse.csr_matrix(
(data, (row, col)), dtype=dtype,
shape=(len(centers), num_tokens)) # yapf: disable
return centers_csr, contexts, centers | [
"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_col)),
dtype=dtype, shape=(len(centers), num_tokens)) # yapf: disable
return centers, 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_col)),
dtype=dtype, shape=(len(centers), num_tokens)) # yapf: disable
return centers, 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_matrix(
(mx.nd.ones(centers.shape), centers, indptr), dtype=dtype,
shape=(len(centers), num_tokens))
return centers_csr, contexts, centers | 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_matrix(
(mx.nd.ones(centers.shape), centers, indptr), dtype=dtype,
shape=(len(centers), num_tokens))
return centers_csr, contexts, centers | [
"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 occurs at row idx in the
SkipGram batch.
offset : int
Offset to add to each subword index.
subwordidxs : numpy.ndarray
Array containing concatenation of all subwords of all tokens in the
vocabulary, in order of their occurrence in the vocabulary.
For example np.concatenate(idx_to_subwordidxs)
subwordidxsptr
Array containing pointers into subwordidxs array such that
subwordidxs[subwordidxsptr[i]:subwordidxsptr[i+1]] returns all subwords
of of token i. For example subwordidxsptr = np.cumsum([
len(subwordidxs) for subwordidxs in idx_to_subwordidxs])
offset : int, default 0
Offset to add to each subword index.
Returns
-------
numpy.ndarray of dtype float32
Array containing weights such that for each row, all weights sum to
1. In particular, all elements in a row have weight 1 /
num_elements_in_the_row
numpy.ndarray of dtype int64
This array is the row array of a sparse array of COO format.
numpy.ndarray of dtype int64
This array is the col array of a sparse array of COO format.
"""
row = []
col = []
data = []
for i, idx in enumerate(indices):
start = subwordidxsptr[idx]
end = subwordidxsptr[idx + 1]
row.append(i)
col.append(idx)
data.append(1 / (1 + end - start))
for subword in subwordidxs[start:end]:
row.append(i)
col.append(subword + offset)
data.append(1 / (1 + end - start))
return (np.array(data, dtype=np.float32), np.array(row, dtype=np.int64),
np.array(col, dtype=np.int64)) | 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 occurs at row idx in the
SkipGram batch.
offset : int
Offset to add to each subword index.
subwordidxs : numpy.ndarray
Array containing concatenation of all subwords of all tokens in the
vocabulary, in order of their occurrence in the vocabulary.
For example np.concatenate(idx_to_subwordidxs)
subwordidxsptr
Array containing pointers into subwordidxs array such that
subwordidxs[subwordidxsptr[i]:subwordidxsptr[i+1]] returns all subwords
of of token i. For example subwordidxsptr = np.cumsum([
len(subwordidxs) for subwordidxs in idx_to_subwordidxs])
offset : int, default 0
Offset to add to each subword index.
Returns
-------
numpy.ndarray of dtype float32
Array containing weights such that for each row, all weights sum to
1. In particular, all elements in a row have weight 1 /
num_elements_in_the_row
numpy.ndarray of dtype int64
This array is the row array of a sparse array of COO format.
numpy.ndarray of dtype int64
This array is the col array of a sparse array of COO format.
"""
row = []
col = []
data = []
for i, idx in enumerate(indices):
start = subwordidxsptr[idx]
end = subwordidxsptr[idx + 1]
row.append(i)
col.append(idx)
data.append(1 / (1 + end - start))
for subword in subwordidxs[start:end]:
row.append(i)
col.append(subword + offset)
data.append(1 / (1 + end - start))
return (np.array(data, dtype=np.float32), np.array(row, dtype=np.int64),
np.array(col, dtype=np.int64)) | [
"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
Offset to add to each subword index.
subwordidxs : numpy.ndarray
Array containing concatenation of all subwords of all tokens in the
vocabulary, in order of their occurrence in the vocabulary.
For example np.concatenate(idx_to_subwordidxs)
subwordidxsptr
Array containing pointers into subwordidxs array such that
subwordidxs[subwordidxsptr[i]:subwordidxsptr[i+1]] returns all subwords
of of token i. For example subwordidxsptr = np.cumsum([
len(subwordidxs) for subwordidxs in idx_to_subwordidxs])
offset : int, default 0
Offset to add to each subword index.
Returns
-------
numpy.ndarray of dtype float32
Array containing weights such that for each row, all weights sum to
1. In particular, all elements in a row have weight 1 /
num_elements_in_the_row
numpy.ndarray of dtype int64
This array is the row array of a sparse array of COO format.
numpy.ndarray of dtype int64
This array is the col array of a sparse array of COO format. | [
"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,
batch_size). For each idx, context_row[idx] specifies the row that
context_col[idx] occurs in a sparse matrix.
context_col : numpy.ndarray of dtype int64
Array of same length as context_row containing numbers in [0,
vocabulary_size). For each idx, context_col[idx] is one of the
context words in the context_row[idx] row of the batch.
subwordidxs : numpy.ndarray
Array containing concatenation of all subwords of all tokens in the
vocabulary, in order of their occurrence in the vocabulary.
For example np.concatenate(idx_to_subwordidxs)
subwordidxsptr
Array containing pointers into subwordidxs array such that
subwordidxs[subwordidxsptr[i]:subwordidxsptr[i+1]] returns all subwords
of of token i. For example subwordidxsptr = np.cumsum([
len(subwordidxs) for subwordidxs in idx_to_subwordidxs])
offset : int, default 0
Offset to add to each subword index.
Returns
-------
numpy.ndarray of dtype float32
Array containing weights summing to 1. The weights are chosen such
that the sum of weights for all subwords and word units of a given
context word is equal to 1 / number_of_context_words_in_the_row.
This array is the data array of a sparse array of COO format.
numpy.ndarray of dtype int64
This array is the row array of a sparse array of COO format.
numpy.ndarray of dtype int64
This array is the col array of a sparse array of COO format.
Array containing weights such that for each row, all weights sum to
1. In particular, all elements in a row have weight 1 /
num_elements_in_the_row
"""
row = []
col = []
data = []
num_rows = np.max(context_row) + 1
row_to_numwords = np.zeros(num_rows)
for i, idx in enumerate(context_col):
start = subwordidxsptr[idx]
end = subwordidxsptr[idx + 1]
row_ = context_row[i]
row_to_numwords[row_] += 1
row.append(row_)
col.append(idx)
data.append(1 / (1 + end - start))
for subword in subwordidxs[start:end]:
row.append(row_)
col.append(subword + offset)
data.append(1 / (1 + end - start))
# Normalize by number of words
for i, row_ in enumerate(row):
assert 0 <= row_ <= num_rows
data[i] /= row_to_numwords[row_]
return (np.array(data, dtype=np.float32), np.array(row, dtype=np.int64),
np.array(col, dtype=np.int64)) | 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,
batch_size). For each idx, context_row[idx] specifies the row that
context_col[idx] occurs in a sparse matrix.
context_col : numpy.ndarray of dtype int64
Array of same length as context_row containing numbers in [0,
vocabulary_size). For each idx, context_col[idx] is one of the
context words in the context_row[idx] row of the batch.
subwordidxs : numpy.ndarray
Array containing concatenation of all subwords of all tokens in the
vocabulary, in order of their occurrence in the vocabulary.
For example np.concatenate(idx_to_subwordidxs)
subwordidxsptr
Array containing pointers into subwordidxs array such that
subwordidxs[subwordidxsptr[i]:subwordidxsptr[i+1]] returns all subwords
of of token i. For example subwordidxsptr = np.cumsum([
len(subwordidxs) for subwordidxs in idx_to_subwordidxs])
offset : int, default 0
Offset to add to each subword index.
Returns
-------
numpy.ndarray of dtype float32
Array containing weights summing to 1. The weights are chosen such
that the sum of weights for all subwords and word units of a given
context word is equal to 1 / number_of_context_words_in_the_row.
This array is the data array of a sparse array of COO format.
numpy.ndarray of dtype int64
This array is the row array of a sparse array of COO format.
numpy.ndarray of dtype int64
This array is the col array of a sparse array of COO format.
Array containing weights such that for each row, all weights sum to
1. In particular, all elements in a row have weight 1 /
num_elements_in_the_row
"""
row = []
col = []
data = []
num_rows = np.max(context_row) + 1
row_to_numwords = np.zeros(num_rows)
for i, idx in enumerate(context_col):
start = subwordidxsptr[idx]
end = subwordidxsptr[idx + 1]
row_ = context_row[i]
row_to_numwords[row_] += 1
row.append(row_)
col.append(idx)
data.append(1 / (1 + end - start))
for subword in subwordidxs[start:end]:
row.append(row_)
col.append(subword + offset)
data.append(1 / (1 + end - start))
# Normalize by number of words
for i, row_ in enumerate(row):
assert 0 <= row_ <= num_rows
data[i] /= row_to_numwords[row_]
return (np.array(data, dtype=np.float32), np.array(row, dtype=np.int64),
np.array(col, dtype=np.int64)) | [
"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 sparse matrix.
context_col : numpy.ndarray of dtype int64
Array of same length as context_row containing numbers in [0,
vocabulary_size). For each idx, context_col[idx] is one of the
context words in the context_row[idx] row of the batch.
subwordidxs : numpy.ndarray
Array containing concatenation of all subwords of all tokens in the
vocabulary, in order of their occurrence in the vocabulary.
For example np.concatenate(idx_to_subwordidxs)
subwordidxsptr
Array containing pointers into subwordidxs array such that
subwordidxs[subwordidxsptr[i]:subwordidxsptr[i+1]] returns all subwords
of of token i. For example subwordidxsptr = np.cumsum([
len(subwordidxs) for subwordidxs in idx_to_subwordidxs])
offset : int, default 0
Offset to add to each subword index.
Returns
-------
numpy.ndarray of dtype float32
Array containing weights summing to 1. The weights are chosen such
that the sum of weights for all subwords and word units of a given
context word is equal to 1 / number_of_context_words_in_the_row.
This array is the data array of a sparse array of COO format.
numpy.ndarray of dtype int64
This array is the row array of a sparse array of COO format.
numpy.ndarray of dtype int64
This array is the col array of a sparse array of COO format.
Array containing weights such that for each row, all weights sum to
1. In particular, all elements in a row have weight 1 /
num_elements_in_the_row | [
"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' + '_' + self._src_lang]
[src_vocab_path] = self._fetch_data_path([(src_vocab_file_name, src_vocab_hash)])
with io.open(src_vocab_path, 'r', encoding='utf-8') as in_file:
self._src_vocab = Vocab.from_json(in_file.read())
return self._src_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' + '_' + self._src_lang]
[src_vocab_path] = self._fetch_data_path([(src_vocab_file_name, src_vocab_hash)])
with io.open(src_vocab_path, 'r', encoding='utf-8') as in_file:
self._src_vocab = Vocab.from_json(in_file.read())
return self._src_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' + '_' + self._tgt_lang]
[tgt_vocab_path] = self._fetch_data_path([(tgt_vocab_file_name, tgt_vocab_hash)])
with io.open(tgt_vocab_path, 'r', encoding='utf-8') as in_file:
self._tgt_vocab = Vocab.from_json(in_file.read())
return self._tgt_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' + '_' + self._tgt_lang]
[tgt_vocab_path] = self._fetch_data_path([(tgt_vocab_file_name, tgt_vocab_hash)])
with io.open(tgt_vocab_path, 'r', encoding='utf-8') as in_file:
self._tgt_vocab = Vocab.from_json(in_file.read())
return self._tgt_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 = []
avg_loss_denom = 0
avg_loss = 0.0
for _, (src_seq, tgt_seq, src_valid_length, tgt_valid_length, inst_ids) \
in enumerate(data_loader):
src_seq = src_seq.as_in_context(ctx)
tgt_seq = tgt_seq.as_in_context(ctx)
src_valid_length = src_valid_length.as_in_context(ctx)
tgt_valid_length = tgt_valid_length.as_in_context(ctx)
# Calculating Loss
out, _ = model(src_seq, tgt_seq[:, :-1], src_valid_length, tgt_valid_length - 1)
loss = loss_function(out, tgt_seq[:, 1:], tgt_valid_length - 1).mean().asscalar()
all_inst_ids.extend(inst_ids.asnumpy().astype(np.int32).tolist())
avg_loss += loss * (tgt_seq.shape[1] - 1)
avg_loss_denom += (tgt_seq.shape[1] - 1)
# Translate
samples, _, sample_valid_length =\
translator.translate(src_seq=src_seq, src_valid_length=src_valid_length)
max_score_sample = samples[:, 0, :].asnumpy()
sample_valid_length = sample_valid_length[:, 0].asnumpy()
for i in range(max_score_sample.shape[0]):
translation_out.append(
[tgt_vocab.idx_to_token[ele] for ele in
max_score_sample[i][1:(sample_valid_length[i] - 1)]])
avg_loss = avg_loss / avg_loss_denom
real_translation_out = [None for _ in range(len(all_inst_ids))]
for ind, sentence in zip(all_inst_ids, translation_out):
real_translation_out[ind] = sentence
return avg_loss, real_translation_out | 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 = []
avg_loss_denom = 0
avg_loss = 0.0
for _, (src_seq, tgt_seq, src_valid_length, tgt_valid_length, inst_ids) \
in enumerate(data_loader):
src_seq = src_seq.as_in_context(ctx)
tgt_seq = tgt_seq.as_in_context(ctx)
src_valid_length = src_valid_length.as_in_context(ctx)
tgt_valid_length = tgt_valid_length.as_in_context(ctx)
# Calculating Loss
out, _ = model(src_seq, tgt_seq[:, :-1], src_valid_length, tgt_valid_length - 1)
loss = loss_function(out, tgt_seq[:, 1:], tgt_valid_length - 1).mean().asscalar()
all_inst_ids.extend(inst_ids.asnumpy().astype(np.int32).tolist())
avg_loss += loss * (tgt_seq.shape[1] - 1)
avg_loss_denom += (tgt_seq.shape[1] - 1)
# Translate
samples, _, sample_valid_length =\
translator.translate(src_seq=src_seq, src_valid_length=src_valid_length)
max_score_sample = samples[:, 0, :].asnumpy()
sample_valid_length = sample_valid_length[:, 0].asnumpy()
for i in range(max_score_sample.shape[0]):
translation_out.append(
[tgt_vocab.idx_to_token[ele] for ele in
max_score_sample[i][1:(sample_valid_length[i] - 1)]])
avg_loss = avg_loss / avg_loss_denom
real_translation_out = [None for _ in range(len(all_inst_ids))]
for ind, sentence in zip(all_inst_ids, translation_out):
real_translation_out[ind] = sentence
return avg_loss, real_translation_out | [
"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,
title={Improving neural language models with a continuous cache},
author={Grave, Edouard and Joulin, Armand and Usunier, Nicolas},
journal={ICLR},
year={2017}
}
Parameters
----------
name : str
Name of the cache language model.
dataset_name : str or None, default 'wikitext-2'.
The dataset name on which the pre-trained model is trained.
Options are 'wikitext-2'. If specified, then the returned vocabulary is extracted from
the training set of the dataset.
If None, then vocab is required, for specifying embedding weight size, and is directly
returned.
window : int
Size of cache window
theta : float
The scala controls the flatness of the cache distribution
that predict the next word as shown below:
.. math::
p_{cache} \propto \sum_{i=1}^{t-1} \mathbb{1}_{w=x_{i+1}} exp(\theta {h_t}^T h_i)
where :math:`p_{cache}` is the cache distribution, :math:`\mathbb{1}` is
the identity function, and :math:`h_i` is the output of timestep i.
lambdas : float
Linear scalar between only cache and vocab distribution, the formulation is as below:
.. math::
p = (1 - \lambda) p_{vocab} + \lambda p_{cache}
where :math:`p_{vocab}` is the vocabulary distribution and :math:`p_{cache}`
is the cache distribution.
vocab : gluonnlp.Vocab or None, default None
Vocabulary object to be used with the language model.
Required when dataset_name is not specified.
pretrained : bool, default False
Whether to load the pre-trained weights for model.
ctx : Context, default CPU
The context in which to load the pre-trained weights.
root : str, default '~/.mxnet/models'
Location for keeping the pre-trained model parameters.
Returns
-------
Block
The model.
"""
lm_model, vocab = nlp.model.\
get_model(name, dataset_name=dataset_name, pretrained=True, ctx=ctx, **kwargs)
cache_cell = CacheCell(lm_model, len(vocab), window, theta, lambdas)
return cache_cell | 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,
title={Improving neural language models with a continuous cache},
author={Grave, Edouard and Joulin, Armand and Usunier, Nicolas},
journal={ICLR},
year={2017}
}
Parameters
----------
name : str
Name of the cache language model.
dataset_name : str or None, default 'wikitext-2'.
The dataset name on which the pre-trained model is trained.
Options are 'wikitext-2'. If specified, then the returned vocabulary is extracted from
the training set of the dataset.
If None, then vocab is required, for specifying embedding weight size, and is directly
returned.
window : int
Size of cache window
theta : float
The scala controls the flatness of the cache distribution
that predict the next word as shown below:
.. math::
p_{cache} \propto \sum_{i=1}^{t-1} \mathbb{1}_{w=x_{i+1}} exp(\theta {h_t}^T h_i)
where :math:`p_{cache}` is the cache distribution, :math:`\mathbb{1}` is
the identity function, and :math:`h_i` is the output of timestep i.
lambdas : float
Linear scalar between only cache and vocab distribution, the formulation is as below:
.. math::
p = (1 - \lambda) p_{vocab} + \lambda p_{cache}
where :math:`p_{vocab}` is the vocabulary distribution and :math:`p_{cache}`
is the cache distribution.
vocab : gluonnlp.Vocab or None, default None
Vocabulary object to be used with the language model.
Required when dataset_name is not specified.
pretrained : bool, default False
Whether to load the pre-trained weights for model.
ctx : Context, default CPU
The context in which to load the pre-trained weights.
root : str, default '~/.mxnet/models'
Location for keeping the pre-trained model parameters.
Returns
-------
Block
The model.
"""
lm_model, vocab = nlp.model.\
get_model(name, dataset_name=dataset_name, pretrained=True, ctx=ctx, **kwargs)
cache_cell = CacheCell(lm_model, len(vocab), window, theta, lambdas)
return cache_cell | [
"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, Nicolas},
journal={ICLR},
year={2017}
}
Parameters
----------
name : str
Name of the cache language model.
dataset_name : str or None, default 'wikitext-2'.
The dataset name on which the pre-trained model is trained.
Options are 'wikitext-2'. If specified, then the returned vocabulary is extracted from
the training set of the dataset.
If None, then vocab is required, for specifying embedding weight size, and is directly
returned.
window : int
Size of cache window
theta : float
The scala controls the flatness of the cache distribution
that predict the next word as shown below:
.. math::
p_{cache} \propto \sum_{i=1}^{t-1} \mathbb{1}_{w=x_{i+1}} exp(\theta {h_t}^T h_i)
where :math:`p_{cache}` is the cache distribution, :math:`\mathbb{1}` is
the identity function, and :math:`h_i` is the output of timestep i.
lambdas : float
Linear scalar between only cache and vocab distribution, the formulation is as below:
.. math::
p = (1 - \lambda) p_{vocab} + \lambda p_{cache}
where :math:`p_{vocab}` is the vocabulary distribution and :math:`p_{cache}`
is the cache distribution.
vocab : gluonnlp.Vocab or None, default None
Vocabulary object to be used with the language model.
Required when dataset_name is not specified.
pretrained : bool, default False
Whether to load the pre-trained weights for model.
ctx : Context, default CPU
The context in which to load the pre-trained weights.
root : str, default '~/.mxnet/models'
Location for keeping the pre-trained model parameters.
Returns
-------
Block
The model. | [
"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')
data_b = dataset.get_field('b')
Parameters
----------
field : str
The name of the field to retrieve.
"""
idx = self._keys.index(field)
return self._data[idx] | 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')
data_b = dataset.get_field('b')
Parameters
----------
field : str
The name of the field to retrieve.
"""
idx = self._keys.index(field)
return self._data[idx] | [
"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')
Parameters
----------
field : str
The name of the field to retrieve. | [
"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: dict
F1 and EM scores.
"""
f1 = exact_match = total = 0
for record in dataset:
total += 1
if record[1] not in predict_data:
message = 'Unanswered question ' + record[1] + \
' will receive score 0.'
print(message)
continue
ground_truths = record[4]
prediction = predict_data[record[1]]
exact_match += metric_max_over_ground_truths(
exact_match_score, prediction, ground_truths)
f1 += metric_max_over_ground_truths(f1_score, prediction,
ground_truths)
exact_match = 100.0 * exact_match / total
f1 = 100.0 * f1 / total
scores = {'exact_match': exact_match, 'f1': f1}
return 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: dict
F1 and EM scores.
"""
f1 = exact_match = total = 0
for record in dataset:
total += 1
if record[1] not in predict_data:
message = 'Unanswered question ' + record[1] + \
' will receive score 0.'
print(message)
continue
ground_truths = record[4]
prediction = predict_data[record[1]]
exact_match += metric_max_over_ground_truths(
exact_match_score, prediction, ground_truths)
f1 += metric_max_over_ground_truths(f1_score, prediction,
ground_truths)
exact_match = 100.0 * exact_match / total
f1 = 100.0 * f1 / total
scores = {'exact_match': exact_match, 'f1': f1}
return 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' if not task.get_labels() else 'int32')
data_train = task('train').transform(trans, lazy=False)
data_train_len = data_train.transform(
lambda input_id, length, segment_id, label_id: length)
num_samples_train = len(data_train)
# bucket sampler
batchify_fn = nlp.data.batchify.Tuple(
nlp.data.batchify.Pad(axis=0), nlp.data.batchify.Stack(),
nlp.data.batchify.Pad(axis=0),
nlp.data.batchify.Stack(
'float32' if not task.get_labels() else 'int32'))
batch_sampler = nlp.data.sampler.FixedBucketSampler(
data_train_len,
batch_size=batch_size,
num_buckets=10,
ratio=0,
shuffle=True)
# data loaders
dataloader_train = gluon.data.DataLoader(
dataset=data_train,
num_workers=1,
batch_sampler=batch_sampler,
batchify_fn=batchify_fn)
if task.task_name == 'MNLI':
data_dev_matched = task('dev_matched').transform(trans, lazy=False)
data_dev_mismatched = task('dev_mismatched').transform(trans, lazy=False)
dataloader_dev_matched = mx.gluon.data.DataLoader(
data_dev_matched, batch_size=dev_batch_size,
num_workers=1, shuffle=False, batchify_fn=batchify_fn)
dataloader_dev_mismatched = mx.gluon.data.DataLoader(
data_dev_mismatched, batch_size=dev_batch_size,
num_workers=1, shuffle=False, batchify_fn=batchify_fn)
return dataloader_train, dataloader_dev_matched, \
dataloader_dev_mismatched, num_samples_train
else:
data_dev = task('dev').transform(trans, lazy=False)
dataloader_dev = mx.gluon.data.DataLoader(
data_dev,
batch_size=dev_batch_size,
num_workers=1,
shuffle=False,
batchify_fn=batchify_fn)
return dataloader_train, dataloader_dev, num_samples_train | 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' if not task.get_labels() else 'int32')
data_train = task('train').transform(trans, lazy=False)
data_train_len = data_train.transform(
lambda input_id, length, segment_id, label_id: length)
num_samples_train = len(data_train)
# bucket sampler
batchify_fn = nlp.data.batchify.Tuple(
nlp.data.batchify.Pad(axis=0), nlp.data.batchify.Stack(),
nlp.data.batchify.Pad(axis=0),
nlp.data.batchify.Stack(
'float32' if not task.get_labels() else 'int32'))
batch_sampler = nlp.data.sampler.FixedBucketSampler(
data_train_len,
batch_size=batch_size,
num_buckets=10,
ratio=0,
shuffle=True)
# data loaders
dataloader_train = gluon.data.DataLoader(
dataset=data_train,
num_workers=1,
batch_sampler=batch_sampler,
batchify_fn=batchify_fn)
if task.task_name == 'MNLI':
data_dev_matched = task('dev_matched').transform(trans, lazy=False)
data_dev_mismatched = task('dev_mismatched').transform(trans, lazy=False)
dataloader_dev_matched = mx.gluon.data.DataLoader(
data_dev_matched, batch_size=dev_batch_size,
num_workers=1, shuffle=False, batchify_fn=batchify_fn)
dataloader_dev_mismatched = mx.gluon.data.DataLoader(
data_dev_mismatched, batch_size=dev_batch_size,
num_workers=1, shuffle=False, batchify_fn=batchify_fn)
return dataloader_train, dataloader_dev_matched, \
dataloader_dev_mismatched, num_samples_train
else:
data_dev = task('dev').transform(trans, lazy=False)
dataloader_dev = mx.gluon.data.DataLoader(
data_dev,
batch_size=dev_batch_size,
num_workers=1,
shuffle=False,
batchify_fn=batchify_fn)
return dataloader_train, dataloader_dev, num_samples_train | [
"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_str = '[Epoch %d Batch %d/%d] loss=%.4f, lr=%.7f, metrics:' + \
','.join([i + ':%.4f' for i in metric_nm])
logging.info(train_str, epoch_id + 1, batch_id + 1, batch_num, \
step_loss / log_interval, \
learning_rate, \
*metric_val) | 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_str = '[Epoch %d Batch %d/%d] loss=%.4f, lr=%.7f, metrics:' + \
','.join([i + ':%.4f' for i in metric_nm])
logging.info(train_str, epoch_id + 1, batch_id + 1, batch_num, \
step_loss / log_interval, \
learning_rate, \
*metric_val) | [
"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] loss=%.4f, metrics:' + \
','.join([i + ':%.4f' for i in metric_nm])
logging.info(eval_str, batch_id + 1, batch_num, \
step_loss / log_interval, \
*metric_val) | 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] loss=%.4f, metrics:' + \
','.join([i + ':%.4f' for i in metric_nm])
logging.info(eval_str, batch_id + 1, batch_num, \
step_loss / log_interval, \
*metric_val) | [
"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.reset()
step_loss = 0
tic = time.time()
for batch_id, seqs in enumerate(dev_data):
input_ids, valid_length, type_ids, label = seqs
out = model(input_ids.as_in_context(ctx),
type_ids.as_in_context(ctx),
valid_length.astype('float32').as_in_context(ctx))
ls = loss_function(out, label.as_in_context(ctx)).mean()
step_loss += ls.asscalar()
metric.update([label], [out])
if (batch_id + 1) % (args.log_interval) == 0:
log_inference(batch_id, len(dev_data), metric, step_loss, args.log_interval)
step_loss = 0
mx.nd.waitall()
toc = time.time()
total_num = dev_batch_size * len(dev_data)
logging.info('Time cost=%.2fs, throughput=%.2fsamples/s', toc - tic, \
total_num / (toc - tic)) | 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.reset()
step_loss = 0
tic = time.time()
for batch_id, seqs in enumerate(dev_data):
input_ids, valid_length, type_ids, label = seqs
out = model(input_ids.as_in_context(ctx),
type_ids.as_in_context(ctx),
valid_length.astype('float32').as_in_context(ctx))
ls = loss_function(out, label.as_in_context(ctx)).mean()
step_loss += ls.asscalar()
metric.update([label], [out])
if (batch_id + 1) % (args.log_interval) == 0:
log_inference(batch_id, len(dev_data), metric, step_loss, args.log_interval)
step_loss = 0
mx.nd.waitall()
toc = time.time()
total_num = dev_batch_size * len(dev_data)
logging.info('Time cost=%.2fs, throughput=%.2fsamples/s', toc - tic, \
total_num / (toc - tic)) | [
"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 length of context (padded or trimmed to that size)
Returns
-------
SimpleDataset
Dataset of preprocessed records
"""
vocab_provider = VocabProvider(dataset)
transformer = SQuADTransform(
vocab_provider, question_max_length, context_max_length)
processed_dataset = SimpleDataset(
dataset.transform(transformer, lazy=False))
return processed_dataset | 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 length of context (padded or trimmed to that size)
Returns
-------
SimpleDataset
Dataset of preprocessed records
"""
vocab_provider = VocabProvider(dataset)
transformer = SQuADTransform(
vocab_provider, question_max_length, context_max_length)
processed_dataset = SimpleDataset(
dataset.transform(transformer, lazy=False))
return processed_dataset | [
"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
-------
SimpleDataset
Dataset of preprocessed records | [
"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
-------
List[Tuple]
list of Tuple(answer_start_index answer_end_index) per question
"""
return [(answer_start_list[i], answer_start_list[i] + len(answer))
for i, answer in enumerate(answer_list)] | 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
-------
List[Tuple]
list of Tuple(answer_start_index answer_end_index) per question
"""
return [(answer_start_list[i], answer_start_list[i] + len(answer))
for i, answer in enumerate(answer_list)] | [
"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_end_index) per question | [
"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, source_str)))
return VocabProvider._create_squad_vocab(simple_tokenize, self._dataset) | 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, source_str)))
return VocabProvider._create_squad_vocab(simple_tokenize, self._dataset) | [
"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):
output.append(' ')
else:
output.append(char)
return ''.join(output) | 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):
output.append(' ')
else:
output.append(char)
return ''.join(output) | [
"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.startswith('C'):
return True
return False | 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.startswith('C'):
return True
return False | [
"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])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return [''.join(x) for x in output] | 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])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return [''.join(x) for x in output] | [
"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
cat = unicodedata.category(char)
if cat == 'Zs':
return True
return False | 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
cat = unicodedata.category(char)
if cat == 'Zs':
return True
return False | [
"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 tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop() | 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 tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop() | [
"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.add_argument('--embedding-path', type=str,
help='Path to a .vec in Word2Vec text foramt or '
'.bin binary fastText model file. ')
group.add_argument('--embedding-name', type=str,
help=('Name of embedding type to load. '
'Valid entries: {}'.format(
', '.join(
nlp.embedding.list_sources().keys()))))
group.add_argument('--embedding-source', type=str,
help=('Source from which to initialize the embedding.'
'Pass --list-embedding-sources to get a list of '
'valid sources for a given --embedding-name.'))
group.add_argument(
'--fasttext-load-ngrams',
action='store_true',
help=('Specify load_ngrams=True '
'when loading pretrained fastText embedding.'))
group.add_argument(
'--analogy-max-vocab-size', type=int, default=None,
help=('Only retain the X first tokens from the pre-trained embedding. '
'The tokens are ordered by decreasing frequency.'
'As the analogy task takes the whole vocabulary into account, '
'removing very infrequent words improves performance.'))
group.add_argument('--list-embedding-sources', action='store_true')
# Computation options
group = parser.add_argument_group('Computation arguments')
group.add_argument('--batch-size', type=int, default=1024,
help='Batch size to use on analogy task. '
'Decrease batch size if evaluation crashes.')
group.add_argument('--gpu', type=int,
help=('Number (index) of GPU to run on, e.g. 0. '
'If not specified, uses CPU.'))
group.add_argument('--no-hybridize', action='store_true',
help='Disable hybridization of gluon HybridBlocks.')
# Logging
group = parser.add_argument_group('Logging arguments')
group.add_argument('--logdir', type=str, default='logs',
help='Directory to store logs.')
# Evaluation options
evaluation.add_parameters(parser)
args = parser.parse_args()
validate_args(args)
evaluation.validate_args(args)
return args | 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.add_argument('--embedding-path', type=str,
help='Path to a .vec in Word2Vec text foramt or '
'.bin binary fastText model file. ')
group.add_argument('--embedding-name', type=str,
help=('Name of embedding type to load. '
'Valid entries: {}'.format(
', '.join(
nlp.embedding.list_sources().keys()))))
group.add_argument('--embedding-source', type=str,
help=('Source from which to initialize the embedding.'
'Pass --list-embedding-sources to get a list of '
'valid sources for a given --embedding-name.'))
group.add_argument(
'--fasttext-load-ngrams',
action='store_true',
help=('Specify load_ngrams=True '
'when loading pretrained fastText embedding.'))
group.add_argument(
'--analogy-max-vocab-size', type=int, default=None,
help=('Only retain the X first tokens from the pre-trained embedding. '
'The tokens are ordered by decreasing frequency.'
'As the analogy task takes the whole vocabulary into account, '
'removing very infrequent words improves performance.'))
group.add_argument('--list-embedding-sources', action='store_true')
# Computation options
group = parser.add_argument_group('Computation arguments')
group.add_argument('--batch-size', type=int, default=1024,
help='Batch size to use on analogy task. '
'Decrease batch size if evaluation crashes.')
group.add_argument('--gpu', type=int,
help=('Number (index) of GPU to run on, e.g. 0. '
'If not specified, uses CPU.'))
group.add_argument('--no-hybridize', action='store_true',
help='Disable hybridization of gluon HybridBlocks.')
# Logging
group = parser.add_argument_group('Logging arguments')
group.add_argument('--logdir', type=str, default='logs',
help='Directory to store logs.')
# Evaluation options
evaluation.add_parameters(parser)
args = parser.parse_args()
validate_args(args)
evaluation.validate_args(args)
return args | [
"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_to_token = sorted(model._token_to_idx, key=model._token_to_idx.get)
embedding = nlp.embedding.TokenEmbedding(
unknown_token=None, unknown_lookup=model, allow_extend=True)
# Analogy task is open-vocabulary, so must keep all known words.
# But if not evaluating analogy, no need to precompute now as all
# words for closed vocabulary task can be obtained via the unknown
# lookup
if not args.analogy_datasets:
idx_to_token = []
elif args.analogy_datasets and args.analogy_max_vocab_size:
idx_to_token = idx_to_token[:args.analogy_max_vocab_size]
embedding['<unk>'] = mx.nd.zeros(model.weight.shape[1])
if idx_to_token:
with utils.print_time('compute vectors for {} known '
'words.'.format(len(idx_to_token))):
embedding[idx_to_token] = model[idx_to_token]
else:
embedding = nlp.embedding.TokenEmbedding.from_file(args.embedding_path)
return embedding | 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_to_token = sorted(model._token_to_idx, key=model._token_to_idx.get)
embedding = nlp.embedding.TokenEmbedding(
unknown_token=None, unknown_lookup=model, allow_extend=True)
# Analogy task is open-vocabulary, so must keep all known words.
# But if not evaluating analogy, no need to precompute now as all
# words for closed vocabulary task can be obtained via the unknown
# lookup
if not args.analogy_datasets:
idx_to_token = []
elif args.analogy_datasets and args.analogy_max_vocab_size:
idx_to_token = idx_to_token[:args.analogy_max_vocab_size]
embedding['<unk>'] = mx.nd.zeros(model.weight.shape[1])
if idx_to_token:
with utils.print_time('compute vectors for {} known '
'words.'.format(len(idx_to_token))):
embedding[idx_to_token] = model[idx_to_token]
else:
embedding = nlp.embedding.TokenEmbedding.from_file(args.embedding_path)
return embedding | [
"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_grads`` so that the gradients are summed first before calculating
the 2-norm.
.. note::
This function is only for use when `update_on_kvstore` is set to False in trainer.
Example::
trainer = Trainer(net.collect_params(), update_on_kvstore=False, ...)
for x, y in mx.gluon.utils.split_and_load(X, [mx.gpu(0), mx.gpu(1)]):
with mx.autograd.record():
y = net(x)
loss = loss_fn(y, label)
loss.backward()
trainer.allreduce_grads()
norm, ratio = grad_global_norm(net.collect_params().values(), max_norm)
trainer.update(batch_size * ratio)
...
Parameters
----------
parameters : list of Parameters
Returns
-------
NDArray
Total norm. Shape is (1,)
NDArray
Ratio for rescaling gradients based on max_norm s.t. grad = grad / ratio.
If total norm is NaN, ratio will be NaN, too. Shape is (1,)
NDArray
Whether the total norm is finite. Shape is (1,)
"""
# collect gradient arrays
arrays = []
idx = 0
for p in parameters:
if p.grad_req != 'null':
p_grads = p.list_grad()
arrays.append(p_grads[idx % len(p_grads)])
idx += 1
assert len(arrays) > 0, 'No parameter found available for gradient norm.'
# compute gradient norms
def _norm(array):
# TODO(haibin) norm operator does not support fp16 safe reduction.
# Issue is tracked at: https://github.com/apache/incubator-mxnet/issues/14126
x = array.reshape((-1,)).astype('float32', copy=False)
return nd.dot(x, x)
norm_arrays = [_norm(arr) for arr in arrays]
# group norm arrays by ctx
def group_by_ctx(arr_list):
groups = collections.defaultdict(list)
for arr in arr_list:
ctx = arr.context
groups[ctx].append(arr)
return groups
norm_groups = group_by_ctx(norm_arrays)
# reduce
ctx, dtype = arrays[0].context, 'float32'
norms = [nd.add_n(*g).as_in_context(ctx) for g in norm_groups.values()]
total_norm = nd.add_n(*norms).sqrt()
scale = total_norm / max_norm
# is_finite = 0 if NaN or Inf, 1 otherwise.
is_finite = nd.contrib.isfinite(scale)
# if scale is finite, nd.maximum selects the max between scale and 1. That is,
# 1 is returned if total_norm does not exceed max_norm.
# if scale = NaN or Inf, the result of nd.minimum is undefined. Therefore, we use
# choices.take to return NaN or Inf.
scale_or_one = nd.maximum(nd.ones((1,), dtype=dtype, ctx=ctx), scale)
choices = nd.concat(scale, scale_or_one, dim=0)
chosen_scale = choices.take(is_finite)
return total_norm, chosen_scale, is_finite | 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_grads`` so that the gradients are summed first before calculating
the 2-norm.
.. note::
This function is only for use when `update_on_kvstore` is set to False in trainer.
Example::
trainer = Trainer(net.collect_params(), update_on_kvstore=False, ...)
for x, y in mx.gluon.utils.split_and_load(X, [mx.gpu(0), mx.gpu(1)]):
with mx.autograd.record():
y = net(x)
loss = loss_fn(y, label)
loss.backward()
trainer.allreduce_grads()
norm, ratio = grad_global_norm(net.collect_params().values(), max_norm)
trainer.update(batch_size * ratio)
...
Parameters
----------
parameters : list of Parameters
Returns
-------
NDArray
Total norm. Shape is (1,)
NDArray
Ratio for rescaling gradients based on max_norm s.t. grad = grad / ratio.
If total norm is NaN, ratio will be NaN, too. Shape is (1,)
NDArray
Whether the total norm is finite. Shape is (1,)
"""
# collect gradient arrays
arrays = []
idx = 0
for p in parameters:
if p.grad_req != 'null':
p_grads = p.list_grad()
arrays.append(p_grads[idx % len(p_grads)])
idx += 1
assert len(arrays) > 0, 'No parameter found available for gradient norm.'
# compute gradient norms
def _norm(array):
# TODO(haibin) norm operator does not support fp16 safe reduction.
# Issue is tracked at: https://github.com/apache/incubator-mxnet/issues/14126
x = array.reshape((-1,)).astype('float32', copy=False)
return nd.dot(x, x)
norm_arrays = [_norm(arr) for arr in arrays]
# group norm arrays by ctx
def group_by_ctx(arr_list):
groups = collections.defaultdict(list)
for arr in arr_list:
ctx = arr.context
groups[ctx].append(arr)
return groups
norm_groups = group_by_ctx(norm_arrays)
# reduce
ctx, dtype = arrays[0].context, 'float32'
norms = [nd.add_n(*g).as_in_context(ctx) for g in norm_groups.values()]
total_norm = nd.add_n(*norms).sqrt()
scale = total_norm / max_norm
# is_finite = 0 if NaN or Inf, 1 otherwise.
is_finite = nd.contrib.isfinite(scale)
# if scale is finite, nd.maximum selects the max between scale and 1. That is,
# 1 is returned if total_norm does not exceed max_norm.
# if scale = NaN or Inf, the result of nd.minimum is undefined. Therefore, we use
# choices.take to return NaN or Inf.
scale_or_one = nd.maximum(nd.ones((1,), dtype=dtype, ctx=ctx), scale)
choices = nd.concat(scale, scale_or_one, dim=0)
chosen_scale = choices.take(is_finite)
return total_norm, chosen_scale, is_finite | [
"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 calculating
the 2-norm.
.. note::
This function is only for use when `update_on_kvstore` is set to False in trainer.
Example::
trainer = Trainer(net.collect_params(), update_on_kvstore=False, ...)
for x, y in mx.gluon.utils.split_and_load(X, [mx.gpu(0), mx.gpu(1)]):
with mx.autograd.record():
y = net(x)
loss = loss_fn(y, label)
loss.backward()
trainer.allreduce_grads()
norm, ratio = grad_global_norm(net.collect_params().values(), max_norm)
trainer.update(batch_size * ratio)
...
Parameters
----------
parameters : list of Parameters
Returns
-------
NDArray
Total norm. Shape is (1,)
NDArray
Ratio for rescaling gradients based on max_norm s.t. grad = grad / ratio.
If total norm is NaN, ratio will be NaN, too. Shape is (1,)
NDArray
Whether the total norm is finite. Shape is (1,) | [
"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.isinf(grad).sum()
# NDArray is implicitly converted to bool
if is_not_finite == 0:
return False
else:
return True | 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.isinf(grad).sum()
# NDArray is implicitly converted to bool
if is_not_finite == 0:
return False
else:
return True | [
"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_rescale / float(iter_since_rescale)
# we tolerate a certrain amount of NaNs before actually scaling it down
if percentage >= self.tolerance:
self.loss_scale /= self.scale_factor
self._last_rescale_iter = self._num_steps
self._overflows_since_rescale = 0
logging.info('DynamicLossScaler: overflow detected. set loss_scale = %s',
self.loss_scale)
elif (self._num_steps - self._last_overflow_iter) % self.scale_window == 0:
self.loss_scale *= self.scale_factor
self._last_rescale_iter = self._num_steps
self._num_steps += 1 | 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_rescale / float(iter_since_rescale)
# we tolerate a certrain amount of NaNs before actually scaling it down
if percentage >= self.tolerance:
self.loss_scale /= self.scale_factor
self._last_rescale_iter = self._num_steps
self._overflows_since_rescale = 0
logging.info('DynamicLossScaler: overflow detected. set loss_scale = %s',
self.loss_scale)
elif (self._num_steps - self._last_overflow_iter) % self.scale_window == 0:
self.loss_scale *= self.scale_factor
self._last_rescale_iter = self._num_steps
self._num_steps += 1 | [
"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' \
' key={bucket_keys}\n' \
' cnt={bucket_counts}\n' \
' batch_size={bucket_batch_sizes}'\
.format(name=self.__class__.__name__,
sample_num=len(self._lengths),
batch_num=len(self._batch_infos),
bucket_keys=self._bucket_keys,
bucket_counts=[len(sample_ids) for sample_ids in self._bucket_sample_ids],
bucket_batch_sizes=self._bucket_batch_sizes)
return ret | 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' \
' key={bucket_keys}\n' \
' cnt={bucket_counts}\n' \
' batch_size={bucket_batch_sizes}'\
.format(name=self.__class__.__name__,
sample_num=len(self._lengths),
batch_num=len(self._batch_infos),
bucket_keys=self._bucket_keys,
bucket_counts=[len(sample_ids) for sample_ids in self._bucket_sample_ids],
bucket_batch_sizes=self._bucket_batch_sizes)
return ret | [
"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 = '%s.%s'%(args.save, format(epoch, '02d'))
if not os.path.exists(checkpoint_name):
print('Wait for a new checkpoint...')
# check again after 600 seconds
time.sleep(600)
continue
eval_model.load_parameters(checkpoint_name)
print('Loaded parameters from checkpoint %s'%(checkpoint_name))
start_epoch_time = time.time()
final_test_L = test(test_data, test_batch_size, ctx=context[0])
end_epoch_time = time.time()
print('[Epoch %d] test loss %.2f, test ppl %.2f'%
(epoch, final_test_L, math.exp(final_test_L)))
print('Epoch %d took %.2f seconds.'%(epoch, end_epoch_time - start_epoch_time))
sys.stdout.flush()
epoch += 1 | 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 = '%s.%s'%(args.save, format(epoch, '02d'))
if not os.path.exists(checkpoint_name):
print('Wait for a new checkpoint...')
# check again after 600 seconds
time.sleep(600)
continue
eval_model.load_parameters(checkpoint_name)
print('Loaded parameters from checkpoint %s'%(checkpoint_name))
start_epoch_time = time.time()
final_test_L = test(test_data, test_batch_size, ctx=context[0])
end_epoch_time = time.time()
print('[Epoch %d] test loss %.2f, test ppl %.2f'%
(epoch, final_test_L, math.exp(final_test_L)))
print('Epoch %d took %.2f seconds.'%(epoch, end_epoch_time - start_epoch_time))
sys.stdout.flush()
epoch += 1 | [
"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, vocab, max_len)
return vocab, max_len, output_size, train_dataset, train_data_lengths
else:
train_dataset, test_dataset, output_size = _load_file(data_name)
vocab, max_len = _build_vocab(data_name, train_dataset, test_dataset)
train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vocab, max_len)
test_dataset, test_data_lengths = _preprocess_dataset(test_dataset, vocab, max_len)
return vocab, max_len, output_size, train_dataset, train_data_lengths, test_dataset, \
test_data_lengths | 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, vocab, max_len)
return vocab, max_len, output_size, train_dataset, train_data_lengths
else:
train_dataset, test_dataset, output_size = _load_file(data_name)
vocab, max_len = _build_vocab(data_name, train_dataset, test_dataset)
train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vocab, max_len)
test_dataset, test_data_lengths = _preprocess_dataset(test_dataset, vocab, max_len)
return vocab, max_len, output_size, train_dataset, train_data_lengths, test_dataset, \
test_data_lengths | [
"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.max_num_examples]
# NOTE: assume data has been tokenized
dataset = gluon.data.SimpleDataset([(e[0], e[1], LABEL_TO_IDX[e[2]]) for e in examples])
dataset = dataset.transform(lambda s1, s2, label: (
['NULL'] + s1.lower().split(),
['NULL'] + s2.lower().split(), label),
lazy=False)
logger.info('read {} examples'.format(len(dataset)))
return dataset | 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.max_num_examples]
# NOTE: assume data has been tokenized
dataset = gluon.data.SimpleDataset([(e[0], e[1], LABEL_TO_IDX[e[2]]) for e in examples])
dataset = dataset.transform(lambda s1, s2, label: (
['NULL'] + s1.lower().split(),
['NULL'] + s2.lower().split(), label),
lazy=False)
logger.info('read {} examples'.format(len(dataset)))
return dataset | [
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.