repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.kernels_pull_cli | def kernels_pull_cli(self,
kernel,
kernel_opt=None,
path=None,
metadata=False):
""" client wrapper for kernels_pull
"""
kernel = kernel or kernel_opt
effective_path = self.kernels_pull(
... | python | def kernels_pull_cli(self,
kernel,
kernel_opt=None,
path=None,
metadata=False):
""" client wrapper for kernels_pull
"""
kernel = kernel or kernel_opt
effective_path = self.kernels_pull(
... | [
"def",
"kernels_pull_cli",
"(",
"self",
",",
"kernel",
",",
"kernel_opt",
"=",
"None",
",",
"path",
"=",
"None",
",",
"metadata",
"=",
"False",
")",
":",
"kernel",
"=",
"kernel",
"or",
"kernel_opt",
"effective_path",
"=",
"self",
".",
"kernels_pull",
"(",
... | client wrapper for kernels_pull | [
"client",
"wrapper",
"for",
"kernels_pull"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1965-L1978 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.kernels_output | def kernels_output(self, kernel, path, force=False, quiet=True):
""" retrieve output for a specified kernel
Parameters
==========
kernel: the kernel to output
path: the path to pull files to on the filesystem
force: if output already exists, force ove... | python | def kernels_output(self, kernel, path, force=False, quiet=True):
""" retrieve output for a specified kernel
Parameters
==========
kernel: the kernel to output
path: the path to pull files to on the filesystem
force: if output already exists, force ove... | [
"def",
"kernels_output",
"(",
"self",
",",
"kernel",
",",
"path",
",",
"force",
"=",
"False",
",",
"quiet",
"=",
"True",
")",
":",
"if",
"kernel",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'A kernel must be specified'",
")",
"if",
"'/'",
"in",
"ker... | retrieve output for a specified kernel
Parameters
==========
kernel: the kernel to output
path: the path to pull files to on the filesystem
force: if output already exists, force overwrite (default False)
quiet: suppress verbosity (default is True... | [
"retrieve",
"output",
"for",
"a",
"specified",
"kernel",
"Parameters",
"==========",
"kernel",
":",
"the",
"kernel",
"to",
"output",
"path",
":",
"the",
"path",
"to",
"pull",
"files",
"to",
"on",
"the",
"filesystem",
"force",
":",
"if",
"output",
"already",
... | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1980-L2036 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.kernels_output_cli | def kernels_output_cli(self,
kernel,
kernel_opt=None,
path=None,
force=False,
quiet=False):
""" client wrapper for kernels_output, with same arguments. Extra
argumen... | python | def kernels_output_cli(self,
kernel,
kernel_opt=None,
path=None,
force=False,
quiet=False):
""" client wrapper for kernels_output, with same arguments. Extra
argumen... | [
"def",
"kernels_output_cli",
"(",
"self",
",",
"kernel",
",",
"kernel_opt",
"=",
"None",
",",
"path",
"=",
"None",
",",
"force",
"=",
"False",
",",
"quiet",
"=",
"False",
")",
":",
"kernel",
"=",
"kernel",
"or",
"kernel_opt",
"self",
".",
"kernels_output... | client wrapper for kernels_output, with same arguments. Extra
arguments are described below, and see kernels_output for others.
Parameters
==========
kernel_opt: option from client instead of kernel, if not defined | [
"client",
"wrapper",
"for",
"kernels_output",
"with",
"same",
"arguments",
".",
"Extra",
"arguments",
"are",
"described",
"below",
"and",
"see",
"kernels_output",
"for",
"others",
".",
"Parameters",
"==========",
"kernel_opt",
":",
"option",
"from",
"client",
"ins... | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2038-L2051 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.kernels_status | def kernels_status(self, kernel):
""" call to the api to get the status of a kernel.
Parameters
==========
kernel: the kernel to get the status for
"""
if kernel is None:
raise ValueError('A kernel must be specified')
if '/' in kernel:
... | python | def kernels_status(self, kernel):
""" call to the api to get the status of a kernel.
Parameters
==========
kernel: the kernel to get the status for
"""
if kernel is None:
raise ValueError('A kernel must be specified')
if '/' in kernel:
... | [
"def",
"kernels_status",
"(",
"self",
",",
"kernel",
")",
":",
"if",
"kernel",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'A kernel must be specified'",
")",
"if",
"'/'",
"in",
"kernel",
":",
"self",
".",
"validate_kernel_string",
"(",
"kernel",
")",
"k... | call to the api to get the status of a kernel.
Parameters
==========
kernel: the kernel to get the status for | [
"call",
"to",
"the",
"api",
"to",
"get",
"the",
"status",
"of",
"a",
"kernel",
".",
"Parameters",
"==========",
"kernel",
":",
"the",
"kernel",
"to",
"get",
"the",
"status",
"for"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2053-L2071 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.kernels_status_cli | def kernels_status_cli(self, kernel, kernel_opt=None):
""" client wrapper for kernel_status
Parameters
==========
kernel_opt: additional option from the client, if kernel not defined
"""
kernel = kernel or kernel_opt
response = self.kernels_status(ker... | python | def kernels_status_cli(self, kernel, kernel_opt=None):
""" client wrapper for kernel_status
Parameters
==========
kernel_opt: additional option from the client, if kernel not defined
"""
kernel = kernel or kernel_opt
response = self.kernels_status(ker... | [
"def",
"kernels_status_cli",
"(",
"self",
",",
"kernel",
",",
"kernel_opt",
"=",
"None",
")",
":",
"kernel",
"=",
"kernel",
"or",
"kernel_opt",
"response",
"=",
"self",
".",
"kernels_status",
"(",
"kernel",
")",
"status",
"=",
"response",
"[",
"'status'",
... | client wrapper for kernel_status
Parameters
==========
kernel_opt: additional option from the client, if kernel not defined | [
"client",
"wrapper",
"for",
"kernel_status",
"Parameters",
"==========",
"kernel_opt",
":",
"additional",
"option",
"from",
"the",
"client",
"if",
"kernel",
"not",
"defined"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2073-L2087 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.download_needed | def download_needed(self, response, outfile, quiet=True):
""" determine if a download is needed based on timestamp. Return True
if needed (remote is newer) or False if local is newest.
Parameters
==========
response: the response from the API
outfile:... | python | def download_needed(self, response, outfile, quiet=True):
""" determine if a download is needed based on timestamp. Return True
if needed (remote is newer) or False if local is newest.
Parameters
==========
response: the response from the API
outfile:... | [
"def",
"download_needed",
"(",
"self",
",",
"response",
",",
"outfile",
",",
"quiet",
"=",
"True",
")",
":",
"try",
":",
"remote_date",
"=",
"datetime",
".",
"strptime",
"(",
"response",
".",
"headers",
"[",
"'Last-Modified'",
"]",
",",
"'%a, %d %b %Y %X %Z'... | determine if a download is needed based on timestamp. Return True
if needed (remote is newer) or False if local is newest.
Parameters
==========
response: the response from the API
outfile: the output file to write to
quiet: suppress verbose outpu... | [
"determine",
"if",
"a",
"download",
"is",
"needed",
"based",
"on",
"timestamp",
".",
"Return",
"True",
"if",
"needed",
"(",
"remote",
"is",
"newer",
")",
"or",
"False",
"if",
"local",
"is",
"newest",
".",
"Parameters",
"==========",
"response",
":",
"the",... | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2089-L2111 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.print_table | def print_table(self, items, fields):
""" print a table of items, for a set of fields defined
Parameters
==========
items: a list of items to print
fields: a list of fields to select from items
"""
formats = []
borders = []
for f i... | python | def print_table(self, items, fields):
""" print a table of items, for a set of fields defined
Parameters
==========
items: a list of items to print
fields: a list of fields to select from items
"""
formats = []
borders = []
for f i... | [
"def",
"print_table",
"(",
"self",
",",
"items",
",",
"fields",
")",
":",
"formats",
"=",
"[",
"]",
"borders",
"=",
"[",
"]",
"for",
"f",
"in",
"fields",
":",
"length",
"=",
"max",
"(",
"len",
"(",
"f",
")",
",",
"max",
"(",
"[",
"len",
"(",
... | print a table of items, for a set of fields defined
Parameters
==========
items: a list of items to print
fields: a list of fields to select from items | [
"print",
"a",
"table",
"of",
"items",
"for",
"a",
"set",
"of",
"fields",
"defined"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2113-L2139 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.print_csv | def print_csv(self, items, fields):
""" print a set of fields in a set of items using a csv.writer
Parameters
==========
items: a list of items to print
fields: a list of fields to select from items
"""
writer = csv.writer(sys.stdout)
writ... | python | def print_csv(self, items, fields):
""" print a set of fields in a set of items using a csv.writer
Parameters
==========
items: a list of items to print
fields: a list of fields to select from items
"""
writer = csv.writer(sys.stdout)
writ... | [
"def",
"print_csv",
"(",
"self",
",",
"items",
",",
"fields",
")",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"sys",
".",
"stdout",
")",
"writer",
".",
"writerow",
"(",
"fields",
")",
"for",
"i",
"in",
"items",
":",
"i_fields",
"=",
"[",
"self"... | print a set of fields in a set of items using a csv.writer
Parameters
==========
items: a list of items to print
fields: a list of fields to select from items | [
"print",
"a",
"set",
"of",
"fields",
"in",
"a",
"set",
"of",
"items",
"using",
"a",
"csv",
".",
"writer"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2141-L2153 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.process_response | def process_response(self, result):
""" process a response from the API. We check the API version against
the client's to see if it's old, and give them a warning (once)
Parameters
==========
result: the result from the API
"""
if len(result) == 3... | python | def process_response(self, result):
""" process a response from the API. We check the API version against
the client's to see if it's old, and give them a warning (once)
Parameters
==========
result: the result from the API
"""
if len(result) == 3... | [
"def",
"process_response",
"(",
"self",
",",
"result",
")",
":",
"if",
"len",
"(",
"result",
")",
"==",
"3",
":",
"data",
"=",
"result",
"[",
"0",
"]",
"headers",
"=",
"result",
"[",
"2",
"]",
"if",
"self",
".",
"HEADER_API_VERSION",
"in",
"headers",... | process a response from the API. We check the API version against
the client's to see if it's old, and give them a warning (once)
Parameters
==========
result: the result from the API | [
"process",
"a",
"response",
"from",
"the",
"API",
".",
"We",
"check",
"the",
"API",
"version",
"against",
"the",
"client",
"s",
"to",
"see",
"if",
"it",
"s",
"old",
"and",
"give",
"them",
"a",
"warning",
"(",
"once",
")"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2181-L2201 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.is_up_to_date | def is_up_to_date(self, server_version):
""" determine if a client (on the local user's machine) is up to date
with the version provided on the server. Return a boolean with True
or False
Parameters
==========
server_version: the server version string... | python | def is_up_to_date(self, server_version):
""" determine if a client (on the local user's machine) is up to date
with the version provided on the server. Return a boolean with True
or False
Parameters
==========
server_version: the server version string... | [
"def",
"is_up_to_date",
"(",
"self",
",",
"server_version",
")",
":",
"client_split",
"=",
"self",
".",
"__version__",
".",
"split",
"(",
"'.'",
")",
"client_len",
"=",
"len",
"(",
"client_split",
")",
"server_split",
"=",
"server_version",
".",
"split",
"("... | determine if a client (on the local user's machine) is up to date
with the version provided on the server. Return a boolean with True
or False
Parameters
==========
server_version: the server version string to compare to the host | [
"determine",
"if",
"a",
"client",
"(",
"on",
"the",
"local",
"user",
"s",
"machine",
")",
"is",
"up",
"to",
"date",
"with",
"the",
"version",
"provided",
"on",
"the",
"server",
".",
"Return",
"a",
"boolean",
"with",
"True",
"or",
"False",
"Parameters",
... | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2203-L2233 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.upload_files | def upload_files(self,
request,
resources,
folder,
quiet=False,
dir_mode='skip'):
""" upload files in a folder
Parameters
==========
request: the prepared request
... | python | def upload_files(self,
request,
resources,
folder,
quiet=False,
dir_mode='skip'):
""" upload files in a folder
Parameters
==========
request: the prepared request
... | [
"def",
"upload_files",
"(",
"self",
",",
"request",
",",
"resources",
",",
"folder",
",",
"quiet",
"=",
"False",
",",
"dir_mode",
"=",
"'skip'",
")",
":",
"for",
"file_name",
"in",
"os",
".",
"listdir",
"(",
"folder",
")",
":",
"if",
"(",
"file_name",
... | upload files in a folder
Parameters
==========
request: the prepared request
resources: the files to upload
folder: the folder to upload from
quiet: suppress verbose output (default is False) | [
"upload",
"files",
"in",
"a",
"folder",
"Parameters",
"==========",
"request",
":",
"the",
"prepared",
"request",
"resources",
":",
"the",
"files",
"to",
"upload",
"folder",
":",
"the",
"folder",
"to",
"upload",
"from",
"quiet",
":",
"suppress",
"verbose",
"... | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2235-L2282 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi._upload_file | def _upload_file(self, file_name, full_path, quiet, request, resources):
""" Helper function to upload a single file
Parameters
==========
file_name: name of the file to upload
full_path: path to the file to upload
request: the prepared request
... | python | def _upload_file(self, file_name, full_path, quiet, request, resources):
""" Helper function to upload a single file
Parameters
==========
file_name: name of the file to upload
full_path: path to the file to upload
request: the prepared request
... | [
"def",
"_upload_file",
"(",
"self",
",",
"file_name",
",",
"full_path",
",",
"quiet",
",",
"request",
",",
"resources",
")",
":",
"if",
"not",
"quiet",
":",
"print",
"(",
"'Starting upload for file '",
"+",
"file_name",
")",
"content_length",
"=",
"os",
".",... | Helper function to upload a single file
Parameters
==========
file_name: name of the file to upload
full_path: path to the file to upload
request: the prepared request
resources: optional file metadata
quiet: suppress verbose output
... | [
"Helper",
"function",
"to",
"upload",
"a",
"single",
"file",
"Parameters",
"==========",
"file_name",
":",
"name",
"of",
"the",
"file",
"to",
"upload",
"full_path",
":",
"path",
"to",
"the",
"file",
"to",
"upload",
"request",
":",
"the",
"prepared",
"request... | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2284-L2325 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.process_column | def process_column(self, column):
""" process a column, check for the type, and return the processed
column
Parameters
==========
column: a list of values in a column to be processed
"""
processed_column = DatasetColumn(
name=self.get_... | python | def process_column(self, column):
""" process a column, check for the type, and return the processed
column
Parameters
==========
column: a list of values in a column to be processed
"""
processed_column = DatasetColumn(
name=self.get_... | [
"def",
"process_column",
"(",
"self",
",",
"column",
")",
":",
"processed_column",
"=",
"DatasetColumn",
"(",
"name",
"=",
"self",
".",
"get_or_fail",
"(",
"column",
",",
"'name'",
")",
",",
"description",
"=",
"self",
".",
"get_or_default",
"(",
"column",
... | process a column, check for the type, and return the processed
column
Parameters
==========
column: a list of values in a column to be processed | [
"process",
"a",
"column",
"check",
"for",
"the",
"type",
"and",
"return",
"the",
"processed",
"column",
"Parameters",
"==========",
"column",
":",
"a",
"list",
"of",
"values",
"in",
"a",
"column",
"to",
"be",
"processed"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2327-L2357 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.upload_complete | def upload_complete(self, path, url, quiet):
""" function to complete an upload to retrieve a path from a url
Parameters
==========
path: the path for the upload that is read in
url: the url to send the POST to
quiet: suppress verbose output (default ... | python | def upload_complete(self, path, url, quiet):
""" function to complete an upload to retrieve a path from a url
Parameters
==========
path: the path for the upload that is read in
url: the url to send the POST to
quiet: suppress verbose output (default ... | [
"def",
"upload_complete",
"(",
"self",
",",
"path",
",",
"url",
",",
"quiet",
")",
":",
"file_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"path",
")",
"try",
":",
"with",
"tqdm",
"(",
"total",
"=",
"file_size",
",",
"unit",
"=",
"'B'",
",",... | function to complete an upload to retrieve a path from a url
Parameters
==========
path: the path for the upload that is read in
url: the url to send the POST to
quiet: suppress verbose output (default is False) | [
"function",
"to",
"complete",
"an",
"upload",
"to",
"retrieve",
"a",
"path",
"from",
"a",
"url",
"Parameters",
"==========",
"path",
":",
"the",
"path",
"for",
"the",
"upload",
"that",
"is",
"read",
"in",
"url",
":",
"the",
"url",
"to",
"send",
"the",
... | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2359-L2386 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.validate_dataset_string | def validate_dataset_string(self, dataset):
""" determine if a dataset string is valid, meaning it is in the format
of {username}/{dataset-slug}.
Parameters
==========
dataset: the dataset name to validate
"""
if dataset:
if '/' not in... | python | def validate_dataset_string(self, dataset):
""" determine if a dataset string is valid, meaning it is in the format
of {username}/{dataset-slug}.
Parameters
==========
dataset: the dataset name to validate
"""
if dataset:
if '/' not in... | [
"def",
"validate_dataset_string",
"(",
"self",
",",
"dataset",
")",
":",
"if",
"dataset",
":",
"if",
"'/'",
"not",
"in",
"dataset",
":",
"raise",
"ValueError",
"(",
"'Dataset must be specified in the form of '",
"'\\'{username}/{dataset-slug}\\''",
")",
"split",
"=",
... | determine if a dataset string is valid, meaning it is in the format
of {username}/{dataset-slug}.
Parameters
==========
dataset: the dataset name to validate | [
"determine",
"if",
"a",
"dataset",
"string",
"is",
"valid",
"meaning",
"it",
"is",
"in",
"the",
"format",
"of",
"{",
"username",
"}",
"/",
"{",
"dataset",
"-",
"slug",
"}",
".",
"Parameters",
"==========",
"dataset",
":",
"the",
"dataset",
"name",
"to",
... | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2388-L2402 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.validate_kernel_string | def validate_kernel_string(self, kernel):
""" determine if a kernel string is valid, meaning it is in the format
of {username}/{kernel-slug}.
Parameters
==========
kernel: the kernel name to validate
"""
if kernel:
if '/' not in kernel... | python | def validate_kernel_string(self, kernel):
""" determine if a kernel string is valid, meaning it is in the format
of {username}/{kernel-slug}.
Parameters
==========
kernel: the kernel name to validate
"""
if kernel:
if '/' not in kernel... | [
"def",
"validate_kernel_string",
"(",
"self",
",",
"kernel",
")",
":",
"if",
"kernel",
":",
"if",
"'/'",
"not",
"in",
"kernel",
":",
"raise",
"ValueError",
"(",
"'Kernel must be specified in the form of '",
"'\\'{username}/{kernel-slug}\\''",
")",
"split",
"=",
"ker... | determine if a kernel string is valid, meaning it is in the format
of {username}/{kernel-slug}.
Parameters
==========
kernel: the kernel name to validate | [
"determine",
"if",
"a",
"kernel",
"string",
"is",
"valid",
"meaning",
"it",
"is",
"in",
"the",
"format",
"of",
"{",
"username",
"}",
"/",
"{",
"kernel",
"-",
"slug",
"}",
".",
"Parameters",
"==========",
"kernel",
":",
"the",
"kernel",
"name",
"to",
"v... | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2404-L2423 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.validate_resources | def validate_resources(self, folder, resources):
""" validate resources is a wrapper to validate the existence of files
and that there are no duplicates for a folder and set of resources.
Parameters
==========
folder: the folder to validate
resources:... | python | def validate_resources(self, folder, resources):
""" validate resources is a wrapper to validate the existence of files
and that there are no duplicates for a folder and set of resources.
Parameters
==========
folder: the folder to validate
resources:... | [
"def",
"validate_resources",
"(",
"self",
",",
"folder",
",",
"resources",
")",
":",
"self",
".",
"validate_files_exist",
"(",
"folder",
",",
"resources",
")",
"self",
".",
"validate_no_duplicate_paths",
"(",
"resources",
")"
] | validate resources is a wrapper to validate the existence of files
and that there are no duplicates for a folder and set of resources.
Parameters
==========
folder: the folder to validate
resources: one or more resources to validate within the folder | [
"validate",
"resources",
"is",
"a",
"wrapper",
"to",
"validate",
"the",
"existence",
"of",
"files",
"and",
"that",
"there",
"are",
"no",
"duplicates",
"for",
"a",
"folder",
"and",
"set",
"of",
"resources",
"."
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2425-L2435 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.validate_files_exist | def validate_files_exist(self, folder, resources):
""" ensure that one or more resource files exist in a folder
Parameters
==========
folder: the folder to validate
resources: one or more resources to validate within the folder
"""
for item in res... | python | def validate_files_exist(self, folder, resources):
""" ensure that one or more resource files exist in a folder
Parameters
==========
folder: the folder to validate
resources: one or more resources to validate within the folder
"""
for item in res... | [
"def",
"validate_files_exist",
"(",
"self",
",",
"folder",
",",
"resources",
")",
":",
"for",
"item",
"in",
"resources",
":",
"file_name",
"=",
"item",
".",
"get",
"(",
"'path'",
")",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
","... | ensure that one or more resource files exist in a folder
Parameters
==========
folder: the folder to validate
resources: one or more resources to validate within the folder | [
"ensure",
"that",
"one",
"or",
"more",
"resource",
"files",
"exist",
"in",
"a",
"folder"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2437-L2449 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.validate_no_duplicate_paths | def validate_no_duplicate_paths(self, resources):
""" ensure that the user has not provided duplicate paths in
a list of resources.
Parameters
==========
resources: one or more resources to validate not duplicated
"""
paths = set()
for ite... | python | def validate_no_duplicate_paths(self, resources):
""" ensure that the user has not provided duplicate paths in
a list of resources.
Parameters
==========
resources: one or more resources to validate not duplicated
"""
paths = set()
for ite... | [
"def",
"validate_no_duplicate_paths",
"(",
"self",
",",
"resources",
")",
":",
"paths",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"resources",
":",
"file_name",
"=",
"item",
".",
"get",
"(",
"'path'",
")",
"if",
"file_name",
"in",
"paths",
":",
"raise",... | ensure that the user has not provided duplicate paths in
a list of resources.
Parameters
==========
resources: one or more resources to validate not duplicated | [
"ensure",
"that",
"the",
"user",
"has",
"not",
"provided",
"duplicate",
"paths",
"in",
"a",
"list",
"of",
"resources",
"."
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2451-L2466 | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | KaggleApi.convert_to_dataset_file_metadata | def convert_to_dataset_file_metadata(self, file_data, path):
""" convert a set of file_data to a metadata file at path
Parameters
==========
file_data: a dictionary of file data to write to file
path: the path to write the metadata to
"""
as_metad... | python | def convert_to_dataset_file_metadata(self, file_data, path):
""" convert a set of file_data to a metadata file at path
Parameters
==========
file_data: a dictionary of file data to write to file
path: the path to write the metadata to
"""
as_metad... | [
"def",
"convert_to_dataset_file_metadata",
"(",
"self",
",",
"file_data",
",",
"path",
")",
":",
"as_metadata",
"=",
"{",
"'path'",
":",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"file_data",
"[",
"'name'",
"]",
")",
",",
"'description'",
":",
"f... | convert a set of file_data to a metadata file at path
Parameters
==========
file_data: a dictionary of file data to write to file
path: the path to write the metadata to | [
"convert",
"a",
"set",
"of",
"file_data",
"to",
"a",
"metadata",
"file",
"at",
"path"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2468-L2493 | train |
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 | train |
Kaggle/kaggle-api | kaggle/api_client.py | ApiClient.parameters_to_tuples | def parameters_to_tuples(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collection... | python | def parameters_to_tuples(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collection... | [
"def",
"parameters_to_tuples",
"(",
"self",
",",
"params",
",",
"collection_formats",
")",
":",
"new_params",
"=",
"[",
"]",
"if",
"collection_formats",
"is",
"None",
":",
"collection_formats",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iterit... | Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collections formatted | [
"Get",
"parameters",
"as",
"list",
"of",
"tuples",
"formatting",
"collections",
"."
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api_client.py#L407-L435 | train |
Kaggle/kaggle-api | kaggle/api_client.py | ApiClient.prepare_post_parameters | def prepare_post_parameters(self, post_params=None, files=None):
"""Builds form parameters.
:param post_params: Normal form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = []
if post_params:
params = post_... | python | def prepare_post_parameters(self, post_params=None, files=None):
"""Builds form parameters.
:param post_params: Normal form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = []
if post_params:
params = post_... | [
"def",
"prepare_post_parameters",
"(",
"self",
",",
"post_params",
"=",
"None",
",",
"files",
"=",
"None",
")",
":",
"params",
"=",
"[",
"]",
"if",
"post_params",
":",
"params",
"=",
"post_params",
"if",
"files",
":",
"for",
"k",
",",
"v",
"in",
"six",... | Builds form parameters.
:param post_params: Normal form parameters.
:param files: File parameters.
:return: Form parameters with files. | [
"Builds",
"form",
"parameters",
"."
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api_client.py#L437-L463 | train |
Kaggle/kaggle-api | kaggle/api_client.py | ApiClient.__deserialize_file | def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path.
"""
fd, path = t... | python | def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path.
"""
fd, path = t... | [
"def",
"__deserialize_file",
"(",
"self",
",",
"response",
")",
":",
"fd",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"dir",
"=",
"self",
".",
"configuration",
".",
"temp_folder_path",
")",
"os",
".",
"close",
"(",
"fd",
")",
"os",
".",
"remove... | Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path. | [
"Deserializes",
"body",
"to",
"file"
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api_client.py#L521-L543 | train |
Kaggle/kaggle-api | kaggle/api_client.py | ApiClient.__deserialize_primitive | def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return s... | python | def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return s... | [
"def",
"__deserialize_primitive",
"(",
"self",
",",
"data",
",",
"klass",
")",
":",
"try",
":",
"return",
"klass",
"(",
"data",
")",
"except",
"UnicodeEncodeError",
":",
"return",
"six",
".",
"text_type",
"(",
"data",
")",
"except",
"TypeError",
":",
"retu... | Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool. | [
"Deserializes",
"string",
"to",
"primitive",
"type",
"."
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api_client.py#L545-L558 | train |
Kaggle/kaggle-api | kaggle/configuration.py | Configuration.logger_file | def logger_file(self, value):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
self.__logger_file = value
... | python | def logger_file(self, value):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
self.__logger_file = value
... | [
"def",
"logger_file",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"__logger_file",
"=",
"value",
"if",
"self",
".",
"__logger_file",
":",
"# If set logging file,",
"# then add file handler and remove stream handler.",
"self",
".",
"logger_file_handler",
"=",
"lo... | The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str | [
"The",
"logger",
"file",
"."
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/configuration.py#L133-L160 | train |
Kaggle/kaggle-api | kaggle/models/dataset_new_request.py | DatasetNewRequest.license_name | def license_name(self, license_name):
"""Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str
"""
allowed_values = ... | python | def license_name(self, license_name):
"""Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str
"""
allowed_values = ... | [
"def",
"license_name",
"(",
"self",
",",
"license_name",
")",
":",
"allowed_values",
"=",
"[",
"\"CC0-1.0\"",
",",
"\"CC-BY-SA-4.0\"",
",",
"\"GPL-2.0\"",
",",
"\"ODbL-1.0\"",
",",
"\"CC-BY-NC-SA-4.0\"",
",",
"\"unknown\"",
",",
"\"DbCL-1.0\"",
",",
"\"CC-BY-SA-3.0\... | Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str | [
"Sets",
"the",
"license_name",
"of",
"this",
"DatasetNewRequest",
"."
] | 65f14b1386470c5784d4753e491478e7537660d9 | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/models/dataset_new_request.py#L194-L209 | train |
dmlc/gluon-nlp | scripts/sentiment_analysis/sentiment_analysis_cnn.py | train | def train(net, train_data, test_data):
"""Train textCNN model for sentiment analysis."""
start_pipeline_time = time.time()
net, trainer = text_cnn.init(net, vocab, args.model_mode, context, args.lr)
random.shuffle(train_data)
sp = int(len(train_data)*0.9)
train_dataloader = DataLoader(dataset=tr... | python | def train(net, train_data, test_data):
"""Train textCNN model for sentiment analysis."""
start_pipeline_time = time.time()
net, trainer = text_cnn.init(net, vocab, args.model_mode, context, args.lr)
random.shuffle(train_data)
sp = int(len(train_data)*0.9)
train_dataloader = DataLoader(dataset=tr... | [
"def",
"train",
"(",
"net",
",",
"train_data",
",",
"test_data",
")",
":",
"start_pipeline_time",
"=",
"time",
".",
"time",
"(",
")",
"net",
",",
"trainer",
"=",
"text_cnn",
".",
"init",
"(",
"net",
",",
"vocab",
",",
"args",
".",
"model_mode",
",",
... | Train textCNN model for sentiment analysis. | [
"Train",
"textCNN",
"model",
"for",
"sentiment",
"analysis",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/sentiment_analysis_cnn.py#L114-L184 | train |
dmlc/gluon-nlp | scripts/bert/embedding.py | BertEmbedding.embedding | def embedding(self, sentences, oov_way='avg'):
"""
Get tokens, tokens embedding
Parameters
----------
sentences : List[str]
sentences for encoding.
oov_way : str, default avg.
use **avg**, **sum** or **last** to get token embedding for those out o... | python | def embedding(self, sentences, oov_way='avg'):
"""
Get tokens, tokens embedding
Parameters
----------
sentences : List[str]
sentences for encoding.
oov_way : str, default avg.
use **avg**, **sum** or **last** to get token embedding for those out o... | [
"def",
"embedding",
"(",
"self",
",",
"sentences",
",",
"oov_way",
"=",
"'avg'",
")",
":",
"data_iter",
"=",
"self",
".",
"data_loader",
"(",
"sentences",
"=",
"sentences",
")",
"batches",
"=",
"[",
"]",
"for",
"token_ids",
",",
"valid_length",
",",
"tok... | Get tokens, tokens embedding
Parameters
----------
sentences : List[str]
sentences for encoding.
oov_way : str, default avg.
use **avg**, **sum** or **last** to get token embedding for those out of
vocabulary words
Returns
-------
... | [
"Get",
"tokens",
"tokens",
"embedding"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/embedding.py#L111-L139 | train |
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 | train |
dmlc/gluon-nlp | scripts/bert/embedding.py | BertEmbedding.oov | def oov(self, batches, oov_way='avg'):
"""
How to handle oov. Also filter out [CLS], [SEP] tokens.
Parameters
----------
batches : List[(tokens_id,
sequence_outputs,
pooled_output].
batch token_ids (max_seq_length, ),... | python | def oov(self, batches, oov_way='avg'):
"""
How to handle oov. Also filter out [CLS], [SEP] tokens.
Parameters
----------
batches : List[(tokens_id,
sequence_outputs,
pooled_output].
batch token_ids (max_seq_length, ),... | [
"def",
"oov",
"(",
"self",
",",
"batches",
",",
"oov_way",
"=",
"'avg'",
")",
":",
"sentences",
"=",
"[",
"]",
"for",
"token_ids",
",",
"sequence_outputs",
"in",
"batches",
":",
"tokens",
"=",
"[",
"]",
"tensors",
"=",
"[",
"]",
"oov_len",
"=",
"1",
... | How to handle oov. Also filter out [CLS], [SEP] tokens.
Parameters
----------
batches : List[(tokens_id,
sequence_outputs,
pooled_output].
batch token_ids (max_seq_length, ),
sequence_outputs (max_seq_length, dim,... | [
"How",
"to",
"handle",
"oov",
".",
"Also",
"filter",
"out",
"[",
"CLS",
"]",
"[",
"SEP",
"]",
"tokens",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/embedding.py#L146-L198 | train |
dmlc/gluon-nlp | src/gluonnlp/model/bert.py | get_bert_model | def get_bert_model(model_name=None, dataset_name=None, vocab=None,
pretrained=True, ctx=mx.cpu(),
use_pooler=True, use_decoder=True, use_classifier=True,
output_attention=False, output_all_encodings=False,
root=os.path.join(get_home_dir(), 'mod... | python | def get_bert_model(model_name=None, dataset_name=None, vocab=None,
pretrained=True, ctx=mx.cpu(),
use_pooler=True, use_decoder=True, use_classifier=True,
output_attention=False, output_all_encodings=False,
root=os.path.join(get_home_dir(), 'mod... | [
"def",
"get_bert_model",
"(",
"model_name",
"=",
"None",
",",
"dataset_name",
"=",
"None",
",",
"vocab",
"=",
"None",
",",
"pretrained",
"=",
"True",
",",
"ctx",
"=",
"mx",
".",
"cpu",
"(",
")",
",",
"use_pooler",
"=",
"True",
",",
"use_decoder",
"=",
... | Any BERT pretrained model.
Parameters
----------
model_name : str or None, default None
Options include 'bert_24_1024_16' and 'bert_12_768_12'.
dataset_name : str or None, default None
Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased'
for both bert_24_10... | [
"Any",
"BERT",
"pretrained",
"model",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L630-L709 | train |
dmlc/gluon-nlp | src/gluonnlp/model/bert.py | BERTLayerNorm.hybrid_forward | def hybrid_forward(self, F, data, gamma, beta):
"""forward computation."""
# TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at:
# https://github.com/apache/incubator-mxnet/issues/14073
if self._dtype:
data = data.astype('float32')
g... | python | def hybrid_forward(self, F, data, gamma, beta):
"""forward computation."""
# TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at:
# https://github.com/apache/incubator-mxnet/issues/14073
if self._dtype:
data = data.astype('float32')
g... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"data",
",",
"gamma",
",",
"beta",
")",
":",
"# TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at:",
"# https://github.com/apache/incubator-mxnet/issues/14073",
"if",
"self",
".",
"_dtype",
"... | forward computation. | [
"forward",
"computation",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L59-L70 | train |
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 | train |
dmlc/gluon-nlp | src/gluonnlp/model/bert.py | BERTModel._get_decoder | def _get_decoder(self, units, vocab_size, embed, prefix):
""" Construct a decoder for the masked language model task """
with self.name_scope():
decoder = nn.HybridSequential(prefix=prefix)
decoder.add(nn.Dense(units, flatten=False))
decoder.add(GELU())
de... | python | def _get_decoder(self, units, vocab_size, embed, prefix):
""" Construct a decoder for the masked language model task """
with self.name_scope():
decoder = nn.HybridSequential(prefix=prefix)
decoder.add(nn.Dense(units, flatten=False))
decoder.add(GELU())
de... | [
"def",
"_get_decoder",
"(",
"self",
",",
"units",
",",
"vocab_size",
",",
"embed",
",",
"prefix",
")",
":",
"with",
"self",
".",
"name_scope",
"(",
")",
":",
"decoder",
"=",
"nn",
".",
"HybridSequential",
"(",
"prefix",
"=",
"prefix",
")",
"decoder",
"... | Construct a decoder for the masked language model task | [
"Construct",
"a",
"decoder",
"for",
"the",
"masked",
"language",
"model",
"task"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L370-L380 | train |
dmlc/gluon-nlp | src/gluonnlp/model/bert.py | BERTModel._get_embed | def _get_embed(self, embed, vocab_size, embed_size, initializer, dropout, prefix):
""" Construct an embedding block. """
if embed is None:
assert embed_size is not None, '"embed_size" cannot be None if "word_embed" or ' \
'token_type_embed is not gi... | python | def _get_embed(self, embed, vocab_size, embed_size, initializer, dropout, prefix):
""" Construct an embedding block. """
if embed is None:
assert embed_size is not None, '"embed_size" cannot be None if "word_embed" or ' \
'token_type_embed is not gi... | [
"def",
"_get_embed",
"(",
"self",
",",
"embed",
",",
"vocab_size",
",",
"embed_size",
",",
"initializer",
",",
"dropout",
",",
"prefix",
")",
":",
"if",
"embed",
"is",
"None",
":",
"assert",
"embed_size",
"is",
"not",
"None",
",",
"'\"embed_size\" cannot be ... | Construct an embedding block. | [
"Construct",
"an",
"embedding",
"block",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L382-L395 | train |
dmlc/gluon-nlp | src/gluonnlp/model/bert.py | BERTModel._get_pooler | def _get_pooler(self, units, prefix):
""" Construct pooler.
The pooler slices and projects the hidden output of first token
in the sequence for segment level classification.
"""
with self.name_scope():
pooler = nn.Dense(units=units, flatten=False, activation='tanh',... | python | def _get_pooler(self, units, prefix):
""" Construct pooler.
The pooler slices and projects the hidden output of first token
in the sequence for segment level classification.
"""
with self.name_scope():
pooler = nn.Dense(units=units, flatten=False, activation='tanh',... | [
"def",
"_get_pooler",
"(",
"self",
",",
"units",
",",
"prefix",
")",
":",
"with",
"self",
".",
"name_scope",
"(",
")",
":",
"pooler",
"=",
"nn",
".",
"Dense",
"(",
"units",
"=",
"units",
",",
"flatten",
"=",
"False",
",",
"activation",
"=",
"'tanh'",... | Construct pooler.
The pooler slices and projects the hidden output of first token
in the sequence for segment level classification. | [
"Construct",
"pooler",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L397-L407 | train |
dmlc/gluon-nlp | src/gluonnlp/model/bert.py | BERTModel._encode_sequence | def _encode_sequence(self, inputs, token_types, valid_length=None):
"""Generate the representation given the input sequences.
This is used for pre-training or fine-tuning a BERT model.
"""
# embedding
word_embedding = self.word_embed(inputs)
type_embedding = self.token_t... | python | def _encode_sequence(self, inputs, token_types, valid_length=None):
"""Generate the representation given the input sequences.
This is used for pre-training or fine-tuning a BERT model.
"""
# embedding
word_embedding = self.word_embed(inputs)
type_embedding = self.token_t... | [
"def",
"_encode_sequence",
"(",
"self",
",",
"inputs",
",",
"token_types",
",",
"valid_length",
"=",
"None",
")",
":",
"# embedding",
"word_embedding",
"=",
"self",
".",
"word_embed",
"(",
"inputs",
")",
"type_embedding",
"=",
"self",
".",
"token_type_embed",
... | Generate the representation given the input sequences.
This is used for pre-training or fine-tuning a BERT model. | [
"Generate",
"the",
"representation",
"given",
"the",
"input",
"sequences",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L440-L451 | train |
dmlc/gluon-nlp | src/gluonnlp/model/bert.py | BERTModel._decode | def _decode(self, sequence, masked_positions):
"""Generate unnormalized prediction for the masked language model task.
This is only used for pre-training the BERT model.
Inputs:
- **sequence**: input tensor of sequence encodings.
Shape (batch_size, seq_length, units).... | python | def _decode(self, sequence, masked_positions):
"""Generate unnormalized prediction for the masked language model task.
This is only used for pre-training the BERT model.
Inputs:
- **sequence**: input tensor of sequence encodings.
Shape (batch_size, seq_length, units).... | [
"def",
"_decode",
"(",
"self",
",",
"sequence",
",",
"masked_positions",
")",
":",
"batch_size",
"=",
"sequence",
".",
"shape",
"[",
"0",
"]",
"num_masked_positions",
"=",
"masked_positions",
".",
"shape",
"[",
"1",
"]",
"ctx",
"=",
"masked_positions",
".",
... | Generate unnormalized prediction for the masked language model task.
This is only used for pre-training the BERT model.
Inputs:
- **sequence**: input tensor of sequence encodings.
Shape (batch_size, seq_length, units).
- **masked_positions**: input tensor of posit... | [
"Generate",
"unnormalized",
"prediction",
"for",
"the",
"masked",
"language",
"model",
"task",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L461-L490 | train |
dmlc/gluon-nlp | scripts/machine_translation/bleu.py | _ngrams | def _ngrams(segment, n):
"""Extracts n-grams from an input segment.
Parameters
----------
segment: list
Text segment from which n-grams will be extracted.
n: int
Order of n-gram.
Returns
-------
ngram_counts: Counter
Contain all the nth n-grams in segment with a... | python | def _ngrams(segment, n):
"""Extracts n-grams from an input segment.
Parameters
----------
segment: list
Text segment from which n-grams will be extracted.
n: int
Order of n-gram.
Returns
-------
ngram_counts: Counter
Contain all the nth n-grams in segment with a... | [
"def",
"_ngrams",
"(",
"segment",
",",
"n",
")",
":",
"ngram_counts",
"=",
"Counter",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"segment",
")",
"-",
"n",
"+",
"1",
")",
":",
"ngram",
"=",
"tuple",
"(",
"segment",
"[",
"i",... | Extracts n-grams from an input segment.
Parameters
----------
segment: list
Text segment from which n-grams will be extracted.
n: int
Order of n-gram.
Returns
-------
ngram_counts: Counter
Contain all the nth n-grams in segment with a count of how many times each n-... | [
"Extracts",
"n",
"-",
"grams",
"from",
"an",
"input",
"segment",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L32-L51 | train |
dmlc/gluon-nlp | scripts/machine_translation/bleu.py | _bpe_to_words | def _bpe_to_words(sentence, delimiter='@@'):
"""Convert a sequence of bpe words into sentence."""
words = []
word = ''
delimiter_len = len(delimiter)
for subwords in sentence:
if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter:
word += subwords[:-delimit... | python | def _bpe_to_words(sentence, delimiter='@@'):
"""Convert a sequence of bpe words into sentence."""
words = []
word = ''
delimiter_len = len(delimiter)
for subwords in sentence:
if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter:
word += subwords[:-delimit... | [
"def",
"_bpe_to_words",
"(",
"sentence",
",",
"delimiter",
"=",
"'@@'",
")",
":",
"words",
"=",
"[",
"]",
"word",
"=",
"''",
"delimiter_len",
"=",
"len",
"(",
"delimiter",
")",
"for",
"subwords",
"in",
"sentence",
":",
"if",
"len",
"(",
"subwords",
")"... | Convert a sequence of bpe words into sentence. | [
"Convert",
"a",
"sequence",
"of",
"bpe",
"words",
"into",
"sentence",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L61-L73 | train |
dmlc/gluon-nlp | scripts/machine_translation/bleu.py | _tokenize_mteval_13a | def _tokenize_mteval_13a(segment):
r"""
Tokenizes a string following the tokenizer in mteval-v13a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L917-L942
Parameters
----------
segment: str
A string to be tokenized
Returns
... | python | def _tokenize_mteval_13a(segment):
r"""
Tokenizes a string following the tokenizer in mteval-v13a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L917-L942
Parameters
----------
segment: str
A string to be tokenized
Returns
... | [
"def",
"_tokenize_mteval_13a",
"(",
"segment",
")",
":",
"norm",
"=",
"segment",
".",
"rstrip",
"(",
")",
"norm",
"=",
"norm",
".",
"replace",
"(",
"'<skipped>'",
",",
"''",
")",
"norm",
"=",
"norm",
".",
"replace",
"(",
"'-\\n'",
",",
"''",
")",
"no... | r"""
Tokenizes a string following the tokenizer in mteval-v13a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L917-L942
Parameters
----------
segment: str
A string to be tokenized
Returns
-------
The tokenized string | [
"r",
"Tokenizes",
"a",
"string",
"following",
"the",
"tokenizer",
"in",
"mteval",
"-",
"v13a",
".",
"pl",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"moses",
"-",
"smt",
"/",
"mosesdecoder",
"/",
"blob",
"/",
"master",
"/",
"scripts",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L76-L110 | train |
dmlc/gluon-nlp | scripts/machine_translation/bleu.py | _tokenize_mteval_v14_intl | def _tokenize_mteval_v14_intl(segment):
r"""Tokenize a string following following the international tokenizer in mteval-v14a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
Parameters
----------
segment: str
A string to be ... | python | def _tokenize_mteval_v14_intl(segment):
r"""Tokenize a string following following the international tokenizer in mteval-v14a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
Parameters
----------
segment: str
A string to be ... | [
"def",
"_tokenize_mteval_v14_intl",
"(",
"segment",
")",
":",
"segment",
"=",
"segment",
".",
"rstrip",
"(",
")",
"segment",
"=",
"unicodeRegex",
".",
"nondigit_punct_re",
".",
"sub",
"(",
"r'\\1 \\2 '",
",",
"segment",
")",
"segment",
"=",
"unicodeRegex",
"."... | r"""Tokenize a string following following the international tokenizer in mteval-v14a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
Parameters
----------
segment: str
A string to be tokenized
Returns
-------
The t... | [
"r",
"Tokenize",
"a",
"string",
"following",
"following",
"the",
"international",
"tokenizer",
"in",
"mteval",
"-",
"v14a",
".",
"pl",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"moses",
"-",
"smt",
"/",
"mosesdecoder",
"/",
"blob",
"/",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L130-L148 | train |
dmlc/gluon-nlp | scripts/machine_translation/bleu.py | compute_bleu | def compute_bleu(reference_corpus_list, translation_corpus, tokenized=True,
tokenizer='13a', max_n=4, smooth=False, lower_case=False,
bpe=False, split_compound_word=False):
r"""Compute bleu score of translation against references.
Parameters
----------
reference_corpus... | python | def compute_bleu(reference_corpus_list, translation_corpus, tokenized=True,
tokenizer='13a', max_n=4, smooth=False, lower_case=False,
bpe=False, split_compound_word=False):
r"""Compute bleu score of translation against references.
Parameters
----------
reference_corpus... | [
"def",
"compute_bleu",
"(",
"reference_corpus_list",
",",
"translation_corpus",
",",
"tokenized",
"=",
"True",
",",
"tokenizer",
"=",
"'13a'",
",",
"max_n",
"=",
"4",
",",
"smooth",
"=",
"False",
",",
"lower_case",
"=",
"False",
",",
"bpe",
"=",
"False",
"... | r"""Compute bleu score of translation against references.
Parameters
----------
reference_corpus_list: list of list(list(str)) or list of list(str)
list of list(list(str)): tokenized references
list of list(str): plain text
List of references for each translation.
translation_co... | [
"r",
"Compute",
"bleu",
"score",
"of",
"translation",
"against",
"references",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L158-L249 | train |
dmlc/gluon-nlp | scripts/machine_translation/bleu.py | _compute_precision | def _compute_precision(references, translation, n):
"""Compute ngram precision.
Parameters
----------
references: list(list(str))
A list of references.
translation: list(str)
A translation.
n: int
Order of n-gram.
Returns
-------
matches: int
Number ... | python | def _compute_precision(references, translation, n):
"""Compute ngram precision.
Parameters
----------
references: list(list(str))
A list of references.
translation: list(str)
A translation.
n: int
Order of n-gram.
Returns
-------
matches: int
Number ... | [
"def",
"_compute_precision",
"(",
"references",
",",
"translation",
",",
"n",
")",
":",
"matches",
"=",
"0",
"candidates",
"=",
"0",
"ref_ngram_counts",
"=",
"Counter",
"(",
")",
"for",
"reference",
"in",
"references",
":",
"ref_ngram_counts",
"|=",
"_ngrams",... | Compute ngram precision.
Parameters
----------
references: list(list(str))
A list of references.
translation: list(str)
A translation.
n: int
Order of n-gram.
Returns
-------
matches: int
Number of matched nth order n-grams
candidates
Number ... | [
"Compute",
"ngram",
"precision",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L252-L284 | train |
dmlc/gluon-nlp | scripts/machine_translation/bleu.py | _brevity_penalty | def _brevity_penalty(ref_length, trans_length):
"""Calculate brevity penalty.
Parameters
----------
ref_length: int
Sum of all closest references'lengths for every translations in a corpus
trans_length: int
Sum of all translations's lengths in a corpus.
Returns
-------
... | python | def _brevity_penalty(ref_length, trans_length):
"""Calculate brevity penalty.
Parameters
----------
ref_length: int
Sum of all closest references'lengths for every translations in a corpus
trans_length: int
Sum of all translations's lengths in a corpus.
Returns
-------
... | [
"def",
"_brevity_penalty",
"(",
"ref_length",
",",
"trans_length",
")",
":",
"if",
"trans_length",
">",
"ref_length",
":",
"return",
"1",
"# If translation is empty, brevity penalty = 0 should result in BLEU = 0.0",
"elif",
"trans_length",
"==",
"0",
":",
"return",
"0",
... | Calculate brevity penalty.
Parameters
----------
ref_length: int
Sum of all closest references'lengths for every translations in a corpus
trans_length: int
Sum of all translations's lengths in a corpus.
Returns
-------
bleu's brevity penalty: float | [
"Calculate",
"brevity",
"penalty",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L287-L307 | train |
dmlc/gluon-nlp | scripts/machine_translation/bleu.py | _closest_ref_length | def _closest_ref_length(references, trans_length):
"""Find the reference that has the closest length to the translation.
Parameters
----------
references: list(list(str))
A list of references.
trans_length: int
Length of the translation.
Returns
-------
closest_ref_len:... | python | def _closest_ref_length(references, trans_length):
"""Find the reference that has the closest length to the translation.
Parameters
----------
references: list(list(str))
A list of references.
trans_length: int
Length of the translation.
Returns
-------
closest_ref_len:... | [
"def",
"_closest_ref_length",
"(",
"references",
",",
"trans_length",
")",
":",
"ref_lengths",
"=",
"(",
"len",
"(",
"reference",
")",
"for",
"reference",
"in",
"references",
")",
"closest_ref_len",
"=",
"min",
"(",
"ref_lengths",
",",
"key",
"=",
"lambda",
... | Find the reference that has the closest length to the translation.
Parameters
----------
references: list(list(str))
A list of references.
trans_length: int
Length of the translation.
Returns
-------
closest_ref_len: int
Length of the reference that is closest to th... | [
"Find",
"the",
"reference",
"that",
"has",
"the",
"closest",
"length",
"to",
"the",
"translation",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L310-L329 | train |
dmlc/gluon-nlp | scripts/machine_translation/bleu.py | _smoothing | def _smoothing(precision_fractions, c=1):
"""Compute the smoothed precision for all the orders.
Parameters
----------
precision_fractions: list(tuple)
Contain a list of (precision_numerator, precision_denominator) pairs
c: int, default 1
Smoothing constant to use
Returns
--... | python | def _smoothing(precision_fractions, c=1):
"""Compute the smoothed precision for all the orders.
Parameters
----------
precision_fractions: list(tuple)
Contain a list of (precision_numerator, precision_denominator) pairs
c: int, default 1
Smoothing constant to use
Returns
--... | [
"def",
"_smoothing",
"(",
"precision_fractions",
",",
"c",
"=",
"1",
")",
":",
"ratios",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"precision_fractions",
")",
"for",
"i",
",",
"precision_fraction",
"in",
"enumerate",
"(",
"precision_fractions",
")",
":",
"if",
... | Compute the smoothed precision for all the orders.
Parameters
----------
precision_fractions: list(tuple)
Contain a list of (precision_numerator, precision_denominator) pairs
c: int, default 1
Smoothing constant to use
Returns
-------
ratios: list of floats
Contain ... | [
"Compute",
"the",
"smoothed",
"precision",
"for",
"all",
"the",
"orders",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L332-L354 | train |
dmlc/gluon-nlp | scripts/language_model/sampler.py | LogUniformSampler.forward | def forward(self, true_classes):
"""Draw samples from log uniform distribution and returns sampled candidates,
expected count for true classes and sampled classes.
Parameters
----------
true_classes: NDArray
The true classes.
Returns
-------
... | python | def forward(self, true_classes):
"""Draw samples from log uniform distribution and returns sampled candidates,
expected count for true classes and sampled classes.
Parameters
----------
true_classes: NDArray
The true classes.
Returns
-------
... | [
"def",
"forward",
"(",
"self",
",",
"true_classes",
")",
":",
"num_sampled",
"=",
"self",
".",
"_num_sampled",
"ctx",
"=",
"true_classes",
".",
"context",
"num_tries",
"=",
"0",
"log_range",
"=",
"math",
".",
"log",
"(",
"self",
".",
"_range_max",
"+",
"... | Draw samples from log uniform distribution and returns sampled candidates,
expected count for true classes and sampled classes.
Parameters
----------
true_classes: NDArray
The true classes.
Returns
-------
samples: NDArray
The sampled can... | [
"Draw",
"samples",
"from",
"log",
"uniform",
"distribution",
"and",
"returns",
"sampled",
"candidates",
"expected",
"count",
"for",
"true",
"classes",
"and",
"sampled",
"classes",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/sampler.py#L66-L109 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | preprocess_dataset | def preprocess_dataset(data, min_freq=5, max_vocab_size=None):
"""Dataset preprocessing helper.
Parameters
----------
data : mx.data.Dataset
Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9
min_freq : int, default 5
Minimum token frequency for a token to be inclu... | python | def preprocess_dataset(data, min_freq=5, max_vocab_size=None):
"""Dataset preprocessing helper.
Parameters
----------
data : mx.data.Dataset
Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9
min_freq : int, default 5
Minimum token frequency for a token to be inclu... | [
"def",
"preprocess_dataset",
"(",
"data",
",",
"min_freq",
"=",
"5",
",",
"max_vocab_size",
"=",
"None",
")",
":",
"with",
"print_time",
"(",
"'count and construct vocabulary'",
")",
":",
"counter",
"=",
"nlp",
".",
"data",
".",
"count_tokens",
"(",
"itertools... | Dataset preprocessing helper.
Parameters
----------
data : mx.data.Dataset
Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9
min_freq : int, default 5
Minimum token frequency for a token to be included in the vocabulary
and returned DataStream.
max_vocab_s... | [
"Dataset",
"preprocessing",
"helper",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L47-L86 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | wiki | def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None):
"""Wikipedia dump helper.
Parameters
----------
wiki_root : str
Parameter for WikiDumpStream
wiki_date : str
Parameter for WikiDumpStream
wiki_language : str
Parameter for WikiDumpStream
max_vocab_si... | python | def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None):
"""Wikipedia dump helper.
Parameters
----------
wiki_root : str
Parameter for WikiDumpStream
wiki_date : str
Parameter for WikiDumpStream
wiki_language : str
Parameter for WikiDumpStream
max_vocab_si... | [
"def",
"wiki",
"(",
"wiki_root",
",",
"wiki_date",
",",
"wiki_language",
",",
"max_vocab_size",
"=",
"None",
")",
":",
"data",
"=",
"WikiDumpStream",
"(",
"root",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"wiki_root",
")",
",",
"language",
"=",
"wi... | Wikipedia dump helper.
Parameters
----------
wiki_root : str
Parameter for WikiDumpStream
wiki_date : str
Parameter for WikiDumpStream
wiki_language : str
Parameter for WikiDumpStream
max_vocab_size : int, optional
Specifies a maximum size for the vocabulary.
... | [
"Wikipedia",
"dump",
"helper",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L89-L131 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | transform_data_fasttext | def transform_data_fasttext(data, vocab, idx_to_counts, cbow, ngram_buckets,
ngrams, batch_size, window_size,
frequent_token_subsampling=1E-4, dtype='float32',
index_dtype='int64'):
"""Transform a DataStream of coded DataSets to a D... | python | def transform_data_fasttext(data, vocab, idx_to_counts, cbow, ngram_buckets,
ngrams, batch_size, window_size,
frequent_token_subsampling=1E-4, dtype='float32',
index_dtype='int64'):
"""Transform a DataStream of coded DataSets to a D... | [
"def",
"transform_data_fasttext",
"(",
"data",
",",
"vocab",
",",
"idx_to_counts",
",",
"cbow",
",",
"ngram_buckets",
",",
"ngrams",
",",
"batch_size",
",",
"window_size",
",",
"frequent_token_subsampling",
"=",
"1E-4",
",",
"dtype",
"=",
"'float32'",
",",
"inde... | Transform a DataStream of coded DataSets to a DataStream of batches.
Parameters
----------
data : gluonnlp.data.DataStream
DataStream where each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
vocab : gluonnlp.Vocab
Vocabulary containing all tokens whose... | [
"Transform",
"a",
"DataStream",
"of",
"coded",
"DataSets",
"to",
"a",
"DataStream",
"of",
"batches",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L134-L252 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | transform_data_word2vec | def transform_data_word2vec(data, vocab, idx_to_counts, cbow, batch_size,
window_size, frequent_token_subsampling=1E-4,
dtype='float32', index_dtype='int64'):
"""Transform a DataStream of coded DataSets to a DataStream of batches.
Parameters
---------... | python | def transform_data_word2vec(data, vocab, idx_to_counts, cbow, batch_size,
window_size, frequent_token_subsampling=1E-4,
dtype='float32', index_dtype='int64'):
"""Transform a DataStream of coded DataSets to a DataStream of batches.
Parameters
---------... | [
"def",
"transform_data_word2vec",
"(",
"data",
",",
"vocab",
",",
"idx_to_counts",
",",
"cbow",
",",
"batch_size",
",",
"window_size",
",",
"frequent_token_subsampling",
"=",
"1E-4",
",",
"dtype",
"=",
"'float32'",
",",
"index_dtype",
"=",
"'int64'",
")",
":",
... | Transform a DataStream of coded DataSets to a DataStream of batches.
Parameters
----------
data : gluonnlp.data.DataStream
DataStream where each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
vocab : gluonnlp.Vocab
Vocabulary containing all tokens whose... | [
"Transform",
"a",
"DataStream",
"of",
"coded",
"DataSets",
"to",
"a",
"DataStream",
"of",
"batches",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L255-L319 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | cbow_fasttext_batch | def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype,
index_dtype):
"""Create a batch for CBOW training objective with subwords."""
_, contexts_row, contexts_col = contexts
data, row, col = subword_lookup(contexts_row, contexts_col)
centers = mx.nd.array(c... | python | def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype,
index_dtype):
"""Create a batch for CBOW training objective with subwords."""
_, contexts_row, contexts_col = contexts
data, row, col = subword_lookup(contexts_row, contexts_col)
centers = mx.nd.array(c... | [
"def",
"cbow_fasttext_batch",
"(",
"centers",
",",
"contexts",
",",
"num_tokens",
",",
"subword_lookup",
",",
"dtype",
",",
"index_dtype",
")",
":",
"_",
",",
"contexts_row",
",",
"contexts_col",
"=",
"contexts",
"data",
",",
"row",
",",
"col",
"=",
"subword... | Create a batch for CBOW training objective with subwords. | [
"Create",
"a",
"batch",
"for",
"CBOW",
"training",
"objective",
"with",
"subwords",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L322-L331 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | skipgram_fasttext_batch | def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup,
dtype, index_dtype):
"""Create a batch for SG training objective with subwords."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
data, row, col = subword_lookup(centers)
centers = mx.nd.array(... | python | def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup,
dtype, index_dtype):
"""Create a batch for SG training objective with subwords."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
data, row, col = subword_lookup(centers)
centers = mx.nd.array(... | [
"def",
"skipgram_fasttext_batch",
"(",
"centers",
",",
"contexts",
",",
"num_tokens",
",",
"subword_lookup",
",",
"dtype",
",",
"index_dtype",
")",
":",
"contexts",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"contexts",
"[",
"2",
"]",
",",
"dtype",
"=",
"i... | Create a batch for SG training objective with subwords. | [
"Create",
"a",
"batch",
"for",
"SG",
"training",
"objective",
"with",
"subwords",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L334-L343 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | cbow_batch | def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for CBOW training objective."""
contexts_data, contexts_row, contexts_col = contexts
centers = mx.nd.array(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(contexts_data, (contexts_row, contexts_... | python | def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for CBOW training objective."""
contexts_data, contexts_row, contexts_col = contexts
centers = mx.nd.array(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(contexts_data, (contexts_row, contexts_... | [
"def",
"cbow_batch",
"(",
"centers",
",",
"contexts",
",",
"num_tokens",
",",
"dtype",
",",
"index_dtype",
")",
":",
"contexts_data",
",",
"contexts_row",
",",
"contexts_col",
"=",
"contexts",
"centers",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"centers",
... | Create a batch for CBOW training objective. | [
"Create",
"a",
"batch",
"for",
"CBOW",
"training",
"objective",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L346-L353 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | skipgram_batch | def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for SG training objective."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
indptr = mx.nd.arange(len(centers) + 1)
centers = mx.nd.array(centers, dtype=index_dtype)
centers_csr = mx.nd.sparse.csr_matri... | python | def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for SG training objective."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
indptr = mx.nd.arange(len(centers) + 1)
centers = mx.nd.array(centers, dtype=index_dtype)
centers_csr = mx.nd.sparse.csr_matri... | [
"def",
"skipgram_batch",
"(",
"centers",
",",
"contexts",
",",
"num_tokens",
",",
"dtype",
",",
"index_dtype",
")",
":",
"contexts",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"contexts",
"[",
"2",
"]",
",",
"dtype",
"=",
"index_dtype",
")",
"indptr",
"=... | Create a batch for SG training objective. | [
"Create",
"a",
"batch",
"for",
"SG",
"training",
"objective",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L356-L364 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | skipgram_lookup | def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0):
"""Get a sparse COO array of words and subwords for SkipGram.
Parameters
----------
indices : numpy.ndarray
Array containing numbers in [0, vocabulary_size). The element at
position idx is taken to be the word that occ... | python | def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0):
"""Get a sparse COO array of words and subwords for SkipGram.
Parameters
----------
indices : numpy.ndarray
Array containing numbers in [0, vocabulary_size). The element at
position idx is taken to be the word that occ... | [
"def",
"skipgram_lookup",
"(",
"indices",
",",
"subwordidxs",
",",
"subwordidxsptr",
",",
"offset",
"=",
"0",
")",
":",
"row",
"=",
"[",
"]",
"col",
"=",
"[",
"]",
"data",
"=",
"[",
"]",
"for",
"i",
",",
"idx",
"in",
"enumerate",
"(",
"indices",
")... | Get a sparse COO array of words and subwords for SkipGram.
Parameters
----------
indices : numpy.ndarray
Array containing numbers in [0, vocabulary_size). The element at
position idx is taken to be the word that occurs at row idx in the
SkipGram batch.
offset : int
Offse... | [
"Get",
"a",
"sparse",
"COO",
"array",
"of",
"words",
"and",
"subwords",
"for",
"SkipGram",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L376-L427 | train |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | cbow_lookup | def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr,
offset=0):
"""Get a sparse COO array of words and subwords for CBOW.
Parameters
----------
context_row : numpy.ndarray of dtype int64
Array of same length as context_col containing numbers in [0,
batc... | python | def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr,
offset=0):
"""Get a sparse COO array of words and subwords for CBOW.
Parameters
----------
context_row : numpy.ndarray of dtype int64
Array of same length as context_col containing numbers in [0,
batc... | [
"def",
"cbow_lookup",
"(",
"context_row",
",",
"context_col",
",",
"subwordidxs",
",",
"subwordidxsptr",
",",
"offset",
"=",
"0",
")",
":",
"row",
"=",
"[",
"]",
"col",
"=",
"[",
"]",
"data",
"=",
"[",
"]",
"num_rows",
"=",
"np",
".",
"max",
"(",
"... | Get a sparse COO array of words and subwords for CBOW.
Parameters
----------
context_row : numpy.ndarray of dtype int64
Array of same length as context_col containing numbers in [0,
batch_size). For each idx, context_row[idx] specifies the row that
context_col[idx] occurs in a spars... | [
"Get",
"a",
"sparse",
"COO",
"array",
"of",
"words",
"and",
"subwords",
"for",
"CBOW",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L431-L501 | train |
dmlc/gluon-nlp | src/gluonnlp/data/translation.py | _TranslationDataset.src_vocab | def src_vocab(self):
"""Source Vocabulary of the Dataset.
Returns
-------
src_vocab : Vocab
Source vocabulary.
"""
if self._src_vocab is None:
src_vocab_file_name, src_vocab_hash = \
self._data_file[self._pair_key]['vocab' + '_' + ... | python | def src_vocab(self):
"""Source Vocabulary of the Dataset.
Returns
-------
src_vocab : Vocab
Source vocabulary.
"""
if self._src_vocab is None:
src_vocab_file_name, src_vocab_hash = \
self._data_file[self._pair_key]['vocab' + '_' + ... | [
"def",
"src_vocab",
"(",
"self",
")",
":",
"if",
"self",
".",
"_src_vocab",
"is",
"None",
":",
"src_vocab_file_name",
",",
"src_vocab_hash",
"=",
"self",
".",
"_data_file",
"[",
"self",
".",
"_pair_key",
"]",
"[",
"'vocab'",
"+",
"'_'",
"+",
"self",
".",... | Source Vocabulary of the Dataset.
Returns
-------
src_vocab : Vocab
Source vocabulary. | [
"Source",
"Vocabulary",
"of",
"the",
"Dataset",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/translation.py#L119-L133 | train |
dmlc/gluon-nlp | src/gluonnlp/data/translation.py | _TranslationDataset.tgt_vocab | def tgt_vocab(self):
"""Target Vocabulary of the Dataset.
Returns
-------
tgt_vocab : Vocab
Target vocabulary.
"""
if self._tgt_vocab is None:
tgt_vocab_file_name, tgt_vocab_hash = \
self._data_file[self._pair_key]['vocab' + '_' + ... | python | def tgt_vocab(self):
"""Target Vocabulary of the Dataset.
Returns
-------
tgt_vocab : Vocab
Target vocabulary.
"""
if self._tgt_vocab is None:
tgt_vocab_file_name, tgt_vocab_hash = \
self._data_file[self._pair_key]['vocab' + '_' + ... | [
"def",
"tgt_vocab",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tgt_vocab",
"is",
"None",
":",
"tgt_vocab_file_name",
",",
"tgt_vocab_hash",
"=",
"self",
".",
"_data_file",
"[",
"self",
".",
"_pair_key",
"]",
"[",
"'vocab'",
"+",
"'_'",
"+",
"self",
".",... | Target Vocabulary of the Dataset.
Returns
-------
tgt_vocab : Vocab
Target vocabulary. | [
"Target",
"Vocabulary",
"of",
"the",
"Dataset",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/translation.py#L136-L150 | train |
dmlc/gluon-nlp | scripts/machine_translation/train_gnmt.py | evaluate | def evaluate(data_loader):
"""Evaluate given the data loader
Parameters
----------
data_loader : DataLoader
Returns
-------
avg_loss : float
Average loss
real_translation_out : list of list of str
The translation output
"""
translation_out = []
all_inst_ids ... | python | def evaluate(data_loader):
"""Evaluate given the data loader
Parameters
----------
data_loader : DataLoader
Returns
-------
avg_loss : float
Average loss
real_translation_out : list of list of str
The translation output
"""
translation_out = []
all_inst_ids ... | [
"def",
"evaluate",
"(",
"data_loader",
")",
":",
"translation_out",
"=",
"[",
"]",
"all_inst_ids",
"=",
"[",
"]",
"avg_loss_denom",
"=",
"0",
"avg_loss",
"=",
"0.0",
"for",
"_",
",",
"(",
"src_seq",
",",
"tgt_seq",
",",
"src_valid_length",
",",
"tgt_valid_... | Evaluate given the data loader
Parameters
----------
data_loader : DataLoader
Returns
-------
avg_loss : float
Average loss
real_translation_out : list of list of str
The translation output | [
"Evaluate",
"given",
"the",
"data",
"loader"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/train_gnmt.py#L147-L190 | train |
dmlc/gluon-nlp | scripts/machine_translation/train_gnmt.py | train | def train():
"""Training function."""
trainer = gluon.Trainer(model.collect_params(), args.optimizer, {'learning_rate': args.lr})
train_data_loader, val_data_loader, test_data_loader \
= dataprocessor.make_dataloader(data_train, data_val, data_test, args)
best_valid_bleu = 0.0
for epoch_id... | python | def train():
"""Training function."""
trainer = gluon.Trainer(model.collect_params(), args.optimizer, {'learning_rate': args.lr})
train_data_loader, val_data_loader, test_data_loader \
= dataprocessor.make_dataloader(data_train, data_val, data_test, args)
best_valid_bleu = 0.0
for epoch_id... | [
"def",
"train",
"(",
")",
":",
"trainer",
"=",
"gluon",
".",
"Trainer",
"(",
"model",
".",
"collect_params",
"(",
")",
",",
"args",
".",
"optimizer",
",",
"{",
"'learning_rate'",
":",
"args",
".",
"lr",
"}",
")",
"train_data_loader",
",",
"val_data_loade... | Training function. | [
"Training",
"function",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/train_gnmt.py#L193-L276 | train |
dmlc/gluon-nlp | src/gluonnlp/model/train/__init__.py | get_cache_model | def get_cache_model(name, dataset_name='wikitext-2', window=2000,
theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs):
r"""Returns a cache model using a pre-trained language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving... | python | def get_cache_model(name, dataset_name='wikitext-2', window=2000,
theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs):
r"""Returns a cache model using a pre-trained language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving... | [
"def",
"get_cache_model",
"(",
"name",
",",
"dataset_name",
"=",
"'wikitext-2'",
",",
"window",
"=",
"2000",
",",
"theta",
"=",
"0.6",
",",
"lambdas",
"=",
"0.2",
",",
"ctx",
"=",
"mx",
".",
"cpu",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"lm_m... | r"""Returns a cache model using a pre-trained language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving,
title={Improving neural language models with a continuous cache},
author={Grave, Edouard and Joulin, Armand and Usunier, ... | [
"r",
"Returns",
"a",
"cache",
"model",
"using",
"a",
"pre",
"-",
"trained",
"language",
"model",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/__init__.py#L36-L98 | train |
dmlc/gluon-nlp | scripts/word_embeddings/train_sg_cbow.py | train | def train(args):
"""Training helper."""
if not args.model.lower() in ['cbow', 'skipgram']:
logging.error('Unsupported model %s.', args.model)
sys.exit(1)
if args.data.lower() == 'toy':
data = mx.gluon.data.SimpleDataset(nlp.data.Text8(segment='train')[:2])
data, vocab, idx_t... | python | def train(args):
"""Training helper."""
if not args.model.lower() in ['cbow', 'skipgram']:
logging.error('Unsupported model %s.', args.model)
sys.exit(1)
if args.data.lower() == 'toy':
data = mx.gluon.data.SimpleDataset(nlp.data.Text8(segment='train')[:2])
data, vocab, idx_t... | [
"def",
"train",
"(",
"args",
")",
":",
"if",
"not",
"args",
".",
"model",
".",
"lower",
"(",
")",
"in",
"[",
"'cbow'",
",",
"'skipgram'",
"]",
":",
"logging",
".",
"error",
"(",
"'Unsupported model %s.'",
",",
"args",
".",
"model",
")",
"sys",
".",
... | Training helper. | [
"Training",
"helper",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_sg_cbow.py#L138-L279 | train |
dmlc/gluon-nlp | scripts/word_embeddings/train_sg_cbow.py | evaluate | def evaluate(args, embedding, vocab, global_step, eval_analogy=False):
"""Evaluation helper"""
if 'eval_tokens' not in globals():
global eval_tokens
eval_tokens_set = evaluation.get_tokens_in_evaluation_datasets(args)
if not args.no_eval_analogy:
eval_tokens_set.update(vocab... | python | def evaluate(args, embedding, vocab, global_step, eval_analogy=False):
"""Evaluation helper"""
if 'eval_tokens' not in globals():
global eval_tokens
eval_tokens_set = evaluation.get_tokens_in_evaluation_datasets(args)
if not args.no_eval_analogy:
eval_tokens_set.update(vocab... | [
"def",
"evaluate",
"(",
"args",
",",
"embedding",
",",
"vocab",
",",
"global_step",
",",
"eval_analogy",
"=",
"False",
")",
":",
"if",
"'eval_tokens'",
"not",
"in",
"globals",
"(",
")",
":",
"global",
"eval_tokens",
"eval_tokens_set",
"=",
"evaluation",
".",... | Evaluation helper | [
"Evaluation",
"helper"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_sg_cbow.py#L282-L317 | train |
dmlc/gluon-nlp | src/gluonnlp/data/dataset.py | NumpyDataset.get_field | def get_field(self, field):
"""Return the dataset corresponds to the provided key.
Example::
a = np.ones((2,2))
b = np.zeros((2,2))
np.savez('data.npz', a=a, b=b)
dataset = NumpyDataset('data.npz')
data_a = dataset.get_field('a')
d... | python | def get_field(self, field):
"""Return the dataset corresponds to the provided key.
Example::
a = np.ones((2,2))
b = np.zeros((2,2))
np.savez('data.npz', a=a, b=b)
dataset = NumpyDataset('data.npz')
data_a = dataset.get_field('a')
d... | [
"def",
"get_field",
"(",
"self",
",",
"field",
")",
":",
"idx",
"=",
"self",
".",
"_keys",
".",
"index",
"(",
"field",
")",
"return",
"self",
".",
"_data",
"[",
"idx",
"]"
] | Return the dataset corresponds to the provided key.
Example::
a = np.ones((2,2))
b = np.zeros((2,2))
np.savez('data.npz', a=a, b=b)
dataset = NumpyDataset('data.npz')
data_a = dataset.get_field('a')
data_b = dataset.get_field('b')
... | [
"Return",
"the",
"dataset",
"corresponds",
"to",
"the",
"provided",
"key",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/dataset.py#L259-L276 | train |
dmlc/gluon-nlp | scripts/bert/bert_qa_evaluate.py | get_final_text | def get_final_text(pred_text, orig_text, tokenizer):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_text` contains the span o... | python | def get_final_text(pred_text, orig_text, tokenizer):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_text` contains the span o... | [
"def",
"get_final_text",
"(",
"pred_text",
",",
"orig_text",
",",
"tokenizer",
")",
":",
"# When we created the data, we kept track of the alignment between original",
"# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So",
"# now `orig_text` contains the span of our origin... | Project the tokenized prediction back to the original text. | [
"Project",
"the",
"tokenized",
"prediction",
"back",
"to",
"the",
"original",
"text",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_evaluate.py#L38-L120 | train |
dmlc/gluon-nlp | scripts/bert/bert_qa_evaluate.py | predictions | def predictions(dev_dataset,
all_results,
tokenizer,
max_answer_length=64,
null_score_diff_threshold=0.0,
n_best_size=10,
version_2=False):
"""Get prediction results
Parameters
----------
dev_dataset: datase... | python | def predictions(dev_dataset,
all_results,
tokenizer,
max_answer_length=64,
null_score_diff_threshold=0.0,
n_best_size=10,
version_2=False):
"""Get prediction results
Parameters
----------
dev_dataset: datase... | [
"def",
"predictions",
"(",
"dev_dataset",
",",
"all_results",
",",
"tokenizer",
",",
"max_answer_length",
"=",
"64",
",",
"null_score_diff_threshold",
"=",
"0.0",
",",
"n_best_size",
"=",
"10",
",",
"version_2",
"=",
"False",
")",
":",
"_PrelimPrediction",
"=",
... | Get prediction results
Parameters
----------
dev_dataset: dataset
Examples of transform.
all_results: dict
A dictionary containing model prediction results.
tokenizer: callable
Tokenizer function.
max_answer_length: int, default 64
Maximum length of the answer to... | [
"Get",
"prediction",
"results"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_evaluate.py#L123-L323 | train |
dmlc/gluon-nlp | scripts/bert/bert_qa_evaluate.py | get_F1_EM | def get_F1_EM(dataset, predict_data):
"""Calculate the F1 and EM scores of the predicted results.
Use only with the SQuAD1.1 dataset.
Parameters
----------
dataset_file: string
Path to the data file.
predict_data: dict
All final predictions.
Returns
-------
scores: ... | python | def get_F1_EM(dataset, predict_data):
"""Calculate the F1 and EM scores of the predicted results.
Use only with the SQuAD1.1 dataset.
Parameters
----------
dataset_file: string
Path to the data file.
predict_data: dict
All final predictions.
Returns
-------
scores: ... | [
"def",
"get_F1_EM",
"(",
"dataset",
",",
"predict_data",
")",
":",
"f1",
"=",
"exact_match",
"=",
"total",
"=",
"0",
"for",
"record",
"in",
"dataset",
":",
"total",
"+=",
"1",
"if",
"record",
"[",
"1",
"]",
"not",
"in",
"predict_data",
":",
"message",
... | Calculate the F1 and EM scores of the predicted results.
Use only with the SQuAD1.1 dataset.
Parameters
----------
dataset_file: string
Path to the data file.
predict_data: dict
All final predictions.
Returns
-------
scores: dict
F1 and EM scores. | [
"Calculate",
"the",
"F1",
"and",
"EM",
"scores",
"of",
"the",
"predicted",
"results",
".",
"Use",
"only",
"with",
"the",
"SQuAD1",
".",
"1",
"dataset",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_evaluate.py#L374-L409 | train |
dmlc/gluon-nlp | scripts/bert/finetune_classifier.py | preprocess_data | def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, pad=False):
"""Data preparation function."""
# transformation
trans = BERTDatasetTransform(
tokenizer,
max_len,
labels=task.get_labels(),
pad=pad,
pair=task.is_pair,
label_dtype='float32... | python | def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, pad=False):
"""Data preparation function."""
# transformation
trans = BERTDatasetTransform(
tokenizer,
max_len,
labels=task.get_labels(),
pad=pad,
pair=task.is_pair,
label_dtype='float32... | [
"def",
"preprocess_data",
"(",
"tokenizer",
",",
"task",
",",
"batch_size",
",",
"dev_batch_size",
",",
"max_len",
",",
"pad",
"=",
"False",
")",
":",
"# transformation",
"trans",
"=",
"BERTDatasetTransform",
"(",
"tokenizer",
",",
"max_len",
",",
"labels",
"=... | Data preparation function. | [
"Data",
"preparation",
"function",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L247-L301 | train |
dmlc/gluon-nlp | scripts/bert/finetune_classifier.py | evaluate | def evaluate(dataloader_eval, metric):
"""Evaluate the model on validation dataset.
"""
metric.reset()
for _, seqs in enumerate(dataloader_eval):
input_ids, valid_len, type_ids, label = seqs
out = model(
input_ids.as_in_context(ctx), type_ids.as_in_context(ctx),
v... | python | def evaluate(dataloader_eval, metric):
"""Evaluate the model on validation dataset.
"""
metric.reset()
for _, seqs in enumerate(dataloader_eval):
input_ids, valid_len, type_ids, label = seqs
out = model(
input_ids.as_in_context(ctx), type_ids.as_in_context(ctx),
v... | [
"def",
"evaluate",
"(",
"dataloader_eval",
",",
"metric",
")",
":",
"metric",
".",
"reset",
"(",
")",
"for",
"_",
",",
"seqs",
"in",
"enumerate",
"(",
"dataloader_eval",
")",
":",
"input_ids",
",",
"valid_len",
",",
"type_ids",
",",
"label",
"=",
"seqs",... | Evaluate the model on validation dataset. | [
"Evaluate",
"the",
"model",
"on",
"validation",
"dataset",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L314-L330 | train |
dmlc/gluon-nlp | scripts/bert/finetune_classifier.py | log_train | def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate):
"""Generate and print out the log message for training.
"""
metric_nm, metric_val = metric.get()
if not isinstance(metric_nm, list):
metric_nm = [metric_nm]
metric_val = [metric_val]
train_... | python | def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate):
"""Generate and print out the log message for training.
"""
metric_nm, metric_val = metric.get()
if not isinstance(metric_nm, list):
metric_nm = [metric_nm]
metric_val = [metric_val]
train_... | [
"def",
"log_train",
"(",
"batch_id",
",",
"batch_num",
",",
"metric",
",",
"step_loss",
",",
"log_interval",
",",
"epoch_id",
",",
"learning_rate",
")",
":",
"metric_nm",
",",
"metric_val",
"=",
"metric",
".",
"get",
"(",
")",
"if",
"not",
"isinstance",
"(... | Generate and print out the log message for training. | [
"Generate",
"and",
"print",
"out",
"the",
"log",
"message",
"for",
"training",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L333-L346 | train |
dmlc/gluon-nlp | scripts/bert/finetune_classifier.py | log_inference | def log_inference(batch_id, batch_num, metric, step_loss, log_interval):
"""Generate and print out the log message for inference.
"""
metric_nm, metric_val = metric.get()
if not isinstance(metric_nm, list):
metric_nm = [metric_nm]
metric_val = [metric_val]
eval_str = '[Batch %d/%d] ... | python | def log_inference(batch_id, batch_num, metric, step_loss, log_interval):
"""Generate and print out the log message for inference.
"""
metric_nm, metric_val = metric.get()
if not isinstance(metric_nm, list):
metric_nm = [metric_nm]
metric_val = [metric_val]
eval_str = '[Batch %d/%d] ... | [
"def",
"log_inference",
"(",
"batch_id",
",",
"batch_num",
",",
"metric",
",",
"step_loss",
",",
"log_interval",
")",
":",
"metric_nm",
",",
"metric_val",
"=",
"metric",
".",
"get",
"(",
")",
"if",
"not",
"isinstance",
"(",
"metric_nm",
",",
"list",
")",
... | Generate and print out the log message for inference. | [
"Generate",
"and",
"print",
"out",
"the",
"log",
"message",
"for",
"inference",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L349-L361 | train |
dmlc/gluon-nlp | scripts/bert/finetune_classifier.py | train | def train(metric):
"""Training function."""
logging.info('Now we are doing BERT classification training on %s!', ctx)
optimizer_params = {'learning_rate': lr, 'epsilon': epsilon, 'wd': 0.01}
try:
trainer = gluon.Trainer(
model.collect_params(),
args.optimizer,
... | python | def train(metric):
"""Training function."""
logging.info('Now we are doing BERT classification training on %s!', ctx)
optimizer_params = {'learning_rate': lr, 'epsilon': epsilon, 'wd': 0.01}
try:
trainer = gluon.Trainer(
model.collect_params(),
args.optimizer,
... | [
"def",
"train",
"(",
"metric",
")",
":",
"logging",
".",
"info",
"(",
"'Now we are doing BERT classification training on %s!'",
",",
"ctx",
")",
"optimizer_params",
"=",
"{",
"'learning_rate'",
":",
"lr",
",",
"'epsilon'",
":",
"epsilon",
",",
"'wd'",
":",
"0.01... | Training function. | [
"Training",
"function",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L364-L459 | train |
dmlc/gluon-nlp | scripts/bert/finetune_classifier.py | inference | def inference(metric):
"""Inference function."""
logging.info('Now we are doing BERT classification inference on %s!', ctx)
model = BERTClassifier(bert, dropout=0.1, num_classes=len(task.get_labels()))
model.hybridize(static_alloc=True)
model.load_parameters(model_parameters, ctx=ctx)
metric.r... | python | def inference(metric):
"""Inference function."""
logging.info('Now we are doing BERT classification inference on %s!', ctx)
model = BERTClassifier(bert, dropout=0.1, num_classes=len(task.get_labels()))
model.hybridize(static_alloc=True)
model.load_parameters(model_parameters, ctx=ctx)
metric.r... | [
"def",
"inference",
"(",
"metric",
")",
":",
"logging",
".",
"info",
"(",
"'Now we are doing BERT classification inference on %s!'",
",",
"ctx",
")",
"model",
"=",
"BERTClassifier",
"(",
"bert",
",",
"dropout",
"=",
"0.1",
",",
"num_classes",
"=",
"len",
"(",
... | Inference function. | [
"Inference",
"function",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L462-L492 | train |
dmlc/gluon-nlp | scripts/question_answering/data_processing.py | preprocess_dataset | def preprocess_dataset(dataset, question_max_length, context_max_length):
"""Process SQuAD dataset by creating NDArray version of data
:param Dataset dataset: SQuAD dataset
:param int question_max_length: Maximum length of question (padded or trimmed to that size)
:param int context_max_length: Maximum... | python | def preprocess_dataset(dataset, question_max_length, context_max_length):
"""Process SQuAD dataset by creating NDArray version of data
:param Dataset dataset: SQuAD dataset
:param int question_max_length: Maximum length of question (padded or trimmed to that size)
:param int context_max_length: Maximum... | [
"def",
"preprocess_dataset",
"(",
"dataset",
",",
"question_max_length",
",",
"context_max_length",
")",
":",
"vocab_provider",
"=",
"VocabProvider",
"(",
"dataset",
")",
"transformer",
"=",
"SQuADTransform",
"(",
"vocab_provider",
",",
"question_max_length",
",",
"co... | Process SQuAD dataset by creating NDArray version of data
:param Dataset dataset: SQuAD dataset
:param int question_max_length: Maximum length of question (padded or trimmed to that size)
:param int context_max_length: Maximum length of context (padded or trimmed to that size)
Returns
-------
... | [
"Process",
"SQuAD",
"dataset",
"by",
"creating",
"NDArray",
"version",
"of",
"data"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/question_answering/data_processing.py#L34-L51 | train |
dmlc/gluon-nlp | scripts/question_answering/data_processing.py | SQuADTransform._get_answer_spans | def _get_answer_spans(answer_list, answer_start_list):
"""Find all answer spans from the context, returning start_index and end_index
:param list[str] answer_list: List of all answers
:param list[int] answer_start_list: List of all answers' start indices
Returns
-------
... | python | def _get_answer_spans(answer_list, answer_start_list):
"""Find all answer spans from the context, returning start_index and end_index
:param list[str] answer_list: List of all answers
:param list[int] answer_start_list: List of all answers' start indices
Returns
-------
... | [
"def",
"_get_answer_spans",
"(",
"answer_list",
",",
"answer_start_list",
")",
":",
"return",
"[",
"(",
"answer_start_list",
"[",
"i",
"]",
",",
"answer_start_list",
"[",
"i",
"]",
"+",
"len",
"(",
"answer",
")",
")",
"for",
"i",
",",
"answer",
"in",
"en... | Find all answer spans from the context, returning start_index and end_index
:param list[str] answer_list: List of all answers
:param list[int] answer_start_list: List of all answers' start indices
Returns
-------
List[Tuple]
list of Tuple(answer_start_index answer_e... | [
"Find",
"all",
"answer",
"spans",
"from",
"the",
"context",
"returning",
"start_index",
"and",
"end_index"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/question_answering/data_processing.py#L98-L110 | train |
dmlc/gluon-nlp | scripts/question_answering/data_processing.py | VocabProvider.get_word_level_vocab | def get_word_level_vocab(self):
"""Provides word level vocabulary
Returns
-------
Vocab
Word level vocabulary
"""
def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'):
return list(filter(None, re.split(token_delim + '|' + seq_delim, s... | python | def get_word_level_vocab(self):
"""Provides word level vocabulary
Returns
-------
Vocab
Word level vocabulary
"""
def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'):
return list(filter(None, re.split(token_delim + '|' + seq_delim, s... | [
"def",
"get_word_level_vocab",
"(",
"self",
")",
":",
"def",
"simple_tokenize",
"(",
"source_str",
",",
"token_delim",
"=",
"' '",
",",
"seq_delim",
"=",
"'\\n'",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"None",
",",
"re",
".",
"split",
"(",
"toke... | Provides word level vocabulary
Returns
-------
Vocab
Word level vocabulary | [
"Provides",
"word",
"level",
"vocabulary"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/question_answering/data_processing.py#L130-L142 | train |
dmlc/gluon-nlp | src/gluonnlp/loss/activation_regularizer.py | TemporalActivationRegularizationLoss.hybrid_forward | def hybrid_forward(self, F, *states): # pylint: disable=arguments-differ
"""
Parameters
----------
states : list
the stack outputs from RNN, which consists of output from each time step (TNC).
Returns
--------
loss : NDArray
loss tensor wi... | python | def hybrid_forward(self, F, *states): # pylint: disable=arguments-differ
"""
Parameters
----------
states : list
the stack outputs from RNN, which consists of output from each time step (TNC).
Returns
--------
loss : NDArray
loss tensor wi... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"*",
"states",
")",
":",
"# pylint: disable=arguments-differ",
"# pylint: disable=unused-argument",
"if",
"self",
".",
"_beta",
"!=",
"0",
":",
"if",
"states",
":",
"means",
"=",
"[",
"self",
".",
"_beta",
... | Parameters
----------
states : list
the stack outputs from RNN, which consists of output from each time step (TNC).
Returns
--------
loss : NDArray
loss tensor with shape (batch_size,). Dimensions other than batch_axis are averaged out. | [
"Parameters",
"----------",
"states",
":",
"list",
"the",
"stack",
"outputs",
"from",
"RNN",
"which",
"consists",
"of",
"output",
"from",
"each",
"time",
"step",
"(",
"TNC",
")",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/loss/activation_regularizer.py#L128-L148 | train |
dmlc/gluon-nlp | src/gluonnlp/data/transforms.py | BERTBasicTokenizer._tokenize | def _tokenize(self, text):
"""Tokenizes a piece of text."""
text = self._clean_text(text)
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not t... | python | def _tokenize(self, text):
"""Tokenizes a piece of text."""
text = self._clean_text(text)
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not t... | [
"def",
"_tokenize",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"self",
".",
"_clean_text",
"(",
"text",
")",
"# This was added on November 1st, 2018 for the multilingual and Chinese",
"# models. This is also applied to the English models now, but it doesn't",
"# matter sinc... | Tokenizes a piece of text. | [
"Tokenizes",
"a",
"piece",
"of",
"text",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L758-L778 | train |
dmlc/gluon-nlp | src/gluonnlp/data/transforms.py | BERTBasicTokenizer._clean_text | def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp in (0, 0xfffd) or self._is_control(char):
continue
if self._is_whitespace(char):
... | python | def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp in (0, 0xfffd) or self._is_control(char):
continue
if self._is_whitespace(char):
... | [
"def",
"_clean_text",
"(",
"self",
",",
"text",
")",
":",
"output",
"=",
"[",
"]",
"for",
"char",
"in",
"text",
":",
"cp",
"=",
"ord",
"(",
"char",
")",
"if",
"cp",
"in",
"(",
"0",
",",
"0xfffd",
")",
"or",
"self",
".",
"_is_control",
"(",
"cha... | Performs invalid character removal and whitespace cleanup on text. | [
"Performs",
"invalid",
"character",
"removal",
"and",
"whitespace",
"cleanup",
"on",
"text",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L780-L791 | train |
dmlc/gluon-nlp | src/gluonnlp/data/transforms.py | BERTBasicTokenizer._is_control | def _is_control(self, char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char in ['\t', '\n', '\r']:
return False
cat = unicodedata.category(char)
if cat.start... | python | def _is_control(self, char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char in ['\t', '\n', '\r']:
return False
cat = unicodedata.category(char)
if cat.start... | [
"def",
"_is_control",
"(",
"self",
",",
"char",
")",
":",
"# These are technically control characters but we count them as whitespace",
"# characters.",
"if",
"char",
"in",
"[",
"'\\t'",
",",
"'\\n'",
",",
"'\\r'",
"]",
":",
"return",
"False",
"cat",
"=",
"unicodeda... | Checks whether `chars` is a control character. | [
"Checks",
"whether",
"chars",
"is",
"a",
"control",
"character",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L793-L802 | train |
dmlc/gluon-nlp | src/gluonnlp/data/transforms.py | BERTBasicTokenizer._run_split_on_punc | def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if self._is_punctuation(char):
output.append([char])
... | python | def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if self._is_punctuation(char):
output.append([char])
... | [
"def",
"_run_split_on_punc",
"(",
"self",
",",
"text",
")",
":",
"chars",
"=",
"list",
"(",
"text",
")",
"i",
"=",
"0",
"start_new_word",
"=",
"True",
"output",
"=",
"[",
"]",
"while",
"i",
"<",
"len",
"(",
"chars",
")",
":",
"char",
"=",
"chars",
... | Splits punctuation on a piece of text. | [
"Splits",
"punctuation",
"on",
"a",
"piece",
"of",
"text",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L850-L868 | train |
dmlc/gluon-nlp | src/gluonnlp/data/transforms.py | BERTBasicTokenizer._is_punctuation | def _is_punctuation(self, char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anywa... | python | def _is_punctuation(self, char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anywa... | [
"def",
"_is_punctuation",
"(",
"self",
",",
"char",
")",
":",
"cp",
"=",
"ord",
"(",
"char",
")",
"# We treat all non-letter/number ASCII as punctuation.",
"# Characters such as \"^\", \"$\", and \"`\" are not in the Unicode",
"# Punctuation class but we treat them as punctuation any... | Checks whether `chars` is a punctuation character. | [
"Checks",
"whether",
"chars",
"is",
"a",
"punctuation",
"character",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L870-L886 | train |
dmlc/gluon-nlp | src/gluonnlp/data/transforms.py | BERTBasicTokenizer._is_whitespace | def _is_whitespace(self, char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char in [' ', '\t', '\n', '\r']:
return True
c... | python | def _is_whitespace(self, char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char in [' ', '\t', '\n', '\r']:
return True
c... | [
"def",
"_is_whitespace",
"(",
"self",
",",
"char",
")",
":",
"# \\t, \\n, and \\r are technically contorl characters but we treat them",
"# as whitespace since they are generally considered as such.",
"if",
"char",
"in",
"[",
"' '",
",",
"'\\t'",
",",
"'\\n'",
",",
"'\\r'",
... | Checks whether `chars` is a whitespace character. | [
"Checks",
"whether",
"chars",
"is",
"a",
"whitespace",
"character",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L888-L897 | train |
dmlc/gluon-nlp | src/gluonnlp/data/transforms.py | BERTBasicTokenizer._whitespace_tokenize | def _whitespace_tokenize(self, text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
tokens = text.split()
return tokens | python | def _whitespace_tokenize(self, text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
tokens = text.split()
return tokens | [
"def",
"_whitespace_tokenize",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"tokens",
"=",
"text",
".",
"split",
"(",
")",
"return",
"tokens"
] | Runs basic whitespace cleaning and splitting on a piece of text. | [
"Runs",
"basic",
"whitespace",
"cleaning",
"and",
"splitting",
"on",
"a",
"piece",
"of",
"text",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L899-L903 | train |
dmlc/gluon-nlp | src/gluonnlp/data/transforms.py | BERTTokenizer._tokenize_wordpiece | def _tokenize_wordpiece(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
... | python | def _tokenize_wordpiece(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
... | [
"def",
"_tokenize_wordpiece",
"(",
"self",
",",
"text",
")",
":",
"output_tokens",
"=",
"[",
"]",
"for",
"token",
"in",
"self",
".",
"basic_tokenizer",
".",
"_whitespace_tokenize",
"(",
"text",
")",
":",
"chars",
"=",
"list",
"(",
"token",
")",
"if",
"le... | Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespa... | [
"Tokenizes",
"a",
"piece",
"of",
"text",
"into",
"its",
"word",
"pieces",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L960-L1007 | train |
dmlc/gluon-nlp | src/gluonnlp/data/transforms.py | BERTSentenceTransform._truncate_seq_pair | def _truncate_seq_pair(self, tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tok... | python | def _truncate_seq_pair(self, tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tok... | [
"def",
"_truncate_seq_pair",
"(",
"self",
",",
"tokens_a",
",",
"tokens_b",
",",
"max_length",
")",
":",
"# This is a simple heuristic which will always truncate the longer sequence",
"# one token at a time. This makes more sense than truncating an equal percent",
"# of tokens from each,... | Truncates a sequence pair in place to the maximum length. | [
"Truncates",
"a",
"sequence",
"pair",
"in",
"place",
"to",
"the",
"maximum",
"length",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L1144-L1157 | train |
dmlc/gluon-nlp | scripts/word_embeddings/evaluate_pretrained.py | get_args | def get_args():
"""Construct the argument parser."""
parser = argparse.ArgumentParser(
description='Word embedding evaluation with Gluon.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Embeddings arguments
group = parser.add_argument_group('Embedding arguments')
group.a... | python | def get_args():
"""Construct the argument parser."""
parser = argparse.ArgumentParser(
description='Word embedding evaluation with Gluon.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Embeddings arguments
group = parser.add_argument_group('Embedding arguments')
group.a... | [
"def",
"get_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Word embedding evaluation with Gluon.'",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"# Embeddings arguments",
"group",
... | Construct the argument parser. | [
"Construct",
"the",
"argument",
"parser",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluate_pretrained.py#L40-L97 | train |
dmlc/gluon-nlp | scripts/word_embeddings/evaluate_pretrained.py | validate_args | def validate_args(args):
"""Validate provided arguments and act on --help."""
if args.list_embedding_sources:
print('Listing all sources for {} embeddings.'.format(
args.embedding_name))
print('Specify --embedding-name if you wish to '
'list sources of other embeddings'... | python | def validate_args(args):
"""Validate provided arguments and act on --help."""
if args.list_embedding_sources:
print('Listing all sources for {} embeddings.'.format(
args.embedding_name))
print('Specify --embedding-name if you wish to '
'list sources of other embeddings'... | [
"def",
"validate_args",
"(",
"args",
")",
":",
"if",
"args",
".",
"list_embedding_sources",
":",
"print",
"(",
"'Listing all sources for {} embeddings.'",
".",
"format",
"(",
"args",
".",
"embedding_name",
")",
")",
"print",
"(",
"'Specify --embedding-name if you wish... | Validate provided arguments and act on --help. | [
"Validate",
"provided",
"arguments",
"and",
"act",
"on",
"--",
"help",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluate_pretrained.py#L100-L131 | train |
dmlc/gluon-nlp | scripts/word_embeddings/evaluate_pretrained.py | load_embedding_from_path | def load_embedding_from_path(args):
"""Load a TokenEmbedding."""
if args.embedding_path.endswith('.bin'):
with utils.print_time('load fastText model.'):
model = \
nlp.model.train.FasttextEmbeddingModel.load_fasttext_format(
args.embedding_path)
idx... | python | def load_embedding_from_path(args):
"""Load a TokenEmbedding."""
if args.embedding_path.endswith('.bin'):
with utils.print_time('load fastText model.'):
model = \
nlp.model.train.FasttextEmbeddingModel.load_fasttext_format(
args.embedding_path)
idx... | [
"def",
"load_embedding_from_path",
"(",
"args",
")",
":",
"if",
"args",
".",
"embedding_path",
".",
"endswith",
"(",
"'.bin'",
")",
":",
"with",
"utils",
".",
"print_time",
"(",
"'load fastText model.'",
")",
":",
"model",
"=",
"nlp",
".",
"model",
".",
"t... | Load a TokenEmbedding. | [
"Load",
"a",
"TokenEmbedding",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluate_pretrained.py#L134-L163 | train |
dmlc/gluon-nlp | scripts/bert/fp16_utils.py | grad_global_norm | def grad_global_norm(parameters, max_norm):
"""Calculate the 2-norm of gradients of parameters, and how much they should be scaled down
such that their 2-norm does not exceed `max_norm`.
If gradients exist for more than one context for a parameter, user needs to explicitly call
``trainer.allreduce_grad... | python | def grad_global_norm(parameters, max_norm):
"""Calculate the 2-norm of gradients of parameters, and how much they should be scaled down
such that their 2-norm does not exceed `max_norm`.
If gradients exist for more than one context for a parameter, user needs to explicitly call
``trainer.allreduce_grad... | [
"def",
"grad_global_norm",
"(",
"parameters",
",",
"max_norm",
")",
":",
"# collect gradient arrays",
"arrays",
"=",
"[",
"]",
"idx",
"=",
"0",
"for",
"p",
"in",
"parameters",
":",
"if",
"p",
".",
"grad_req",
"!=",
"'null'",
":",
"p_grads",
"=",
"p",
"."... | Calculate the 2-norm of gradients of parameters, and how much they should be scaled down
such that their 2-norm does not exceed `max_norm`.
If gradients exist for more than one context for a parameter, user needs to explicitly call
``trainer.allreduce_grads`` so that the gradients are summed first before c... | [
"Calculate",
"the",
"2",
"-",
"norm",
"of",
"gradients",
"of",
"parameters",
"and",
"how",
"much",
"they",
"should",
"be",
"scaled",
"down",
"such",
"that",
"their",
"2",
"-",
"norm",
"does",
"not",
"exceed",
"max_norm",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L26-L107 | train |
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 | train |
dmlc/gluon-nlp | scripts/bert/fp16_utils.py | FP16Trainer.step | def step(self, batch_size, max_norm=None):
"""Makes one step of parameter update. Should be called after
`fp16_optimizer.backward()`, and outside of `record()` scope.
Parameters
----------
batch_size : int
Batch size of data processed. Gradient will be normalized by ... | python | def step(self, batch_size, max_norm=None):
"""Makes one step of parameter update. Should be called after
`fp16_optimizer.backward()`, and outside of `record()` scope.
Parameters
----------
batch_size : int
Batch size of data processed. Gradient will be normalized by ... | [
"def",
"step",
"(",
"self",
",",
"batch_size",
",",
"max_norm",
"=",
"None",
")",
":",
"self",
".",
"fp32_trainer",
".",
"allreduce_grads",
"(",
")",
"step_size",
"=",
"batch_size",
"*",
"self",
".",
"_scaler",
".",
"loss_scale",
"if",
"max_norm",
":",
"... | Makes one step of parameter update. Should be called after
`fp16_optimizer.backward()`, and outside of `record()` scope.
Parameters
----------
batch_size : int
Batch size of data processed. Gradient will be normalized by `1/batch_size`.
Set this to 1 if you norma... | [
"Makes",
"one",
"step",
"of",
"parameter",
"update",
".",
"Should",
"be",
"called",
"after",
"fp16_optimizer",
".",
"backward",
"()",
"and",
"outside",
"of",
"record",
"()",
"scope",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L147-L183 | train |
dmlc/gluon-nlp | scripts/bert/fp16_utils.py | LossScaler.has_overflow | def has_overflow(self, params):
""" detect inf and nan """
is_not_finite = 0
for param in params:
if param.grad_req != 'null':
grad = param.list_grad()[0]
is_not_finite += mx.nd.contrib.isnan(grad).sum()
is_not_finite += mx.nd.contrib.i... | python | def has_overflow(self, params):
""" detect inf and nan """
is_not_finite = 0
for param in params:
if param.grad_req != 'null':
grad = param.list_grad()[0]
is_not_finite += mx.nd.contrib.isnan(grad).sum()
is_not_finite += mx.nd.contrib.i... | [
"def",
"has_overflow",
"(",
"self",
",",
"params",
")",
":",
"is_not_finite",
"=",
"0",
"for",
"param",
"in",
"params",
":",
"if",
"param",
".",
"grad_req",
"!=",
"'null'",
":",
"grad",
"=",
"param",
".",
"list_grad",
"(",
")",
"[",
"0",
"]",
"is_not... | detect inf and nan | [
"detect",
"inf",
"and",
"nan"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L187-L199 | train |
dmlc/gluon-nlp | scripts/bert/fp16_utils.py | DynamicLossScaler.update_scale | def update_scale(self, overflow):
"""dynamically update loss scale"""
iter_since_rescale = self._num_steps - self._last_rescale_iter
if overflow:
self._last_overflow_iter = self._num_steps
self._overflows_since_rescale += 1
percentage = self._overflows_since_r... | python | def update_scale(self, overflow):
"""dynamically update loss scale"""
iter_since_rescale = self._num_steps - self._last_rescale_iter
if overflow:
self._last_overflow_iter = self._num_steps
self._overflows_since_rescale += 1
percentage = self._overflows_since_r... | [
"def",
"update_scale",
"(",
"self",
",",
"overflow",
")",
":",
"iter_since_rescale",
"=",
"self",
".",
"_num_steps",
"-",
"self",
".",
"_last_rescale_iter",
"if",
"overflow",
":",
"self",
".",
"_last_overflow_iter",
"=",
"self",
".",
"_num_steps",
"self",
".",... | dynamically update loss scale | [
"dynamically",
"update",
"loss",
"scale"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L236-L253 | train |
dmlc/gluon-nlp | src/gluonnlp/data/sampler.py | FixedBucketSampler.stats | def stats(self):
"""Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
"""
ret = '{name}:\n' \
' sample_num={sample_num}, batch_num={batch_num}\n' \
... | python | def stats(self):
"""Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
"""
ret = '{name}:\n' \
' sample_num={sample_num}, batch_num={batch_num}\n' \
... | [
"def",
"stats",
"(",
"self",
")",
":",
"ret",
"=",
"'{name}:\\n'",
"' sample_num={sample_num}, batch_num={batch_num}\\n'",
"' key={bucket_keys}\\n'",
"' cnt={bucket_counts}\\n'",
"' batch_size={bucket_batch_sizes}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"__class_... | Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets. | [
"Return",
"a",
"string",
"representing",
"the",
"statistics",
"of",
"the",
"bucketing",
"sampler",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/sampler.py#L420-L439 | train |
dmlc/gluon-nlp | scripts/language_model/large_word_language_model.py | train | def train():
"""Training loop for language model.
"""
print(model)
from_epoch = 0
model.initialize(mx.init.Xavier(factor_type='out'), ctx=context)
trainer_params = {'learning_rate': args.lr, 'wd': 0, 'eps': args.eps}
trainer = gluon.Trainer(model.collect_params(), 'adagrad', trainer_params)
... | python | def train():
"""Training loop for language model.
"""
print(model)
from_epoch = 0
model.initialize(mx.init.Xavier(factor_type='out'), ctx=context)
trainer_params = {'learning_rate': args.lr, 'wd': 0, 'eps': args.eps}
trainer = gluon.Trainer(model.collect_params(), 'adagrad', trainer_params)
... | [
"def",
"train",
"(",
")",
":",
"print",
"(",
"model",
")",
"from_epoch",
"=",
"0",
"model",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"Xavier",
"(",
"factor_type",
"=",
"'out'",
")",
",",
"ctx",
"=",
"context",
")",
"trainer_params",
"=",
"{",
... | Training loop for language model. | [
"Training",
"loop",
"for",
"language",
"model",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/large_word_language_model.py#L210-L290 | train |
dmlc/gluon-nlp | scripts/language_model/large_word_language_model.py | evaluate | def evaluate():
""" Evaluate loop for the trained model """
print(eval_model)
eval_model.initialize(mx.init.Xavier(), ctx=context[0])
eval_model.hybridize(static_alloc=True, static_shape=True)
epoch = args.from_epoch if args.from_epoch else 0
while epoch < args.epochs:
checkpoint_name = ... | python | def evaluate():
""" Evaluate loop for the trained model """
print(eval_model)
eval_model.initialize(mx.init.Xavier(), ctx=context[0])
eval_model.hybridize(static_alloc=True, static_shape=True)
epoch = args.from_epoch if args.from_epoch else 0
while epoch < args.epochs:
checkpoint_name = ... | [
"def",
"evaluate",
"(",
")",
":",
"print",
"(",
"eval_model",
")",
"eval_model",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"Xavier",
"(",
")",
",",
"ctx",
"=",
"context",
"[",
"0",
"]",
")",
"eval_model",
".",
"hybridize",
"(",
"static_alloc",
... | Evaluate loop for the trained model | [
"Evaluate",
"loop",
"for",
"the",
"trained",
"model"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/large_word_language_model.py#L345-L367 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.