repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
micropython/micropython
ports/stm32/boards/make-pins.py
AlternateFunction.print
def print(self): """Prints the C representation of this AF.""" cond_var = None if self.supported: cond_var = conditional_var('{}{}'.format(self.func, self.fn_num)) print_conditional_if(cond_var) print(' AF', end='') else: print(' //', en...
python
def print(self): """Prints the C representation of this AF.""" cond_var = None if self.supported: cond_var = conditional_var('{}{}'.format(self.func, self.fn_num)) print_conditional_if(cond_var) print(' AF', end='') else: print(' //', en...
[ "def", "print", "(", "self", ")", ":", "cond_var", "=", "None", "if", "self", ".", "supported", ":", "cond_var", "=", "conditional_var", "(", "'{}{}'", ".", "format", "(", "self", ".", "func", ",", "self", ".", "fn_num", ")", ")", "print_conditional_if",...
Prints the C representation of this AF.
[ "Prints", "the", "C", "representation", "of", "this", "AF", "." ]
8031b7a25c21fb864fe9dd1fa40740030be66c11
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/ports/stm32/boards/make-pins.py#L121-L135
train
micropython/micropython
ports/cc3200/boards/make-pins.py
parse_port_pin
def parse_port_pin(name_str): """Parses a string and returns a (port, gpio_bit) tuple.""" if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 characters") if name_str[:2] != 'GP': raise ValueError("Expecting pin name to start with GP") if not name_str[2:].isdigit(...
python
def parse_port_pin(name_str): """Parses a string and returns a (port, gpio_bit) tuple.""" if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 characters") if name_str[:2] != 'GP': raise ValueError("Expecting pin name to start with GP") if not name_str[2:].isdigit(...
[ "def", "parse_port_pin", "(", "name_str", ")", ":", "if", "len", "(", "name_str", ")", "<", "3", ":", "raise", "ValueError", "(", "\"Expecting pin name to be at least 3 characters\"", ")", "if", "name_str", "[", ":", "2", "]", "!=", "'GP'", ":", "raise", "Va...
Parses a string and returns a (port, gpio_bit) tuple.
[ "Parses", "a", "string", "and", "returns", "a", "(", "port", "gpio_bit", ")", "tuple", "." ]
8031b7a25c21fb864fe9dd1fa40740030be66c11
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/ports/cc3200/boards/make-pins.py#L20-L30
train
onnx/onnx
onnx/backend/base.py
Backend.run_node
def run_node(cls, node, # type: NodeProto inputs, # type: Any device='CPU', # type: Text outputs_info=None, # type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]] **kwargs # type: Dict[Text, Any] ): # ty...
python
def run_node(cls, node, # type: NodeProto inputs, # type: Any device='CPU', # type: Text outputs_info=None, # type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]] **kwargs # type: Dict[Text, Any] ): # ty...
[ "def", "run_node", "(", "cls", ",", "node", ",", "# type: NodeProto", "inputs", ",", "# type: Any", "device", "=", "'CPU'", ",", "# type: Text", "outputs_info", "=", "None", ",", "# type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]]", "*", "*", "kwargs", "#...
Simple run one operator and return the results. Args: outputs_info: a list of tuples, which contains the element type and shape of each output. First element of the tuple is the dtype, and the second element is the shape. More use case can be found in https://gith...
[ "Simple", "run", "one", "operator", "and", "return", "the", "results", ".", "Args", ":", "outputs_info", ":", "a", "list", "of", "tuples", "which", "contains", "the", "element", "type", "and", "shape", "of", "each", "output", ".", "First", "element", "of",...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/backend/base.py#L89-L111
train
onnx/onnx
onnx/external_data_helper.py
load_external_data_for_tensor
def load_external_data_for_tensor(tensor, base_dir): # type: (TensorProto, Text) -> None """ Load data from an external file for tensor. @params tensor: a TensorProto object. base_dir: directory that contains the external data. """ if tensor.HasField("raw_data"): # already loaded ...
python
def load_external_data_for_tensor(tensor, base_dir): # type: (TensorProto, Text) -> None """ Load data from an external file for tensor. @params tensor: a TensorProto object. base_dir: directory that contains the external data. """ if tensor.HasField("raw_data"): # already loaded ...
[ "def", "load_external_data_for_tensor", "(", "tensor", ",", "base_dir", ")", ":", "# type: (TensorProto, Text) -> None", "if", "tensor", ".", "HasField", "(", "\"raw_data\"", ")", ":", "# already loaded", "return", "info", "=", "ExternalDataInfo", "(", "tensor", ")", ...
Load data from an external file for tensor. @params tensor: a TensorProto object. base_dir: directory that contains the external data.
[ "Load", "data", "from", "an", "external", "file", "for", "tensor", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L32-L54
train
onnx/onnx
onnx/external_data_helper.py
load_external_data_for_model
def load_external_data_for_model(model, base_dir): # type: (ModelProto, Text) -> None """ Loads external tensors into model @params model: ModelProto to load external data to base_dir: directory that contains external data """ for tensor in _get_all_tensors(model): if uses_external...
python
def load_external_data_for_model(model, base_dir): # type: (ModelProto, Text) -> None """ Loads external tensors into model @params model: ModelProto to load external data to base_dir: directory that contains external data """ for tensor in _get_all_tensors(model): if uses_external...
[ "def", "load_external_data_for_model", "(", "model", ",", "base_dir", ")", ":", "# type: (ModelProto, Text) -> None", "for", "tensor", "in", "_get_all_tensors", "(", "model", ")", ":", "if", "uses_external_data", "(", "tensor", ")", ":", "load_external_data_for_tensor",...
Loads external tensors into model @params model: ModelProto to load external data to base_dir: directory that contains external data
[ "Loads", "external", "tensors", "into", "model" ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L57-L67
train
onnx/onnx
onnx/external_data_helper.py
convert_model_to_external_data
def convert_model_to_external_data(model, all_tensors_to_one_file=True, location=None): # type: (ModelProto, bool, Optional[Text]) -> None """ call to set all tensors as external data. save_model saves all the tensors data as external data after calling this function. @params model: ModelProto to be...
python
def convert_model_to_external_data(model, all_tensors_to_one_file=True, location=None): # type: (ModelProto, bool, Optional[Text]) -> None """ call to set all tensors as external data. save_model saves all the tensors data as external data after calling this function. @params model: ModelProto to be...
[ "def", "convert_model_to_external_data", "(", "model", ",", "all_tensors_to_one_file", "=", "True", ",", "location", "=", "None", ")", ":", "# type: (ModelProto, bool, Optional[Text]) -> None", "if", "all_tensors_to_one_file", ":", "file_name", "=", "Text", "(", "uuid", ...
call to set all tensors as external data. save_model saves all the tensors data as external data after calling this function. @params model: ModelProto to be converted. all_tensors_to_one_file: If true, save all tensors to one external file specified by location. If false, save ...
[ "call", "to", "set", "all", "tensors", "as", "external", "data", ".", "save_model", "saves", "all", "the", "tensors", "data", "as", "external", "data", "after", "calling", "this", "function", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L92-L111
train
onnx/onnx
onnx/external_data_helper.py
convert_model_from_external_data
def convert_model_from_external_data(model): # type: (ModelProto) -> None """ call to set all tensors data as embedded data. save_model saves all the tensors data as embedded data after calling this function. @params model: ModelProto to be converted. """ for tensor in _get_all_tensors(model): ...
python
def convert_model_from_external_data(model): # type: (ModelProto) -> None """ call to set all tensors data as embedded data. save_model saves all the tensors data as embedded data after calling this function. @params model: ModelProto to be converted. """ for tensor in _get_all_tensors(model): ...
[ "def", "convert_model_from_external_data", "(", "model", ")", ":", "# type: (ModelProto) -> None", "for", "tensor", "in", "_get_all_tensors", "(", "model", ")", ":", "if", "uses_external_data", "(", "tensor", ")", ":", "if", "not", "tensor", ".", "HasField", "(", ...
call to set all tensors data as embedded data. save_model saves all the tensors data as embedded data after calling this function. @params model: ModelProto to be converted.
[ "call", "to", "set", "all", "tensors", "data", "as", "embedded", "data", ".", "save_model", "saves", "all", "the", "tensors", "data", "as", "embedded", "data", "after", "calling", "this", "function", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L114-L125
train
onnx/onnx
onnx/external_data_helper.py
save_external_data
def save_external_data(tensor, base_path): # type: (TensorProto, Text) -> None """ Write tensor data to an external file according to information in the `external_data` field. @params tensor: Tensor object to be serialized base_path: System path of a folder where tensor data is to be stored ""...
python
def save_external_data(tensor, base_path): # type: (TensorProto, Text) -> None """ Write tensor data to an external file according to information in the `external_data` field. @params tensor: Tensor object to be serialized base_path: System path of a folder where tensor data is to be stored ""...
[ "def", "save_external_data", "(", "tensor", ",", "base_path", ")", ":", "# type: (TensorProto, Text) -> None", "info", "=", "ExternalDataInfo", "(", "tensor", ")", "external_data_file_path", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "info", ".", ...
Write tensor data to an external file according to information in the `external_data` field. @params tensor: Tensor object to be serialized base_path: System path of a folder where tensor data is to be stored
[ "Write", "tensor", "data", "to", "an", "external", "file", "according", "to", "information", "in", "the", "external_data", "field", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L128-L159
train
onnx/onnx
onnx/external_data_helper.py
_get_attribute_tensors
def _get_attribute_tensors(onnx_model_proto): # type: (ModelProto) -> Iterable[TensorProto] """Create an iterator of tensors from node attributes of an ONNX model.""" for node in onnx_model_proto.graph.node: for attribute in node.attribute: if attribute.HasField("t"): yield ...
python
def _get_attribute_tensors(onnx_model_proto): # type: (ModelProto) -> Iterable[TensorProto] """Create an iterator of tensors from node attributes of an ONNX model.""" for node in onnx_model_proto.graph.node: for attribute in node.attribute: if attribute.HasField("t"): yield ...
[ "def", "_get_attribute_tensors", "(", "onnx_model_proto", ")", ":", "# type: (ModelProto) -> Iterable[TensorProto]", "for", "node", "in", "onnx_model_proto", ".", "graph", ".", "node", ":", "for", "attribute", "in", "node", ".", "attribute", ":", "if", "attribute", ...
Create an iterator of tensors from node attributes of an ONNX model.
[ "Create", "an", "iterator", "of", "tensors", "from", "node", "attributes", "of", "an", "ONNX", "model", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L174-L181
train
onnx/onnx
onnx/external_data_helper.py
remove_external_data_field
def remove_external_data_field(tensor, field_key): # type: (TensorProto, Text) -> None """ Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be remove...
python
def remove_external_data_field(tensor, field_key): # type: (TensorProto, Text) -> None """ Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be remove...
[ "def", "remove_external_data_field", "(", "tensor", ",", "field_key", ")", ":", "# type: (TensorProto, Text) -> None", "for", "(", "i", ",", "field", ")", "in", "enumerate", "(", "tensor", ".", "external_data", ")", ":", "if", "field", ".", "key", "==", "field...
Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be removed
[ "Remove", "a", "field", "from", "a", "Tensor", "s", "external_data", "key", "-", "value", "store", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L197-L209
train
onnx/onnx
onnx/external_data_helper.py
write_external_data_tensors
def write_external_data_tensors(model, filepath): # type: (ModelProto, Text) -> ModelProto """ Write external data of all tensors to files on disk. Note: This function also strips basepath information from all tensors' external_data fields. @params model: Model object which is the source of tenso...
python
def write_external_data_tensors(model, filepath): # type: (ModelProto, Text) -> ModelProto """ Write external data of all tensors to files on disk. Note: This function also strips basepath information from all tensors' external_data fields. @params model: Model object which is the source of tenso...
[ "def", "write_external_data_tensors", "(", "model", ",", "filepath", ")", ":", "# type: (ModelProto, Text) -> ModelProto", "for", "tensor", "in", "_get_all_tensors", "(", "model", ")", ":", "if", "uses_external_data", "(", "tensor", ")", ":", "save_external_data", "("...
Write external data of all tensors to files on disk. Note: This function also strips basepath information from all tensors' external_data fields. @params model: Model object which is the source of tensors to serialize. filepath: System path to the directory which should be treated as base path for ext...
[ "Write", "external", "data", "of", "all", "tensors", "to", "files", "on", "disk", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L212-L230
train
onnx/onnx
tools/protoc-gen-mypy.py
PkgWriter._import
def _import(self, path, name): # type: (Text, Text) -> Text """Imports a stdlib path and returns a handle to it eg. self._import("typing", "Optional") -> "Optional" """ imp = path.replace('/', '.') self.imports[imp].add(name) return name
python
def _import(self, path, name): # type: (Text, Text) -> Text """Imports a stdlib path and returns a handle to it eg. self._import("typing", "Optional") -> "Optional" """ imp = path.replace('/', '.') self.imports[imp].add(name) return name
[ "def", "_import", "(", "self", ",", "path", ",", "name", ")", ":", "# type: (Text, Text) -> Text", "imp", "=", "path", ".", "replace", "(", "'/'", ",", "'.'", ")", "self", ".", "imports", "[", "imp", "]", ".", "add", "(", "name", ")", "return", "name...
Imports a stdlib path and returns a handle to it eg. self._import("typing", "Optional") -> "Optional"
[ "Imports", "a", "stdlib", "path", "and", "returns", "a", "handle", "to", "it", "eg", ".", "self", ".", "_import", "(", "typing", "Optional", ")", "-", ">", "Optional" ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/tools/protoc-gen-mypy.py#L74-L81
train
onnx/onnx
tools/protoc-gen-mypy.py
PkgWriter._import_message
def _import_message(self, type_name): # type: (d.FieldDescriptorProto) -> Text """Import a referenced message and return a handle""" name = cast(Text, type_name) if name[0] == '.' and name[1].isupper() and name[2].islower(): # Message defined in this file return ...
python
def _import_message(self, type_name): # type: (d.FieldDescriptorProto) -> Text """Import a referenced message and return a handle""" name = cast(Text, type_name) if name[0] == '.' and name[1].isupper() and name[2].islower(): # Message defined in this file return ...
[ "def", "_import_message", "(", "self", ",", "type_name", ")", ":", "# type: (d.FieldDescriptorProto) -> Text", "name", "=", "cast", "(", "Text", ",", "type_name", ")", "if", "name", "[", "0", "]", "==", "'.'", "and", "name", "[", "1", "]", ".", "isupper", ...
Import a referenced message and return a handle
[ "Import", "a", "referenced", "message", "and", "return", "a", "handle" ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/tools/protoc-gen-mypy.py#L83-L112
train
onnx/onnx
setup.py
mypy_type_check.run
def run(self): """Run command.""" onnx_script = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py")) returncode = subprocess.call([sys.executable, onnx_script]) sys.exit(returncode)
python
def run(self): """Run command.""" onnx_script = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py")) returncode = subprocess.call([sys.executable, onnx_script]) sys.exit(returncode)
[ "def", "run", "(", "self", ")", ":", "onnx_script", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",", "\...
Run command.
[ "Run", "command", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/setup.py#L252-L256
train
onnx/onnx
onnx/helper.py
make_node
def make_node( op_type, # type: Text inputs, # type: Sequence[Text] outputs, # type: Sequence[Text] name=None, # type: Optional[Text] doc_string=None, # type: Optional[Text] domain=None, # type: Optional[Text] **kwargs # type: Any ): # type: (...) -> NodeP...
python
def make_node( op_type, # type: Text inputs, # type: Sequence[Text] outputs, # type: Sequence[Text] name=None, # type: Optional[Text] doc_string=None, # type: Optional[Text] domain=None, # type: Optional[Text] **kwargs # type: Any ): # type: (...) -> NodeP...
[ "def", "make_node", "(", "op_type", ",", "# type: Text", "inputs", ",", "# type: Sequence[Text]", "outputs", ",", "# type: Sequence[Text]", "name", "=", "None", ",", "# type: Optional[Text]", "doc_string", "=", "None", ",", "# type: Optional[Text]", "domain", "=", "No...
Construct a NodeProto. Arguments: op_type (string): The name of the operator to construct inputs (list of string): list of input names outputs (list of string): list of output names name (string, default None): optional unique identifier for NodeProto doc_string (string, def...
[ "Construct", "a", "NodeProto", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L20-L57
train
onnx/onnx
onnx/helper.py
make_operatorsetid
def make_operatorsetid( domain, # type: Text version, # type: int ): # type: (...) -> OperatorSetIdProto """Construct an OperatorSetIdProto. Arguments: domain (string): The domain of the operator set id version (integer): Version of operator set id """ operatorsetid =...
python
def make_operatorsetid( domain, # type: Text version, # type: int ): # type: (...) -> OperatorSetIdProto """Construct an OperatorSetIdProto. Arguments: domain (string): The domain of the operator set id version (integer): Version of operator set id """ operatorsetid =...
[ "def", "make_operatorsetid", "(", "domain", ",", "# type: Text", "version", ",", "# type: int", ")", ":", "# type: (...) -> OperatorSetIdProto", "operatorsetid", "=", "OperatorSetIdProto", "(", ")", "operatorsetid", ".", "domain", "=", "domain", "operatorsetid", ".", ...
Construct an OperatorSetIdProto. Arguments: domain (string): The domain of the operator set id version (integer): Version of operator set id
[ "Construct", "an", "OperatorSetIdProto", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L60-L73
train
onnx/onnx
onnx/helper.py
_to_bytes_or_false
def _to_bytes_or_false(val): # type: (Union[Text, bytes]) -> Union[bytes, bool] """An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicod...
python
def _to_bytes_or_false(val): # type: (Union[Text, bytes]) -> Union[bytes, bool] """An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicod...
[ "def", "_to_bytes_or_false", "(", "val", ")", ":", "# type: (Union[Text, bytes]) -> Union[bytes, bool]", "if", "isinstance", "(", "val", ",", "bytes", ")", ":", "return", "val", "else", ":", "try", ":", "return", "val", ".", "encode", "(", "'utf-8'", ")", "exc...
An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicode or py3 str: return val.decode('utf-8') - Otherwise, return False
[ "An", "internal", "graph", "to", "convert", "the", "input", "to", "a", "bytes", "or", "to", "False", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L179-L194
train
onnx/onnx
onnx/helper.py
make_attribute
def make_attribute( key, # type: Text value, # type: Any doc_string=None # type: Optional[Text] ): # type: (...) -> AttributeProto """Makes an AttributeProto based on the value type.""" attr = AttributeProto() attr.name = key if doc_string: attr.doc_string = doc_strin...
python
def make_attribute( key, # type: Text value, # type: Any doc_string=None # type: Optional[Text] ): # type: (...) -> AttributeProto """Makes an AttributeProto based on the value type.""" attr = AttributeProto() attr.name = key if doc_string: attr.doc_string = doc_strin...
[ "def", "make_attribute", "(", "key", ",", "# type: Text", "value", ",", "# type: Any", "doc_string", "=", "None", "# type: Optional[Text]", ")", ":", "# type: (...) -> AttributeProto", "attr", "=", "AttributeProto", "(", ")", "attr", ".", "name", "=", "key", "if",...
Makes an AttributeProto based on the value type.
[ "Makes", "an", "AttributeProto", "based", "on", "the", "value", "type", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L197-L256
train
onnx/onnx
onnx/helper.py
make_tensor_value_info
def make_tensor_value_info( name, # type: Text elem_type, # type: int shape, # type: Optional[Sequence[Union[Text, int]]] doc_string="", # type: Text shape_denotation=None, # type: Optional[List[Text]] ): # type: (...) -> ValueInfoProto """Makes a ValueInfoProto based o...
python
def make_tensor_value_info( name, # type: Text elem_type, # type: int shape, # type: Optional[Sequence[Union[Text, int]]] doc_string="", # type: Text shape_denotation=None, # type: Optional[List[Text]] ): # type: (...) -> ValueInfoProto """Makes a ValueInfoProto based o...
[ "def", "make_tensor_value_info", "(", "name", ",", "# type: Text", "elem_type", ",", "# type: int", "shape", ",", "# type: Optional[Sequence[Union[Text, int]]]", "doc_string", "=", "\"\"", ",", "# type: Text", "shape_denotation", "=", "None", ",", "# type: Optional[List[Tex...
Makes a ValueInfoProto based on the data type and shape.
[ "Makes", "a", "ValueInfoProto", "based", "on", "the", "data", "type", "and", "shape", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L290-L340
train
onnx/onnx
onnx/helper.py
strip_doc_string
def strip_doc_string(proto): # type: (google.protobuf.message.Message) -> None """ Empties `doc_string` field on any nested protobuf messages """ assert isinstance(proto, google.protobuf.message.Message) for descriptor in proto.DESCRIPTOR.fields: if descriptor.name == 'doc_string': ...
python
def strip_doc_string(proto): # type: (google.protobuf.message.Message) -> None """ Empties `doc_string` field on any nested protobuf messages """ assert isinstance(proto, google.protobuf.message.Message) for descriptor in proto.DESCRIPTOR.fields: if descriptor.name == 'doc_string': ...
[ "def", "strip_doc_string", "(", "proto", ")", ":", "# type: (google.protobuf.message.Message) -> None", "assert", "isinstance", "(", "proto", ",", "google", ".", "protobuf", ".", "message", ".", "Message", ")", "for", "descriptor", "in", "proto", ".", "DESCRIPTOR", ...
Empties `doc_string` field on any nested protobuf messages
[ "Empties", "doc_string", "field", "on", "any", "nested", "protobuf", "messages" ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L538-L551
train
onnx/onnx
onnx/numpy_helper.py
to_array
def to_array(tensor): # type: (TensorProto) -> np.ndarray[Any] """Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. Returns: arr: the converted array. """ if tensor.HasField("segment"): raise ValueError( "Currently not supporti...
python
def to_array(tensor): # type: (TensorProto) -> np.ndarray[Any] """Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. Returns: arr: the converted array. """ if tensor.HasField("segment"): raise ValueError( "Currently not supporti...
[ "def", "to_array", "(", "tensor", ")", ":", "# type: (TensorProto) -> np.ndarray[Any]", "if", "tensor", ".", "HasField", "(", "\"segment\"", ")", ":", "raise", "ValueError", "(", "\"Currently not supporting loading segments.\"", ")", "if", "tensor", ".", "data_type", ...
Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. Returns: arr: the converted array.
[ "Converts", "a", "tensor", "def", "object", "to", "a", "numpy", "array", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/numpy_helper.py#L24-L66
train
onnx/onnx
onnx/numpy_helper.py
from_array
def from_array(arr, name=None): # type: (np.ndarray[Any], Optional[Text]) -> TensorProto """Converts a numpy array to a tensor def. Inputs: arr: a numpy array. name: (optional) the name of the tensor. Returns: tensor_def: the converted tensor def. """ tensor = TensorProto()...
python
def from_array(arr, name=None): # type: (np.ndarray[Any], Optional[Text]) -> TensorProto """Converts a numpy array to a tensor def. Inputs: arr: a numpy array. name: (optional) the name of the tensor. Returns: tensor_def: the converted tensor def. """ tensor = TensorProto()...
[ "def", "from_array", "(", "arr", ",", "name", "=", "None", ")", ":", "# type: (np.ndarray[Any], Optional[Text]) -> TensorProto", "tensor", "=", "TensorProto", "(", ")", "tensor", ".", "dims", ".", "extend", "(", "arr", ".", "shape", ")", "if", "name", ":", "...
Converts a numpy array to a tensor def. Inputs: arr: a numpy array. name: (optional) the name of the tensor. Returns: tensor_def: the converted tensor def.
[ "Converts", "a", "numpy", "array", "to", "a", "tensor", "def", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/numpy_helper.py#L69-L117
train
onnx/onnx
onnx/__init__.py
_serialize
def _serialize(proto): # type: (Union[bytes, google.protobuf.message.Message]) -> bytes ''' Serialize a in-memory proto to bytes @params proto is a in-memory proto, such as a ModelProto, TensorProto, etc @return Serialized proto in bytes ''' if isinstance(proto, bytes): return...
python
def _serialize(proto): # type: (Union[bytes, google.protobuf.message.Message]) -> bytes ''' Serialize a in-memory proto to bytes @params proto is a in-memory proto, such as a ModelProto, TensorProto, etc @return Serialized proto in bytes ''' if isinstance(proto, bytes): return...
[ "def", "_serialize", "(", "proto", ")", ":", "# type: (Union[bytes, google.protobuf.message.Message]) -> bytes", "if", "isinstance", "(", "proto", ",", "bytes", ")", ":", "return", "proto", "elif", "hasattr", "(", "proto", ",", "'SerializeToString'", ")", "and", "ca...
Serialize a in-memory proto to bytes @params proto is a in-memory proto, such as a ModelProto, TensorProto, etc @return Serialized proto in bytes
[ "Serialize", "a", "in", "-", "memory", "proto", "to", "bytes" ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/__init__.py#L53-L70
train
onnx/onnx
onnx/__init__.py
_deserialize
def _deserialize(s, proto): # type: (bytes, _Proto) -> _Proto ''' Parse bytes into a in-memory proto @params s is bytes containing serialized proto proto is a in-memory proto object @return The proto instance filled in by s ''' if not isinstance(s, bytes): raise ValueError...
python
def _deserialize(s, proto): # type: (bytes, _Proto) -> _Proto ''' Parse bytes into a in-memory proto @params s is bytes containing serialized proto proto is a in-memory proto object @return The proto instance filled in by s ''' if not isinstance(s, bytes): raise ValueError...
[ "def", "_deserialize", "(", "s", ",", "proto", ")", ":", "# type: (bytes, _Proto) -> _Proto", "if", "not", "isinstance", "(", "s", ",", "bytes", ")", ":", "raise", "ValueError", "(", "'Parameter s must be bytes, but got type: {}'", ".", "format", "(", "type", "(",...
Parse bytes into a in-memory proto @params s is bytes containing serialized proto proto is a in-memory proto object @return The proto instance filled in by s
[ "Parse", "bytes", "into", "a", "in", "-", "memory", "proto" ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/__init__.py#L76-L99
train
onnx/onnx
onnx/__init__.py
load_model
def load_model(f, format=None, load_external_data=True): # type: (Union[IO[bytes], Text], Optional[Any], bool) -> ModelProto ''' Loads a serialized ModelProto into memory @params f can be a file-like object (has "read" function) or a string containing a file name format is for future use @ret...
python
def load_model(f, format=None, load_external_data=True): # type: (Union[IO[bytes], Text], Optional[Any], bool) -> ModelProto ''' Loads a serialized ModelProto into memory @params f can be a file-like object (has "read" function) or a string containing a file name format is for future use @ret...
[ "def", "load_model", "(", "f", ",", "format", "=", "None", ",", "load_external_data", "=", "True", ")", ":", "# type: (Union[IO[bytes], Text], Optional[Any], bool) -> ModelProto", "s", "=", "_load_bytes", "(", "f", ")", "model", "=", "load_model_from_string", "(", "...
Loads a serialized ModelProto into memory @params f can be a file-like object (has "read" function) or a string containing a file name format is for future use @return Loaded in-memory ModelProto
[ "Loads", "a", "serialized", "ModelProto", "into", "memory" ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/__init__.py#L102-L122
train
onnx/onnx
onnx/__init__.py
load_tensor
def load_tensor(f, format=None): # type: (Union[IO[bytes], Text], Optional[Any]) -> TensorProto ''' Loads a serialized TensorProto into memory @params f can be a file-like object (has "read" function) or a string containing a file name format is for future use @return Loaded in-memory Ten...
python
def load_tensor(f, format=None): # type: (Union[IO[bytes], Text], Optional[Any]) -> TensorProto ''' Loads a serialized TensorProto into memory @params f can be a file-like object (has "read" function) or a string containing a file name format is for future use @return Loaded in-memory Ten...
[ "def", "load_tensor", "(", "f", ",", "format", "=", "None", ")", ":", "# type: (Union[IO[bytes], Text], Optional[Any]) -> TensorProto", "s", "=", "_load_bytes", "(", "f", ")", "return", "load_tensor_from_string", "(", "s", ",", "format", "=", "format", ")" ]
Loads a serialized TensorProto into memory @params f can be a file-like object (has "read" function) or a string containing a file name format is for future use @return Loaded in-memory TensorProto
[ "Loads", "a", "serialized", "TensorProto", "into", "memory" ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/__init__.py#L125-L137
train
onnx/onnx
onnx/__init__.py
save_model
def save_model(proto, f, format=None): # type: (Union[ModelProto, bytes], Union[IO[bytes], Text], Optional[Any]) -> None ''' Saves the ModelProto to the specified path. @params proto should be a in-memory ModelProto f can be a file-like object (has "write" function) or a string containing a file n...
python
def save_model(proto, f, format=None): # type: (Union[ModelProto, bytes], Union[IO[bytes], Text], Optional[Any]) -> None ''' Saves the ModelProto to the specified path. @params proto should be a in-memory ModelProto f can be a file-like object (has "write" function) or a string containing a file n...
[ "def", "save_model", "(", "proto", ",", "f", ",", "format", "=", "None", ")", ":", "# type: (Union[ModelProto, bytes], Union[IO[bytes], Text], Optional[Any]) -> None", "if", "isinstance", "(", "proto", ",", "bytes", ")", ":", "proto", "=", "_deserialize", "(", "prot...
Saves the ModelProto to the specified path. @params proto should be a in-memory ModelProto f can be a file-like object (has "write" function) or a string containing a file name format is for future use
[ "Saves", "the", "ModelProto", "to", "the", "specified", "path", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/__init__.py#L168-L186
train
onnx/onnx
onnx/utils.py
polish_model
def polish_model(model): # type: (ModelProto) -> ModelProto ''' This function combines several useful utility functions together. ''' onnx.checker.check_model(model) onnx.helper.strip_doc_string(model) model = onnx.shape_inference.infer_shapes(model) model = onnx.optimizer.optimize(mode...
python
def polish_model(model): # type: (ModelProto) -> ModelProto ''' This function combines several useful utility functions together. ''' onnx.checker.check_model(model) onnx.helper.strip_doc_string(model) model = onnx.shape_inference.infer_shapes(model) model = onnx.optimizer.optimize(mode...
[ "def", "polish_model", "(", "model", ")", ":", "# type: (ModelProto) -> ModelProto", "onnx", ".", "checker", ".", "check_model", "(", "model", ")", "onnx", ".", "helper", ".", "strip_doc_string", "(", "model", ")", "model", "=", "onnx", ".", "shape_inference", ...
This function combines several useful utility functions together.
[ "This", "function", "combines", "several", "useful", "utility", "functions", "together", "." ]
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/utils.py#L14-L23
train
apache/incubator-mxnet
python/mxnet/gluon/contrib/rnn/rnn_cell.py
dynamic_unroll
def dynamic_unroll(cell, inputs, begin_state, drop_inputs=0, drop_outputs=0, layout='TNC', valid_length=None): """Unrolls an RNN cell across time steps. Currently, 'TNC' is a preferred layout. unroll on the input of this layout runs much faster. Parameters ---------- cell : ...
python
def dynamic_unroll(cell, inputs, begin_state, drop_inputs=0, drop_outputs=0, layout='TNC', valid_length=None): """Unrolls an RNN cell across time steps. Currently, 'TNC' is a preferred layout. unroll on the input of this layout runs much faster. Parameters ---------- cell : ...
[ "def", "dynamic_unroll", "(", "cell", ",", "inputs", ",", "begin_state", ",", "drop_inputs", "=", "0", ",", "drop_outputs", "=", "0", ",", "layout", "=", "'TNC'", ",", "valid_length", "=", "None", ")", ":", "# Merge is always True, so we don't need length.", "in...
Unrolls an RNN cell across time steps. Currently, 'TNC' is a preferred layout. unroll on the input of this layout runs much faster. Parameters ---------- cell : an object whose base class is RNNCell. The RNN cell to run on the input sequence. inputs : Symbol It should have shap...
[ "Unrolls", "an", "RNN", "cell", "across", "time", "steps", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/contrib/rnn/rnn_cell.py#L326-L437
train
apache/incubator-mxnet
python/mxnet/gluon/contrib/rnn/rnn_cell.py
VariationalDropoutCell.unroll
def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None, valid_length=None): """Unrolls an RNN cell across time steps. Parameters ---------- length : int Number of steps to unroll. inputs : Symbol, list of Symbol, or None ...
python
def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None, valid_length=None): """Unrolls an RNN cell across time steps. Parameters ---------- length : int Number of steps to unroll. inputs : Symbol, list of Symbol, or None ...
[ "def", "unroll", "(", "self", ",", "length", ",", "inputs", ",", "begin_state", "=", "None", ",", "layout", "=", "'NTC'", ",", "merge_outputs", "=", "None", ",", "valid_length", "=", "None", ")", ":", "# Dropout on inputs and outputs can be performed on the whole ...
Unrolls an RNN cell across time steps. Parameters ---------- length : int Number of steps to unroll. inputs : Symbol, list of Symbol, or None If `inputs` is a single Symbol (usually the output of Embedding symbol), it should have shape (ba...
[ "Unrolls", "an", "RNN", "cell", "across", "time", "steps", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/contrib/rnn/rnn_cell.py#L117-L195
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
_fix_attribute_names
def _fix_attribute_names(attrs, change_map): """ Change attribute names as per values in change_map dictionary. Parameters ---------- :param attrs : dict Dict of operator attributes :param change_map : dict Dict of onnx attribute name to mxnet attribute names. Returns ------- :retur...
python
def _fix_attribute_names(attrs, change_map): """ Change attribute names as per values in change_map dictionary. Parameters ---------- :param attrs : dict Dict of operator attributes :param change_map : dict Dict of onnx attribute name to mxnet attribute names. Returns ------- :retur...
[ "def", "_fix_attribute_names", "(", "attrs", ",", "change_map", ")", ":", "new_attr", "=", "{", "}", "for", "k", "in", "attrs", ".", "keys", "(", ")", ":", "if", "k", "in", "change_map", ":", "new_attr", "[", "change_map", "[", "k", "]", "]", "=", ...
Change attribute names as per values in change_map dictionary. Parameters ---------- :param attrs : dict Dict of operator attributes :param change_map : dict Dict of onnx attribute name to mxnet attribute names. Returns ------- :return new_attr : dict Converted dict of operator attributes.
[ "Change", "attribute", "names", "as", "per", "values", "in", "change_map", "dictionary", ".", "Parameters", "----------", ":", "param", "attrs", ":", "dict", "Dict", "of", "operator", "attributes", ":", "param", "change_map", ":", "dict", "Dict", "of", "onnx",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L29-L47
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
_remove_attributes
def _remove_attributes(attrs, remove_list): """ Removes attributes in the remove list from the input attribute dict :param attrs : Dict of operator attributes :param remove_list : list of attributes to be removed :return new_attr : Dict of operator attributes without the listed attributes. """ ...
python
def _remove_attributes(attrs, remove_list): """ Removes attributes in the remove list from the input attribute dict :param attrs : Dict of operator attributes :param remove_list : list of attributes to be removed :return new_attr : Dict of operator attributes without the listed attributes. """ ...
[ "def", "_remove_attributes", "(", "attrs", ",", "remove_list", ")", ":", "new_attrs", "=", "{", "}", "for", "attr", "in", "attrs", ".", "keys", "(", ")", ":", "if", "attr", "not", "in", "remove_list", ":", "new_attrs", "[", "attr", "]", "=", "attrs", ...
Removes attributes in the remove list from the input attribute dict :param attrs : Dict of operator attributes :param remove_list : list of attributes to be removed :return new_attr : Dict of operator attributes without the listed attributes.
[ "Removes", "attributes", "in", "the", "remove", "list", "from", "the", "input", "attribute", "dict", ":", "param", "attrs", ":", "Dict", "of", "operator", "attributes", ":", "param", "remove_list", ":", "list", "of", "attributes", "to", "be", "removed" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L49-L61
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
_add_extra_attributes
def _add_extra_attributes(attrs, extra_attr_map): """ :param attrs: Current Attribute list :param extraAttrMap: Additional attributes to be added :return: new_attr """ for attr in extra_attr_map: if attr not in attrs: attrs[attr] = extra_attr_map[attr] return attrs
python
def _add_extra_attributes(attrs, extra_attr_map): """ :param attrs: Current Attribute list :param extraAttrMap: Additional attributes to be added :return: new_attr """ for attr in extra_attr_map: if attr not in attrs: attrs[attr] = extra_attr_map[attr] return attrs
[ "def", "_add_extra_attributes", "(", "attrs", ",", "extra_attr_map", ")", ":", "for", "attr", "in", "extra_attr_map", ":", "if", "attr", "not", "in", "attrs", ":", "attrs", "[", "attr", "]", "=", "extra_attr_map", "[", "attr", "]", "return", "attrs" ]
:param attrs: Current Attribute list :param extraAttrMap: Additional attributes to be added :return: new_attr
[ ":", "param", "attrs", ":", "Current", "Attribute", "list", ":", "param", "extraAttrMap", ":", "Additional", "attributes", "to", "be", "added", ":", "return", ":", "new_attr" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L63-L72
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
_pad_sequence_fix
def _pad_sequence_fix(attr, kernel_dim=None): """Changing onnx's pads sequence to match with mxnet's pad_width mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end) onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)""" new_attr = () if len(attr) % 2 == 0: for index in range(int(len(attr) / 2)): ...
python
def _pad_sequence_fix(attr, kernel_dim=None): """Changing onnx's pads sequence to match with mxnet's pad_width mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end) onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)""" new_attr = () if len(attr) % 2 == 0: for index in range(int(len(attr) / 2)): ...
[ "def", "_pad_sequence_fix", "(", "attr", ",", "kernel_dim", "=", "None", ")", ":", "new_attr", "=", "(", ")", "if", "len", "(", "attr", ")", "%", "2", "==", "0", ":", "for", "index", "in", "range", "(", "int", "(", "len", "(", "attr", ")", "/", ...
Changing onnx's pads sequence to match with mxnet's pad_width mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end) onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)
[ "Changing", "onnx", "s", "pads", "sequence", "to", "match", "with", "mxnet", "s", "pad_width", "mxnet", ":", "(", "x1_begin", "x1_end", "...", "xn_begin", "xn_end", ")", "onnx", ":", "(", "x1_begin", "x2_begin", "...", "xn_end", "xn_end", ")" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L75-L88
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
_fix_pooling
def _fix_pooling(pool_type, inputs, new_attr): """onnx pooling operator supports asymmetrical padding Adding pad operator before pooling in mxnet to work with onnx""" stride = new_attr.get('stride') kernel = new_attr.get('kernel') padding = new_attr.get('pad') p_value = new_attr.get('p_value') ...
python
def _fix_pooling(pool_type, inputs, new_attr): """onnx pooling operator supports asymmetrical padding Adding pad operator before pooling in mxnet to work with onnx""" stride = new_attr.get('stride') kernel = new_attr.get('kernel') padding = new_attr.get('pad') p_value = new_attr.get('p_value') ...
[ "def", "_fix_pooling", "(", "pool_type", ",", "inputs", ",", "new_attr", ")", ":", "stride", "=", "new_attr", ".", "get", "(", "'stride'", ")", "kernel", "=", "new_attr", ".", "get", "(", "'kernel'", ")", "padding", "=", "new_attr", ".", "get", "(", "'...
onnx pooling operator supports asymmetrical padding Adding pad operator before pooling in mxnet to work with onnx
[ "onnx", "pooling", "operator", "supports", "asymmetrical", "padding", "Adding", "pad", "operator", "before", "pooling", "in", "mxnet", "to", "work", "with", "onnx" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L91-L146
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
_fix_bias
def _fix_bias(op_name, attrs, num_inputs): """A workaround for 'use_bias' attribute since onnx don't provide this attribute, we have to check the number of inputs to decide it.""" if num_inputs == 3: attrs['no_bias'] = False elif num_inputs == 2: attrs['no_bias'] = True else: ...
python
def _fix_bias(op_name, attrs, num_inputs): """A workaround for 'use_bias' attribute since onnx don't provide this attribute, we have to check the number of inputs to decide it.""" if num_inputs == 3: attrs['no_bias'] = False elif num_inputs == 2: attrs['no_bias'] = True else: ...
[ "def", "_fix_bias", "(", "op_name", ",", "attrs", ",", "num_inputs", ")", ":", "if", "num_inputs", "==", "3", ":", "attrs", "[", "'no_bias'", "]", "=", "False", "elif", "num_inputs", "==", "2", ":", "attrs", "[", "'no_bias'", "]", "=", "True", "else", ...
A workaround for 'use_bias' attribute since onnx don't provide this attribute, we have to check the number of inputs to decide it.
[ "A", "workaround", "for", "use_bias", "attribute", "since", "onnx", "don", "t", "provide", "this", "attribute", "we", "have", "to", "check", "the", "number", "of", "inputs", "to", "decide", "it", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L148-L157
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
_fix_broadcast
def _fix_broadcast(op_name, inputs, broadcast_axis, proto_obj): """A workaround to reshape bias term to (1, num_channel).""" if int(len(proto_obj._params)) > 0: assert len(list(inputs)) == 2 input0_shape = get_input_shape(inputs[0], proto_obj) #creating reshape shape reshape_sha...
python
def _fix_broadcast(op_name, inputs, broadcast_axis, proto_obj): """A workaround to reshape bias term to (1, num_channel).""" if int(len(proto_obj._params)) > 0: assert len(list(inputs)) == 2 input0_shape = get_input_shape(inputs[0], proto_obj) #creating reshape shape reshape_sha...
[ "def", "_fix_broadcast", "(", "op_name", ",", "inputs", ",", "broadcast_axis", ",", "proto_obj", ")", ":", "if", "int", "(", "len", "(", "proto_obj", ".", "_params", ")", ")", ">", "0", ":", "assert", "len", "(", "list", "(", "inputs", ")", ")", "=="...
A workaround to reshape bias term to (1, num_channel).
[ "A", "workaround", "to", "reshape", "bias", "term", "to", "(", "1", "num_channel", ")", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L159-L173
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
_fix_channels
def _fix_channels(op_name, attrs, inputs, proto_obj): """A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number. """ weight_name = inputs[1].name if not weight_name in proto_obj._params: raise ValueEr...
python
def _fix_channels(op_name, attrs, inputs, proto_obj): """A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number. """ weight_name = inputs[1].name if not weight_name in proto_obj._params: raise ValueEr...
[ "def", "_fix_channels", "(", "op_name", ",", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "weight_name", "=", "inputs", "[", "1", "]", ".", "name", "if", "not", "weight_name", "in", "proto_obj", ".", "_params", ":", "raise", "ValueError", "(", "\"...
A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number.
[ "A", "workaround", "for", "getting", "channels", "or", "units", "since", "onnx", "don", "t", "provide", "these", "attributes", ".", "We", "check", "the", "shape", "of", "weights", "provided", "to", "get", "the", "number", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L176-L198
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
_fix_gemm
def _fix_gemm(op_name, inputs, old_attr, proto_obj): """Using FullyConnected operator in place of linalg_gemm to perform same operation""" op_sym = getattr(symbol, op_name, None) alpha = float(old_attr.get('alpha', 1.0)) beta = float(old_attr.get('beta', 1.0)) trans_a = int(old_attr.get('transA', 0)...
python
def _fix_gemm(op_name, inputs, old_attr, proto_obj): """Using FullyConnected operator in place of linalg_gemm to perform same operation""" op_sym = getattr(symbol, op_name, None) alpha = float(old_attr.get('alpha', 1.0)) beta = float(old_attr.get('beta', 1.0)) trans_a = int(old_attr.get('transA', 0)...
[ "def", "_fix_gemm", "(", "op_name", ",", "inputs", ",", "old_attr", ",", "proto_obj", ")", ":", "op_sym", "=", "getattr", "(", "symbol", ",", "op_name", ",", "None", ")", "alpha", "=", "float", "(", "old_attr", ".", "get", "(", "'alpha'", ",", "1.0", ...
Using FullyConnected operator in place of linalg_gemm to perform same operation
[ "Using", "FullyConnected", "operator", "in", "place", "of", "linalg_gemm", "to", "perform", "same", "operation" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L201-L214
train
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
get_input_shape
def get_input_shape(sym, proto_obj): """Helper function to obtain the shape of an array""" arg_params = proto_obj.arg_dict aux_params = proto_obj.aux_dict model_input_shape = [data[1] for data in proto_obj.model_metadata.get('input_tensor_data')] data_names = [data[0] for data in proto_obj.model_...
python
def get_input_shape(sym, proto_obj): """Helper function to obtain the shape of an array""" arg_params = proto_obj.arg_dict aux_params = proto_obj.aux_dict model_input_shape = [data[1] for data in proto_obj.model_metadata.get('input_tensor_data')] data_names = [data[0] for data in proto_obj.model_...
[ "def", "get_input_shape", "(", "sym", ",", "proto_obj", ")", ":", "arg_params", "=", "proto_obj", ".", "arg_dict", "aux_params", "=", "proto_obj", ".", "aux_dict", "model_input_shape", "=", "[", "data", "[", "1", "]", "for", "data", "in", "proto_obj", ".", ...
Helper function to obtain the shape of an array
[ "Helper", "function", "to", "obtain", "the", "shape", "of", "an", "array" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L216-L247
train
apache/incubator-mxnet
python/mxnet/image/image.py
imresize
def imresize(src, w, h, *args, **kwargs): r"""Resize image with OpenCV. .. note:: `imresize` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imresize` to work. Parameters ---------- src : NDArray source image w : int, required ...
python
def imresize(src, w, h, *args, **kwargs): r"""Resize image with OpenCV. .. note:: `imresize` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imresize` to work. Parameters ---------- src : NDArray source image w : int, required ...
[ "def", "imresize", "(", "src", ",", "w", ",", "h", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_internal", ".", "_cvimresize", "(", "src", ",", "w", ",", "h", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
r"""Resize image with OpenCV. .. note:: `imresize` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imresize` to work. Parameters ---------- src : NDArray source image w : int, required Width of resized image. h : int, required ...
[ "r", "Resize", "image", "with", "OpenCV", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L86-L140
train
apache/incubator-mxnet
python/mxnet/image/image.py
imdecode
def imdecode(buf, *args, **kwargs): """Decode an image to an NDArray. .. note:: `imdecode` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imdecode` to work. Parameters ---------- buf : str/bytes/bytearray or numpy.ndarray Binary image dat...
python
def imdecode(buf, *args, **kwargs): """Decode an image to an NDArray. .. note:: `imdecode` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imdecode` to work. Parameters ---------- buf : str/bytes/bytearray or numpy.ndarray Binary image dat...
[ "def", "imdecode", "(", "buf", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "buf", ",", "nd", ".", "NDArray", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "==", "3", "and", "not", "isinstance"...
Decode an image to an NDArray. .. note:: `imdecode` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imdecode` to work. Parameters ---------- buf : str/bytes/bytearray or numpy.ndarray Binary image data as string or numpy ndarray. flag : in...
[ "Decode", "an", "image", "to", "an", "NDArray", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L143-L198
train
apache/incubator-mxnet
python/mxnet/image/image.py
scale_down
def scale_down(src_size, size): """Scales down crop size if it's larger than image size. If width/height of the crop is larger than the width/height of the image, sets the width/height to the width/height of the image. Parameters ---------- src_size : tuple of int Size of the image in ...
python
def scale_down(src_size, size): """Scales down crop size if it's larger than image size. If width/height of the crop is larger than the width/height of the image, sets the width/height to the width/height of the image. Parameters ---------- src_size : tuple of int Size of the image in ...
[ "def", "scale_down", "(", "src_size", ",", "size", ")", ":", "w", ",", "h", "=", "size", "sw", ",", "sh", "=", "src_size", "if", "sh", "<", "h", ":", "w", ",", "h", "=", "float", "(", "w", "*", "sh", ")", "/", "h", ",", "sh", "if", "sw", ...
Scales down crop size if it's larger than image size. If width/height of the crop is larger than the width/height of the image, sets the width/height to the width/height of the image. Parameters ---------- src_size : tuple of int Size of the image in (width, height) format. size : tupl...
[ "Scales", "down", "crop", "size", "if", "it", "s", "larger", "than", "image", "size", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L201-L233
train
apache/incubator-mxnet
python/mxnet/image/image.py
copyMakeBorder
def copyMakeBorder(src, top, bot, left, right, *args, **kwargs): """Pad image border with OpenCV. Parameters ---------- src : NDArray source image top : int, required Top margin. bot : int, required Bottom margin. left : int, required Left margin. right :...
python
def copyMakeBorder(src, top, bot, left, right, *args, **kwargs): """Pad image border with OpenCV. Parameters ---------- src : NDArray source image top : int, required Top margin. bot : int, required Bottom margin. left : int, required Left margin. right :...
[ "def", "copyMakeBorder", "(", "src", ",", "top", ",", "bot", ",", "left", ",", "right", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_internal", ".", "_cvcopyMakeBorder", "(", "src", ",", "top", ",", "bot", ",", "left", ",", "rig...
Pad image border with OpenCV. Parameters ---------- src : NDArray source image top : int, required Top margin. bot : int, required Bottom margin. left : int, required Left margin. right : int, required Right margin. type : int, optional, default='...
[ "Pad", "image", "border", "with", "OpenCV", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L236-L286
train
apache/incubator-mxnet
python/mxnet/image/image.py
_get_interp_method
def _get_interp_method(interp, sizes=()): """Get the interpolation method for resize functions. The major purpose of this function is to wrap a random interp method selection and a auto-estimation method. Parameters ---------- interp : int interpolation method for all resizing operation...
python
def _get_interp_method(interp, sizes=()): """Get the interpolation method for resize functions. The major purpose of this function is to wrap a random interp method selection and a auto-estimation method. Parameters ---------- interp : int interpolation method for all resizing operation...
[ "def", "_get_interp_method", "(", "interp", ",", "sizes", "=", "(", ")", ")", ":", "if", "interp", "==", "9", ":", "if", "sizes", ":", "assert", "len", "(", "sizes", ")", "==", "4", "oh", ",", "ow", ",", "nh", ",", "nw", "=", "sizes", "if", "nh...
Get the interpolation method for resize functions. The major purpose of this function is to wrap a random interp method selection and a auto-estimation method. Parameters ---------- interp : int interpolation method for all resizing operations Possible values: 0: Nearest Ne...
[ "Get", "the", "interpolation", "method", "for", "resize", "functions", ".", "The", "major", "purpose", "of", "this", "function", "is", "to", "wrap", "a", "random", "interp", "method", "selection", "and", "a", "auto", "-", "estimation", "method", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L289-L341
train
apache/incubator-mxnet
python/mxnet/image/image.py
resize_short
def resize_short(src, size, interp=2): """Resizes shorter edge to size. .. note:: `resize_short` uses OpenCV (not the CV2 Python library). MXNet must have been built with OpenCV for `resize_short` to work. Resizes the original image by setting the shorter edge to size and setting the longer edg...
python
def resize_short(src, size, interp=2): """Resizes shorter edge to size. .. note:: `resize_short` uses OpenCV (not the CV2 Python library). MXNet must have been built with OpenCV for `resize_short` to work. Resizes the original image by setting the shorter edge to size and setting the longer edg...
[ "def", "resize_short", "(", "src", ",", "size", ",", "interp", "=", "2", ")", ":", "h", ",", "w", ",", "_", "=", "src", ".", "shape", "if", "h", ">", "w", ":", "new_h", ",", "new_w", "=", "size", "*", "h", "//", "w", ",", "size", "else", ":...
Resizes shorter edge to size. .. note:: `resize_short` uses OpenCV (not the CV2 Python library). MXNet must have been built with OpenCV for `resize_short` to work. Resizes the original image by setting the shorter edge to size and setting the longer edge accordingly. Resizing function is called...
[ "Resizes", "shorter", "edge", "to", "size", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L344-L403
train
apache/incubator-mxnet
python/mxnet/image/image.py
fixed_crop
def fixed_crop(src, x0, y0, w, h, size=None, interp=2): """Crop src at fixed location, and (optionally) resize it to size. Parameters ---------- src : NDArray Input image x0 : int Left boundary of the cropping area y0 : int Top boundary of the cropping area w : int ...
python
def fixed_crop(src, x0, y0, w, h, size=None, interp=2): """Crop src at fixed location, and (optionally) resize it to size. Parameters ---------- src : NDArray Input image x0 : int Left boundary of the cropping area y0 : int Top boundary of the cropping area w : int ...
[ "def", "fixed_crop", "(", "src", ",", "x0", ",", "y0", ",", "w", ",", "h", ",", "size", "=", "None", ",", "interp", "=", "2", ")", ":", "out", "=", "nd", ".", "slice", "(", "src", ",", "begin", "=", "(", "y0", ",", "x0", ",", "0", ")", ",...
Crop src at fixed location, and (optionally) resize it to size. Parameters ---------- src : NDArray Input image x0 : int Left boundary of the cropping area y0 : int Top boundary of the cropping area w : int Width of the cropping area h : int Height of...
[ "Crop", "src", "at", "fixed", "location", "and", "(", "optionally", ")", "resize", "it", "to", "size", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L406-L435
train
apache/incubator-mxnet
python/mxnet/image/image.py
center_crop
def center_crop(src, size, interp=2): """Crops the image `src` to the given `size` by trimming on all four sides and preserving the center of the image. Upsamples if `src` is smaller than `size`. .. note:: This requires MXNet to be compiled with USE_OPENCV. Parameters ---------- src : NDAr...
python
def center_crop(src, size, interp=2): """Crops the image `src` to the given `size` by trimming on all four sides and preserving the center of the image. Upsamples if `src` is smaller than `size`. .. note:: This requires MXNet to be compiled with USE_OPENCV. Parameters ---------- src : NDAr...
[ "def", "center_crop", "(", "src", ",", "size", ",", "interp", "=", "2", ")", ":", "h", ",", "w", ",", "_", "=", "src", ".", "shape", "new_w", ",", "new_h", "=", "scale_down", "(", "(", "w", ",", "h", ")", ",", "size", ")", "x0", "=", "int", ...
Crops the image `src` to the given `size` by trimming on all four sides and preserving the center of the image. Upsamples if `src` is smaller than `size`. .. note:: This requires MXNet to be compiled with USE_OPENCV. Parameters ---------- src : NDArray Binary source image data. siz...
[ "Crops", "the", "image", "src", "to", "the", "given", "size", "by", "trimming", "on", "all", "four", "sides", "and", "preserving", "the", "center", "of", "the", "image", ".", "Upsamples", "if", "src", "is", "smaller", "than", "size", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L477-L523
train
apache/incubator-mxnet
python/mxnet/image/image.py
color_normalize
def color_normalize(src, mean, std=None): """Normalize src with mean and std. Parameters ---------- src : NDArray Input image mean : NDArray RGB mean to be subtracted std : NDArray RGB standard deviation to be divided Returns ------- NDArray An `NDAr...
python
def color_normalize(src, mean, std=None): """Normalize src with mean and std. Parameters ---------- src : NDArray Input image mean : NDArray RGB mean to be subtracted std : NDArray RGB standard deviation to be divided Returns ------- NDArray An `NDAr...
[ "def", "color_normalize", "(", "src", ",", "mean", ",", "std", "=", "None", ")", ":", "if", "mean", "is", "not", "None", ":", "src", "-=", "mean", "if", "std", "is", "not", "None", ":", "src", "/=", "std", "return", "src" ]
Normalize src with mean and std. Parameters ---------- src : NDArray Input image mean : NDArray RGB mean to be subtracted std : NDArray RGB standard deviation to be divided Returns ------- NDArray An `NDArray` containing the normalized image.
[ "Normalize", "src", "with", "mean", "and", "std", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L526-L547
train
apache/incubator-mxnet
python/mxnet/image/image.py
random_size_crop
def random_size_crop(src, size, area, ratio, interp=2, **kwargs): """Randomly crop src with size. Randomize area and aspect ratio. Parameters ---------- src : NDArray Input image size : tuple of (int, int) Size of the crop formatted as (width, height). area : float in (0, 1] or ...
python
def random_size_crop(src, size, area, ratio, interp=2, **kwargs): """Randomly crop src with size. Randomize area and aspect ratio. Parameters ---------- src : NDArray Input image size : tuple of (int, int) Size of the crop formatted as (width, height). area : float in (0, 1] or ...
[ "def", "random_size_crop", "(", "src", ",", "size", ",", "area", ",", "ratio", ",", "interp", "=", "2", ",", "*", "*", "kwargs", ")", ":", "h", ",", "w", ",", "_", "=", "src", ".", "shape", "src_area", "=", "h", "*", "w", "if", "'min_area'", "i...
Randomly crop src with size. Randomize area and aspect ratio. Parameters ---------- src : NDArray Input image size : tuple of (int, int) Size of the crop formatted as (width, height). area : float in (0, 1] or tuple of (float, float) If tuple, minimum area and maximum area t...
[ "Randomly", "crop", "src", "with", "size", ".", "Randomize", "area", "and", "aspect", "ratio", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L550-L602
train
apache/incubator-mxnet
python/mxnet/image/image.py
CreateAugmenter
def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0, hue=0, pca_noise=0, rand_gray=0, inter_method=2): """Creates an augmenter list. Parameters ---------- dat...
python
def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0, hue=0, pca_noise=0, rand_gray=0, inter_method=2): """Creates an augmenter list. Parameters ---------- dat...
[ "def", "CreateAugmenter", "(", "data_shape", ",", "resize", "=", "0", ",", "rand_crop", "=", "False", ",", "rand_resize", "=", "False", ",", "rand_mirror", "=", "False", ",", "mean", "=", "None", ",", "std", "=", "None", ",", "brightness", "=", "0", ",...
Creates an augmenter list. Parameters ---------- data_shape : tuple of int Shape for output data resize : int Resize shorter edge if larger than 0 at the begining rand_crop : bool Whether to enable random cropping other than center crop rand_resize : bool Whether...
[ "Creates", "an", "augmenter", "list", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1015-L1126
train
apache/incubator-mxnet
python/mxnet/image/image.py
Augmenter.dumps
def dumps(self): """Saves the Augmenter to string Returns ------- str JSON formatted string that describes the Augmenter. """ return json.dumps([self.__class__.__name__.lower(), self._kwargs])
python
def dumps(self): """Saves the Augmenter to string Returns ------- str JSON formatted string that describes the Augmenter. """ return json.dumps([self.__class__.__name__.lower(), self._kwargs])
[ "def", "dumps", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "[", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ",", "self", ".", "_kwargs", "]", ")" ]
Saves the Augmenter to string Returns ------- str JSON formatted string that describes the Augmenter.
[ "Saves", "the", "Augmenter", "to", "string" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L616-L624
train
apache/incubator-mxnet
python/mxnet/image/image.py
SequentialAug.dumps
def dumps(self): """Override the default to avoid duplicate dump.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]]
python
def dumps(self): """Override the default to avoid duplicate dump.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]]
[ "def", "dumps", "(", "self", ")", ":", "return", "[", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ",", "[", "x", ".", "dumps", "(", ")", "for", "x", "in", "self", ".", "ts", "]", "]" ]
Override the default to avoid duplicate dump.
[ "Override", "the", "default", "to", "avoid", "duplicate", "dump", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L643-L645
train
apache/incubator-mxnet
python/mxnet/image/image.py
ImageIter.reset
def reset(self): """Resets the iterator to the beginning of the data.""" if self.seq is not None and self.shuffle: random.shuffle(self.seq) if self.last_batch_handle != 'roll_over' or \ self._cache_data is None: if self.imgrec is not None: self...
python
def reset(self): """Resets the iterator to the beginning of the data.""" if self.seq is not None and self.shuffle: random.shuffle(self.seq) if self.last_batch_handle != 'roll_over' or \ self._cache_data is None: if self.imgrec is not None: self...
[ "def", "reset", "(", "self", ")", ":", "if", "self", ".", "seq", "is", "not", "None", "and", "self", ".", "shuffle", ":", "random", ".", "shuffle", "(", "self", ".", "seq", ")", "if", "self", ".", "last_batch_handle", "!=", "'roll_over'", "or", "self...
Resets the iterator to the beginning of the data.
[ "Resets", "the", "iterator", "to", "the", "beginning", "of", "the", "data", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1278-L1288
train
apache/incubator-mxnet
python/mxnet/image/image.py
ImageIter.hard_reset
def hard_reset(self): """Resets the iterator and ignore roll over data""" if self.seq is not None and self.shuffle: random.shuffle(self.seq) if self.imgrec is not None: self.imgrec.reset() self.cur = 0 self._allow_read = True self._cache_data = Non...
python
def hard_reset(self): """Resets the iterator and ignore roll over data""" if self.seq is not None and self.shuffle: random.shuffle(self.seq) if self.imgrec is not None: self.imgrec.reset() self.cur = 0 self._allow_read = True self._cache_data = Non...
[ "def", "hard_reset", "(", "self", ")", ":", "if", "self", ".", "seq", "is", "not", "None", "and", "self", ".", "shuffle", ":", "random", ".", "shuffle", "(", "self", ".", "seq", ")", "if", "self", ".", "imgrec", "is", "not", "None", ":", "self", ...
Resets the iterator and ignore roll over data
[ "Resets", "the", "iterator", "and", "ignore", "roll", "over", "data" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1290-L1300
train
apache/incubator-mxnet
python/mxnet/image/image.py
ImageIter.next_sample
def next_sample(self): """Helper function for reading in next sample.""" if self._allow_read is False: raise StopIteration if self.seq is not None: if self.cur < self.num_image: idx = self.seq[self.cur] else: if self.last_batch_...
python
def next_sample(self): """Helper function for reading in next sample.""" if self._allow_read is False: raise StopIteration if self.seq is not None: if self.cur < self.num_image: idx = self.seq[self.cur] else: if self.last_batch_...
[ "def", "next_sample", "(", "self", ")", ":", "if", "self", ".", "_allow_read", "is", "False", ":", "raise", "StopIteration", "if", "self", ".", "seq", "is", "not", "None", ":", "if", "self", ".", "cur", "<", "self", ".", "num_image", ":", "idx", "=",...
Helper function for reading in next sample.
[ "Helper", "function", "for", "reading", "in", "next", "sample", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1302-L1331
train
apache/incubator-mxnet
python/mxnet/image/image.py
ImageIter._batchify
def _batchify(self, batch_data, batch_label, start=0): """Helper function for batchifying data""" i = start batch_size = self.batch_size try: while i < batch_size: label, s = self.next_sample() data = self.imdecode(s) try: ...
python
def _batchify(self, batch_data, batch_label, start=0): """Helper function for batchifying data""" i = start batch_size = self.batch_size try: while i < batch_size: label, s = self.next_sample() data = self.imdecode(s) try: ...
[ "def", "_batchify", "(", "self", ",", "batch_data", ",", "batch_label", ",", "start", "=", "0", ")", ":", "i", "=", "start", "batch_size", "=", "self", ".", "batch_size", "try", ":", "while", "i", "<", "batch_size", ":", "label", ",", "s", "=", "self...
Helper function for batchifying data
[ "Helper", "function", "for", "batchifying", "data" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1333-L1354
train
apache/incubator-mxnet
python/mxnet/image/image.py
ImageIter.imdecode
def imdecode(self, s): """Decodes a string or byte string to an NDArray. See mx.img.imdecode for more details.""" def locate(): """Locate the image file/index if decode fails.""" if self.seq is not None: idx = self.seq[(self.cur % self.num_image) - 1] ...
python
def imdecode(self, s): """Decodes a string or byte string to an NDArray. See mx.img.imdecode for more details.""" def locate(): """Locate the image file/index if decode fails.""" if self.seq is not None: idx = self.seq[(self.cur % self.num_image) - 1] ...
[ "def", "imdecode", "(", "self", ",", "s", ")", ":", "def", "locate", "(", ")", ":", "\"\"\"Locate the image file/index if decode fails.\"\"\"", "if", "self", ".", "seq", "is", "not", "None", ":", "idx", "=", "self", ".", "seq", "[", "(", "self", ".", "cu...
Decodes a string or byte string to an NDArray. See mx.img.imdecode for more details.
[ "Decodes", "a", "string", "or", "byte", "string", "to", "an", "NDArray", ".", "See", "mx", ".", "img", ".", "imdecode", "for", "more", "details", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1409-L1428
train
apache/incubator-mxnet
python/mxnet/image/image.py
ImageIter.read_image
def read_image(self, fname): """Reads an input image `fname` and returns the decoded raw bytes. Examples -------- >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes. """ with open(os.path.join(self.path_root, fname), 'rb') as fin: img = fin.read()...
python
def read_image(self, fname): """Reads an input image `fname` and returns the decoded raw bytes. Examples -------- >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes. """ with open(os.path.join(self.path_root, fname), 'rb') as fin: img = fin.read()...
[ "def", "read_image", "(", "self", ",", "fname", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path_root", ",", "fname", ")", ",", "'rb'", ")", "as", "fin", ":", "img", "=", "fin", ".", "read", "(", ")", "retu...
Reads an input image `fname` and returns the decoded raw bytes. Examples -------- >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes.
[ "Reads", "an", "input", "image", "fname", "and", "returns", "the", "decoded", "raw", "bytes", ".", "Examples", "--------", ">>>", "dataIter", ".", "read_image", "(", "Face", ".", "jpg", ")", "#", "returns", "decoded", "raw", "bytes", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1430-L1438
train
apache/incubator-mxnet
example/gluon/sn_gan/train.py
facc
def facc(label, pred): """ evaluate accuracy """ pred = pred.ravel() label = label.ravel() return ((pred > 0.5) == label).mean()
python
def facc(label, pred): """ evaluate accuracy """ pred = pred.ravel() label = label.ravel() return ((pred > 0.5) == label).mean()
[ "def", "facc", "(", "label", ",", "pred", ")", ":", "pred", "=", "pred", ".", "ravel", "(", ")", "label", "=", "label", ".", "ravel", "(", ")", "return", "(", "(", "pred", ">", "0.5", ")", "==", "label", ")", ".", "mean", "(", ")" ]
evaluate accuracy
[ "evaluate", "accuracy" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/train.py#L68-L72
train
apache/incubator-mxnet
example/gluon/lipnet/utils/common.py
word_to_vector
def word_to_vector(word): """ Convert character vectors to integer vectors. """ vector = [] for char in list(word): vector.append(char2int(char)) return vector
python
def word_to_vector(word): """ Convert character vectors to integer vectors. """ vector = [] for char in list(word): vector.append(char2int(char)) return vector
[ "def", "word_to_vector", "(", "word", ")", ":", "vector", "=", "[", "]", "for", "char", "in", "list", "(", "word", ")", ":", "vector", ".", "append", "(", "char2int", "(", "char", ")", ")", "return", "vector" ]
Convert character vectors to integer vectors.
[ "Convert", "character", "vectors", "to", "integer", "vectors", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/common.py#L46-L53
train
apache/incubator-mxnet
example/gluon/lipnet/utils/common.py
vector_to_word
def vector_to_word(vector): """ Convert integer vectors to character vectors. """ word = "" for vec in vector: word = word + int2char(vec) return word
python
def vector_to_word(vector): """ Convert integer vectors to character vectors. """ word = "" for vec in vector: word = word + int2char(vec) return word
[ "def", "vector_to_word", "(", "vector", ")", ":", "word", "=", "\"\"", "for", "vec", "in", "vector", ":", "word", "=", "word", "+", "int2char", "(", "vec", ")", "return", "word" ]
Convert integer vectors to character vectors.
[ "Convert", "integer", "vectors", "to", "character", "vectors", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/common.py#L56-L63
train
apache/incubator-mxnet
example/gluon/lipnet/utils/common.py
char_conv
def char_conv(out): """ Convert integer vectors to character vectors for batch. """ out_conv = list() for i in range(out.shape[0]): tmp_str = '' for j in range(out.shape[1]): if int(out[i][j]) >= 0: tmp_char = int2char(int(out[i][j])) if in...
python
def char_conv(out): """ Convert integer vectors to character vectors for batch. """ out_conv = list() for i in range(out.shape[0]): tmp_str = '' for j in range(out.shape[1]): if int(out[i][j]) >= 0: tmp_char = int2char(int(out[i][j])) if in...
[ "def", "char_conv", "(", "out", ")", ":", "out_conv", "=", "list", "(", ")", "for", "i", "in", "range", "(", "out", ".", "shape", "[", "0", "]", ")", ":", "tmp_str", "=", "''", "for", "j", "in", "range", "(", "out", ".", "shape", "[", "1", "]...
Convert integer vectors to character vectors for batch.
[ "Convert", "integer", "vectors", "to", "character", "vectors", "for", "batch", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/common.py#L66-L80
train
apache/incubator-mxnet
tools/coreml/converter/_add_pooling.py
add_pooling_with_padding_types
def add_pooling_with_padding_types(builder, name, height, width, stride_height, stride_width, layer_type, padding_type, input_name, output_name, padding_top = 0, padding_bottom = 0, padding_left = 0, padding_right = 0, same_padding_asymmetry_mode = 'BOTTOM_RIGHT_HEAVY', exclude_pad_a...
python
def add_pooling_with_padding_types(builder, name, height, width, stride_height, stride_width, layer_type, padding_type, input_name, output_name, padding_top = 0, padding_bottom = 0, padding_left = 0, padding_right = 0, same_padding_asymmetry_mode = 'BOTTOM_RIGHT_HEAVY', exclude_pad_a...
[ "def", "add_pooling_with_padding_types", "(", "builder", ",", "name", ",", "height", ",", "width", ",", "stride_height", ",", "stride_width", ",", "layer_type", ",", "padding_type", ",", "input_name", ",", "output_name", ",", "padding_top", "=", "0", ",", "paddi...
Add a pooling layer to the model. This is our own implementation of add_pooling since current CoreML's version (0.5.0) of builder doesn't provide support for padding types apart from valid. This support will be added in the next release of coremltools. When that happens, this can be removed. Par...
[ "Add", "a", "pooling", "layer", "to", "the", "model", ".", "This", "is", "our", "own", "implementation", "of", "add_pooling", "since", "current", "CoreML", "s", "version", "(", "0", ".", "5", ".", "0", ")", "of", "builder", "doesn", "t", "provide", "su...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_add_pooling.py#L21-L118
train
apache/incubator-mxnet
example/kaggle-ndsb2/Preprocessing.py
get_frames
def get_frames(root_path): """Get path to all the frame in view SAX and contain complete frames""" ret = [] for root, _, files in os.walk(root_path): root=root.replace('\\','/') files=[s for s in files if ".dcm" in s] if len(files) == 0 or not files[0].endswith(".dcm") or root.find("sax") ...
python
def get_frames(root_path): """Get path to all the frame in view SAX and contain complete frames""" ret = [] for root, _, files in os.walk(root_path): root=root.replace('\\','/') files=[s for s in files if ".dcm" in s] if len(files) == 0 or not files[0].endswith(".dcm") or root.find("sax") ...
[ "def", "get_frames", "(", "root_path", ")", ":", "ret", "=", "[", "]", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "root_path", ")", ":", "root", "=", "root", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "files", "=", ...
Get path to all the frame in view SAX and contain complete frames
[ "Get", "path", "to", "all", "the", "frame", "in", "view", "SAX", "and", "contain", "complete", "frames" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Preprocessing.py#L39-L53
train
apache/incubator-mxnet
example/kaggle-ndsb2/Preprocessing.py
write_data_csv
def write_data_csv(fname, frames, preproc): """Write data to csv file""" fdata = open(fname, "w") dr = Parallel()(delayed(get_data)(lst,preproc) for lst in frames) data,result = zip(*dr) for entry in data: fdata.write(','.join(entry)+'\r\n') print("All finished, %d slices in total" % len(data)) ...
python
def write_data_csv(fname, frames, preproc): """Write data to csv file""" fdata = open(fname, "w") dr = Parallel()(delayed(get_data)(lst,preproc) for lst in frames) data,result = zip(*dr) for entry in data: fdata.write(','.join(entry)+'\r\n') print("All finished, %d slices in total" % len(data)) ...
[ "def", "write_data_csv", "(", "fname", ",", "frames", ",", "preproc", ")", ":", "fdata", "=", "open", "(", "fname", ",", "\"w\"", ")", "dr", "=", "Parallel", "(", ")", "(", "delayed", "(", "get_data", ")", "(", "lst", ",", "preproc", ")", "for", "l...
Write data to csv file
[ "Write", "data", "to", "csv", "file" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Preprocessing.py#L94-L104
train
apache/incubator-mxnet
example/kaggle-ndsb2/Preprocessing.py
crop_resize
def crop_resize(img, size): """crop center and resize""" if img.shape[0] < img.shape[1]: img = img.T # we crop image from center short_egde = min(img.shape[:2]) yy = int((img.shape[0] - short_egde) / 2) xx = int((img.shape[1] - short_egde) / 2) crop_img = img[yy : yy + short_egde, xx : xx + ...
python
def crop_resize(img, size): """crop center and resize""" if img.shape[0] < img.shape[1]: img = img.T # we crop image from center short_egde = min(img.shape[:2]) yy = int((img.shape[0] - short_egde) / 2) xx = int((img.shape[1] - short_egde) / 2) crop_img = img[yy : yy + short_egde, xx : xx + ...
[ "def", "crop_resize", "(", "img", ",", "size", ")", ":", "if", "img", ".", "shape", "[", "0", "]", "<", "img", ".", "shape", "[", "1", "]", ":", "img", "=", "img", ".", "T", "# we crop image from center", "short_egde", "=", "min", "(", "img", ".", ...
crop center and resize
[ "crop", "center", "and", "resize" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Preprocessing.py#L107-L119
train
apache/incubator-mxnet
example/gluon/sn_gan/model.py
get_generator
def get_generator(): """ construct and return generator """ g_net = gluon.nn.Sequential() with g_net.name_scope(): g_net.add(gluon.nn.Conv2DTranspose( channels=512, kernel_size=4, strides=1, padding=0, use_bias=False)) g_net.add(gluon.nn.BatchNorm()) g_net.add(gluon.nn.L...
python
def get_generator(): """ construct and return generator """ g_net = gluon.nn.Sequential() with g_net.name_scope(): g_net.add(gluon.nn.Conv2DTranspose( channels=512, kernel_size=4, strides=1, padding=0, use_bias=False)) g_net.add(gluon.nn.BatchNorm()) g_net.add(gluon.nn.L...
[ "def", "get_generator", "(", ")", ":", "g_net", "=", "gluon", ".", "nn", ".", "Sequential", "(", ")", "with", "g_net", ".", "name_scope", "(", ")", ":", "g_net", ".", "add", "(", "gluon", ".", "nn", ".", "Conv2DTranspose", "(", "channels", "=", "512"...
construct and return generator
[ "construct", "and", "return", "generator" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/model.py#L89-L117
train
apache/incubator-mxnet
example/gluon/sn_gan/model.py
get_descriptor
def get_descriptor(ctx): """ construct and return descriptor """ d_net = gluon.nn.Sequential() with d_net.name_scope(): d_net.add(SNConv2D(num_filter=64, kernel_size=4, strides=2, padding=1, in_channels=3, ctx=ctx)) d_net.add(gluon.nn.LeakyReLU(0.2)) d_net.add(SNConv2D(num_filter=1...
python
def get_descriptor(ctx): """ construct and return descriptor """ d_net = gluon.nn.Sequential() with d_net.name_scope(): d_net.add(SNConv2D(num_filter=64, kernel_size=4, strides=2, padding=1, in_channels=3, ctx=ctx)) d_net.add(gluon.nn.LeakyReLU(0.2)) d_net.add(SNConv2D(num_filter=1...
[ "def", "get_descriptor", "(", "ctx", ")", ":", "d_net", "=", "gluon", ".", "nn", ".", "Sequential", "(", ")", "with", "d_net", ".", "name_scope", "(", ")", ":", "d_net", ".", "add", "(", "SNConv2D", "(", "num_filter", "=", "64", ",", "kernel_size", "...
construct and return descriptor
[ "construct", "and", "return", "descriptor" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/model.py#L120-L139
train
apache/incubator-mxnet
example/gluon/sn_gan/model.py
SNConv2D._spectral_norm
def _spectral_norm(self): """ spectral normalization """ w = self.params.get('weight').data(self.ctx) w_mat = nd.reshape(w, [w.shape[0], -1]) _u = self.u.data(self.ctx) _v = None for _ in range(POWER_ITERATION): _v = nd.L2Normalization(nd.dot(_u, w_mat)) ...
python
def _spectral_norm(self): """ spectral normalization """ w = self.params.get('weight').data(self.ctx) w_mat = nd.reshape(w, [w.shape[0], -1]) _u = self.u.data(self.ctx) _v = None for _ in range(POWER_ITERATION): _v = nd.L2Normalization(nd.dot(_u, w_mat)) ...
[ "def", "_spectral_norm", "(", "self", ")", ":", "w", "=", "self", ".", "params", ".", "get", "(", "'weight'", ")", ".", "data", "(", "self", ".", "ctx", ")", "w_mat", "=", "nd", ".", "reshape", "(", "w", ",", "[", "w", ".", "shape", "[", "0", ...
spectral normalization
[ "spectral", "normalization" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/model.py#L55-L74
train
apache/incubator-mxnet
example/speech_recognition/stt_utils.py
conv_output_length
def conv_output_length(input_length, filter_size, border_mode, stride, dilation=1): """ Compute the length of the output sequence after 1D convolution along time. Note that this function is in line with the function used in Convolution1D class from Keras. Params: i...
python
def conv_output_length(input_length, filter_size, border_mode, stride, dilation=1): """ Compute the length of the output sequence after 1D convolution along time. Note that this function is in line with the function used in Convolution1D class from Keras. Params: i...
[ "def", "conv_output_length", "(", "input_length", ",", "filter_size", ",", "border_mode", ",", "stride", ",", "dilation", "=", "1", ")", ":", "if", "input_length", "is", "None", ":", "return", "None", "assert", "border_mode", "in", "{", "'same'", ",", "'vali...
Compute the length of the output sequence after 1D convolution along time. Note that this function is in line with the function used in Convolution1D class from Keras. Params: input_length (int): Length of the input sequence. filter_size (int): Width of the convolution kernel. ...
[ "Compute", "the", "length", "of", "the", "output", "sequence", "after", "1D", "convolution", "along", "time", ".", "Note", "that", "this", "function", "is", "in", "line", "with", "the", "function", "used", "in", "Convolution1D", "class", "from", "Keras", "."...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_utils.py#L30-L50
train
apache/incubator-mxnet
example/speech_recognition/stt_utils.py
spectrogram
def spectrogram(samples, fft_length=256, sample_rate=2, hop_length=128): """ Compute the spectrogram for a real signal. The parameters follow the naming convention of matplotlib.mlab.specgram Args: samples (1D array): input audio signal fft_length (int): number of elements in fft win...
python
def spectrogram(samples, fft_length=256, sample_rate=2, hop_length=128): """ Compute the spectrogram for a real signal. The parameters follow the naming convention of matplotlib.mlab.specgram Args: samples (1D array): input audio signal fft_length (int): number of elements in fft win...
[ "def", "spectrogram", "(", "samples", ",", "fft_length", "=", "256", ",", "sample_rate", "=", "2", ",", "hop_length", "=", "128", ")", ":", "assert", "not", "np", ".", "iscomplexobj", "(", "samples", ")", ",", "\"Must not pass in complex numbers\"", "window", ...
Compute the spectrogram for a real signal. The parameters follow the naming convention of matplotlib.mlab.specgram Args: samples (1D array): input audio signal fft_length (int): number of elements in fft window sample_rate (scalar): sample rate hop_length (int): hop length (r...
[ "Compute", "the", "spectrogram", "for", "a", "real", "signal", ".", "The", "parameters", "follow", "the", "naming", "convention", "of", "matplotlib", ".", "mlab", ".", "specgram", "Args", ":", "samples", "(", "1D", "array", ")", ":", "input", "audio", "sig...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_utils.py#L53-L104
train
apache/incubator-mxnet
example/speech_recognition/stt_utils.py
spectrogram_from_file
def spectrogram_from_file(filename, step=10, window=20, max_freq=None, eps=1e-14, overwrite=False, save_feature_as_csvfile=False): """ Calculate the log of linear spectrogram from FFT energy Params: filename (str): Path to the audio file step (int): Step size in millise...
python
def spectrogram_from_file(filename, step=10, window=20, max_freq=None, eps=1e-14, overwrite=False, save_feature_as_csvfile=False): """ Calculate the log of linear spectrogram from FFT energy Params: filename (str): Path to the audio file step (int): Step size in millise...
[ "def", "spectrogram_from_file", "(", "filename", ",", "step", "=", "10", ",", "window", "=", "20", ",", "max_freq", "=", "None", ",", "eps", "=", "1e-14", ",", "overwrite", "=", "False", ",", "save_feature_as_csvfile", "=", "False", ")", ":", "csvfilename"...
Calculate the log of linear spectrogram from FFT energy Params: filename (str): Path to the audio file step (int): Step size in milliseconds between windows window (int): FFT window size in milliseconds max_freq (int): Only FFT bins corresponding to frequencies between [0...
[ "Calculate", "the", "log", "of", "linear", "spectrogram", "from", "FFT", "energy", "Params", ":", "filename", "(", "str", ")", ":", "Path", "to", "the", "audio", "file", "step", "(", "int", ")", ":", "Step", "size", "in", "milliseconds", "between", "wind...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_utils.py#L107-L146
train
apache/incubator-mxnet
example/ssd/tools/rand_sampler.py
RandCropper.sample
def sample(self, label): """ generate random cropping boxes according to parameters if satifactory crops generated, apply to ground-truth as well Parameters: ---------- label : numpy.array (n x 5 matrix) ground-truths Returns: ---------- ...
python
def sample(self, label): """ generate random cropping boxes according to parameters if satifactory crops generated, apply to ground-truth as well Parameters: ---------- label : numpy.array (n x 5 matrix) ground-truths Returns: ---------- ...
[ "def", "sample", "(", "self", ",", "label", ")", ":", "samples", "=", "[", "]", "count", "=", "0", "for", "trial", "in", "range", "(", "self", ".", "max_trials", ")", ":", "if", "count", ">=", "self", ".", "max_sample", ":", "return", "samples", "s...
generate random cropping boxes according to parameters if satifactory crops generated, apply to ground-truth as well Parameters: ---------- label : numpy.array (n x 5 matrix) ground-truths Returns: ---------- list of (crop_box, label) tuples, if fail...
[ "generate", "random", "cropping", "boxes", "according", "to", "parameters", "if", "satifactory", "crops", "generated", "apply", "to", "ground", "-", "truth", "as", "well" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/rand_sampler.py#L93-L145
train
apache/incubator-mxnet
example/ssd/tools/rand_sampler.py
RandCropper._check_satisfy
def _check_satisfy(self, rand_box, gt_boxes): """ check if overlap with any gt box is larger than threshold """ l, t, r, b = rand_box num_gt = gt_boxes.shape[0] ls = np.ones(num_gt) * l ts = np.ones(num_gt) * t rs = np.ones(num_gt) * r bs = np.ones...
python
def _check_satisfy(self, rand_box, gt_boxes): """ check if overlap with any gt box is larger than threshold """ l, t, r, b = rand_box num_gt = gt_boxes.shape[0] ls = np.ones(num_gt) * l ts = np.ones(num_gt) * t rs = np.ones(num_gt) * r bs = np.ones...
[ "def", "_check_satisfy", "(", "self", ",", "rand_box", ",", "gt_boxes", ")", ":", "l", ",", "t", ",", "r", ",", "b", "=", "rand_box", "num_gt", "=", "gt_boxes", ".", "shape", "[", "0", "]", "ls", "=", "np", ".", "ones", "(", "num_gt", ")", "*", ...
check if overlap with any gt box is larger than threshold
[ "check", "if", "overlap", "with", "any", "gt", "box", "is", "larger", "than", "threshold" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/rand_sampler.py#L147-L192
train
apache/incubator-mxnet
example/ssd/tools/rand_sampler.py
RandPadder.sample
def sample(self, label): """ generate random padding boxes according to parameters if satifactory padding generated, apply to ground-truth as well Parameters: ---------- label : numpy.array (n x 5 matrix) ground-truths Returns: ---------- ...
python
def sample(self, label): """ generate random padding boxes according to parameters if satifactory padding generated, apply to ground-truth as well Parameters: ---------- label : numpy.array (n x 5 matrix) ground-truths Returns: ---------- ...
[ "def", "sample", "(", "self", ",", "label", ")", ":", "samples", "=", "[", "]", "count", "=", "0", "for", "trial", "in", "range", "(", "self", ".", "max_trials", ")", ":", "if", "count", ">=", "self", ".", "max_sample", ":", "return", "samples", "s...
generate random padding boxes according to parameters if satifactory padding generated, apply to ground-truth as well Parameters: ---------- label : numpy.array (n x 5 matrix) ground-truths Returns: ---------- list of (crop_box, label) tuples, if fai...
[ "generate", "random", "padding", "boxes", "according", "to", "parameters", "if", "satifactory", "padding", "generated", "apply", "to", "ground", "-", "truth", "as", "well" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/rand_sampler.py#L232-L287
train
apache/incubator-mxnet
benchmark/python/sparse/dot.py
measure_cost
def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs): """Measure time cost of running a function """ mx.nd.waitall() args_list = [] for arg in args: args_list.append(arg) start = time.time() if scipy_trans_lhs: args_list[0] = np.transpose(args_...
python
def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs): """Measure time cost of running a function """ mx.nd.waitall() args_list = [] for arg in args: args_list.append(arg) start = time.time() if scipy_trans_lhs: args_list[0] = np.transpose(args_...
[ "def", "measure_cost", "(", "repeat", ",", "scipy_trans_lhs", ",", "scipy_dns_lhs", ",", "func_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "mx", ".", "nd", ".", "waitall", "(", ")", "args_list", "=", "[", "]", "for", "arg", "in", "arg...
Measure time cost of running a function
[ "Measure", "time", "cost", "of", "running", "a", "function" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/benchmark/python/sparse/dot.py#L110-L125
train
apache/incubator-mxnet
example/ssd/dataset/pycocotools/coco.py
COCO.info
def info(self): """ Print information about the annotation file. :return: """ for key, value in self.dataset['info'].items(): print('{}: {}'.format(key, value))
python
def info(self): """ Print information about the annotation file. :return: """ for key, value in self.dataset['info'].items(): print('{}: {}'.format(key, value))
[ "def", "info", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "dataset", "[", "'info'", "]", ".", "items", "(", ")", ":", "print", "(", "'{}: {}'", ".", "format", "(", "key", ",", "value", ")", ")" ]
Print information about the annotation file. :return:
[ "Print", "information", "about", "the", "annotation", "file", ".", ":", "return", ":" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pycocotools/coco.py#L116-L122
train
apache/incubator-mxnet
example/ssd/dataset/pycocotools/coco.py
COCO.getCatIds
def getCatIds(self, catNms=[], supNms=[], catIds=[]): """ filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given...
python
def getCatIds(self, catNms=[], supNms=[], catIds=[]): """ filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given...
[ "def", "getCatIds", "(", "self", ",", "catNms", "=", "[", "]", ",", "supNms", "=", "[", "]", ",", "catIds", "=", "[", "]", ")", ":", "catNms", "=", "catNms", "if", "type", "(", "catNms", ")", "==", "list", "else", "[", "catNms", "]", "supNms", ...
filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given cat ids :return: ids (int array) : integer array of cat ids
[ "filtering", "parameters", ".", "default", "skips", "that", "filter", ".", ":", "param", "catNms", "(", "str", "array", ")", ":", "get", "cats", "for", "given", "cat", "names", ":", "param", "supNms", "(", "str", "array", ")", ":", "get", "cats", "for"...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pycocotools/coco.py#L152-L172
train
apache/incubator-mxnet
example/ssd/dataset/pycocotools/coco.py
COCO.loadAnns
def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects """ if type(ids) == list: return [self.anns[id] for id in ids] elif type(ids)...
python
def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects """ if type(ids) == list: return [self.anns[id] for id in ids] elif type(ids)...
[ "def", "loadAnns", "(", "self", ",", "ids", "=", "[", "]", ")", ":", "if", "type", "(", "ids", ")", "==", "list", ":", "return", "[", "self", ".", "anns", "[", "id", "]", "for", "id", "in", "ids", "]", "elif", "type", "(", "ids", ")", "==", ...
Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects
[ "Load", "anns", "with", "the", "specified", "ids", ".", ":", "param", "ids", "(", "int", "array", ")", ":", "integer", "ids", "specifying", "anns", ":", "return", ":", "anns", "(", "object", "array", ")", ":", "loaded", "ann", "objects" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pycocotools/coco.py#L195-L204
train
apache/incubator-mxnet
example/ssd/dataset/pycocotools/coco.py
COCO.loadCats
def loadCats(self, ids=[]): """ Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :return: cats (object array) : loaded cat objects """ if type(ids) == list: return [self.cats[id] for id in ids] elif type(ids)...
python
def loadCats(self, ids=[]): """ Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :return: cats (object array) : loaded cat objects """ if type(ids) == list: return [self.cats[id] for id in ids] elif type(ids)...
[ "def", "loadCats", "(", "self", ",", "ids", "=", "[", "]", ")", ":", "if", "type", "(", "ids", ")", "==", "list", ":", "return", "[", "self", ".", "cats", "[", "id", "]", "for", "id", "in", "ids", "]", "elif", "type", "(", "ids", ")", "==", ...
Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :return: cats (object array) : loaded cat objects
[ "Load", "cats", "with", "the", "specified", "ids", ".", ":", "param", "ids", "(", "int", "array", ")", ":", "integer", "ids", "specifying", "cats", ":", "return", ":", "cats", "(", "object", "array", ")", ":", "loaded", "cat", "objects" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pycocotools/coco.py#L206-L215
train
apache/incubator-mxnet
example/ssd/dataset/pycocotools/coco.py
COCO.loadImgs
def loadImgs(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects """ if type(ids) == list: return [self.imgs[id] for id in ids] elif type(ids) ...
python
def loadImgs(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects """ if type(ids) == list: return [self.imgs[id] for id in ids] elif type(ids) ...
[ "def", "loadImgs", "(", "self", ",", "ids", "=", "[", "]", ")", ":", "if", "type", "(", "ids", ")", "==", "list", ":", "return", "[", "self", ".", "imgs", "[", "id", "]", "for", "id", "in", "ids", "]", "elif", "type", "(", "ids", ")", "==", ...
Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects
[ "Load", "anns", "with", "the", "specified", "ids", ".", ":", "param", "ids", "(", "int", "array", ")", ":", "integer", "ids", "specifying", "img", ":", "return", ":", "imgs", "(", "object", "array", ")", ":", "loaded", "img", "objects" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pycocotools/coco.py#L217-L226
train
apache/incubator-mxnet
example/ssd/dataset/pycocotools/coco.py
COCO.showAnns
def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if 'segmentation' in anns[0] or 'keypoints' in anns[0]: datasetType = 'inst...
python
def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if 'segmentation' in anns[0] or 'keypoints' in anns[0]: datasetType = 'inst...
[ "def", "showAnns", "(", "self", ",", "anns", ")", ":", "if", "len", "(", "anns", ")", "==", "0", ":", "return", "0", "if", "'segmentation'", "in", "anns", "[", "0", "]", "or", "'keypoints'", "in", "anns", "[", "0", "]", ":", "datasetType", "=", "...
Display the specified annotations. :param anns (array of object): annotations to display :return: None
[ "Display", "the", "specified", "annotations", ".", ":", "param", "anns", "(", "array", "of", "object", ")", ":", "annotations", "to", "display", ":", "return", ":", "None" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pycocotools/coco.py#L228-L277
train
apache/incubator-mxnet
example/ssd/dataset/pycocotools/coco.py
COCO.download
def download(self, tarDir = None, imgIds = [] ): ''' Download COCO images from mscoco.org server. :param tarDir (str): COCO results directory name imgIds (list): images to be downloaded :return: ''' if tarDir is None: print('Please specify targe...
python
def download(self, tarDir = None, imgIds = [] ): ''' Download COCO images from mscoco.org server. :param tarDir (str): COCO results directory name imgIds (list): images to be downloaded :return: ''' if tarDir is None: print('Please specify targe...
[ "def", "download", "(", "self", ",", "tarDir", "=", "None", ",", "imgIds", "=", "[", "]", ")", ":", "if", "tarDir", "is", "None", ":", "print", "(", "'Please specify target directory'", ")", "return", "-", "1", "if", "len", "(", "imgIds", ")", "==", ...
Download COCO images from mscoco.org server. :param tarDir (str): COCO results directory name imgIds (list): images to be downloaded :return:
[ "Download", "COCO", "images", "from", "mscoco", ".", "org", "server", ".", ":", "param", "tarDir", "(", "str", ")", ":", "COCO", "results", "directory", "name", "imgIds", "(", "list", ")", ":", "images", "to", "be", "downloaded", ":", "return", ":" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pycocotools/coco.py#L342-L364
train
apache/incubator-mxnet
example/ssd/dataset/pycocotools/coco.py
COCO.loadNumpyAnnotations
def loadNumpyAnnotations(self, data): """ Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class} :param data (numpy.ndarray) :return: annotations (python nested list) """ print('Converting ndarray to lists...') assert...
python
def loadNumpyAnnotations(self, data): """ Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class} :param data (numpy.ndarray) :return: annotations (python nested list) """ print('Converting ndarray to lists...') assert...
[ "def", "loadNumpyAnnotations", "(", "self", ",", "data", ")", ":", "print", "(", "'Converting ndarray to lists...'", ")", "assert", "(", "type", "(", "data", ")", "==", "np", ".", "ndarray", ")", "print", "(", "data", ".", "shape", ")", "assert", "(", "d...
Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class} :param data (numpy.ndarray) :return: annotations (python nested list)
[ "Convert", "result", "data", "from", "a", "numpy", "array", "[", "Nx7", "]", "where", "each", "row", "contains", "{", "imageID", "x1", "y1", "w", "h", "score", "class", "}", ":", "param", "data", "(", "numpy", ".", "ndarray", ")", ":", "return", ":",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pycocotools/coco.py#L366-L387
train
apache/incubator-mxnet
example/ssd/dataset/pycocotools/coco.py
COCO.annToRLE
def annToRLE(self, ann): """ Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array) """ t = self.imgs[ann['image_id']] h, w = t['height'], t['width'] segm = ann['segmentation'] if type(segm) == list: ...
python
def annToRLE(self, ann): """ Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array) """ t = self.imgs[ann['image_id']] h, w = t['height'], t['width'] segm = ann['segmentation'] if type(segm) == list: ...
[ "def", "annToRLE", "(", "self", ",", "ann", ")", ":", "t", "=", "self", ".", "imgs", "[", "ann", "[", "'image_id'", "]", "]", "h", ",", "w", "=", "t", "[", "'height'", "]", ",", "t", "[", "'width'", "]", "segm", "=", "ann", "[", "'segmentation'...
Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array)
[ "Convert", "annotation", "which", "can", "be", "polygons", "uncompressed", "RLE", "to", "RLE", ".", ":", "return", ":", "binary", "mask", "(", "numpy", "2D", "array", ")" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pycocotools/coco.py#L389-L410
train
apache/incubator-mxnet
example/cnn_chinese_text_classification/text_cnn.py
save_model
def save_model(): """Save cnn model Returns ---------- callback: A callback function that can be passed as epoch_end_callback to fit """ if not os.path.exists("checkpoint"): os.mkdir("checkpoint") return mx.callback.do_checkpoint("checkpoint/checkpoint", args.save_period)
python
def save_model(): """Save cnn model Returns ---------- callback: A callback function that can be passed as epoch_end_callback to fit """ if not os.path.exists("checkpoint"): os.mkdir("checkpoint") return mx.callback.do_checkpoint("checkpoint/checkpoint", args.save_period)
[ "def", "save_model", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "\"checkpoint\"", ")", ":", "os", ".", "mkdir", "(", "\"checkpoint\"", ")", "return", "mx", ".", "callback", ".", "do_checkpoint", "(", "\"checkpoint/checkpoint\"", ","...
Save cnn model Returns ---------- callback: A callback function that can be passed as epoch_end_callback to fit
[ "Save", "cnn", "model", "Returns", "----------", "callback", ":", "A", "callback", "function", "that", "can", "be", "passed", "as", "epoch_end_callback", "to", "fit" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/cnn_chinese_text_classification/text_cnn.py#L67-L75
train
apache/incubator-mxnet
example/cnn_chinese_text_classification/text_cnn.py
highway
def highway(data): """Construct highway net Parameters ---------- data: Returns ---------- Highway Networks """ _data = data high_weight = mx.sym.Variable('high_weight') high_bias = mx.sym.Variable('high_bias') high_fc = mx.sym.FullyConnected(data=data, weight=high_weight...
python
def highway(data): """Construct highway net Parameters ---------- data: Returns ---------- Highway Networks """ _data = data high_weight = mx.sym.Variable('high_weight') high_bias = mx.sym.Variable('high_bias') high_fc = mx.sym.FullyConnected(data=data, weight=high_weight...
[ "def", "highway", "(", "data", ")", ":", "_data", "=", "data", "high_weight", "=", "mx", ".", "sym", ".", "Variable", "(", "'high_weight'", ")", "high_bias", "=", "mx", ".", "sym", ".", "Variable", "(", "'high_bias'", ")", "high_fc", "=", "mx", ".", ...
Construct highway net Parameters ---------- data: Returns ---------- Highway Networks
[ "Construct", "highway", "net", "Parameters", "----------", "data", ":", "Returns", "----------", "Highway", "Networks" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/cnn_chinese_text_classification/text_cnn.py#L78-L99
train
apache/incubator-mxnet
example/cnn_chinese_text_classification/text_cnn.py
train
def train(symbol_data, train_iterator, valid_iterator, data_column_names, target_names): """Train cnn model Parameters ---------- symbol_data: symbol train_iterator: DataIter Train DataIter valid_iterator: DataIter Valid DataIter data_column_names: lis...
python
def train(symbol_data, train_iterator, valid_iterator, data_column_names, target_names): """Train cnn model Parameters ---------- symbol_data: symbol train_iterator: DataIter Train DataIter valid_iterator: DataIter Valid DataIter data_column_names: lis...
[ "def", "train", "(", "symbol_data", ",", "train_iterator", ",", "valid_iterator", ",", "data_column_names", ",", "target_names", ")", ":", "devs", "=", "mx", ".", "cpu", "(", ")", "# default setting", "if", "args", ".", "gpus", "is", "not", "None", ":", "f...
Train cnn model Parameters ---------- symbol_data: symbol train_iterator: DataIter Train DataIter valid_iterator: DataIter Valid DataIter data_column_names: list of str Defaults to ('data') for a typical model used in image classific...
[ "Train", "cnn", "model", "Parameters", "----------", "symbol_data", ":", "symbol", "train_iterator", ":", "DataIter", "Train", "DataIter", "valid_iterator", ":", "DataIter", "Valid", "DataIter", "data_column_names", ":", "list", "of", "str", "Defaults", "to", "(", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/cnn_chinese_text_classification/text_cnn.py#L232-L280
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
default_batchify_fn
def default_batchify_fn(data): """Collate data into batch.""" if isinstance(data[0], nd.NDArray): return nd.stack(*data) elif isinstance(data[0], tuple): data = zip(*data) return [default_batchify_fn(i) for i in data] else: data = np.asarray(data) return nd.array(...
python
def default_batchify_fn(data): """Collate data into batch.""" if isinstance(data[0], nd.NDArray): return nd.stack(*data) elif isinstance(data[0], tuple): data = zip(*data) return [default_batchify_fn(i) for i in data] else: data = np.asarray(data) return nd.array(...
[ "def", "default_batchify_fn", "(", "data", ")", ":", "if", "isinstance", "(", "data", "[", "0", "]", ",", "nd", ".", "NDArray", ")", ":", "return", "nd", ".", "stack", "(", "*", "data", ")", "elif", "isinstance", "(", "data", "[", "0", "]", ",", ...
Collate data into batch.
[ "Collate", "data", "into", "batch", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L127-L136
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
default_mp_batchify_fn
def default_mp_batchify_fn(data): """Collate data into batch. Use shared memory for stacking.""" if isinstance(data[0], nd.NDArray): out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype, ctx=context.Context('cpu_shared', 0)) return nd.stack(*data, out=out) ...
python
def default_mp_batchify_fn(data): """Collate data into batch. Use shared memory for stacking.""" if isinstance(data[0], nd.NDArray): out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype, ctx=context.Context('cpu_shared', 0)) return nd.stack(*data, out=out) ...
[ "def", "default_mp_batchify_fn", "(", "data", ")", ":", "if", "isinstance", "(", "data", "[", "0", "]", ",", "nd", ".", "NDArray", ")", ":", "out", "=", "nd", ".", "empty", "(", "(", "len", "(", "data", ")", ",", ")", "+", "data", "[", "0", "]"...
Collate data into batch. Use shared memory for stacking.
[ "Collate", "data", "into", "batch", ".", "Use", "shared", "memory", "for", "stacking", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L139-L151
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
_as_in_context
def _as_in_context(data, ctx): """Move data into new context.""" if isinstance(data, nd.NDArray): return data.as_in_context(ctx) elif isinstance(data, (list, tuple)): return [_as_in_context(d, ctx) for d in data] return data
python
def _as_in_context(data, ctx): """Move data into new context.""" if isinstance(data, nd.NDArray): return data.as_in_context(ctx) elif isinstance(data, (list, tuple)): return [_as_in_context(d, ctx) for d in data] return data
[ "def", "_as_in_context", "(", "data", ",", "ctx", ")", ":", "if", "isinstance", "(", "data", ",", "nd", ".", "NDArray", ")", ":", "return", "data", ".", "as_in_context", "(", "ctx", ")", "elif", "isinstance", "(", "data", ",", "(", "list", ",", "tupl...
Move data into new context.
[ "Move", "data", "into", "new", "context", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L154-L160
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
worker_loop_v1
def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn): """Worker loop for multiprocessing DataLoader.""" while True: idx, samples = key_queue.get() if idx is None: break batch = batchify_fn([dataset[i] for i in samples]) data_queue.put((idx, batch))
python
def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn): """Worker loop for multiprocessing DataLoader.""" while True: idx, samples = key_queue.get() if idx is None: break batch = batchify_fn([dataset[i] for i in samples]) data_queue.put((idx, batch))
[ "def", "worker_loop_v1", "(", "dataset", ",", "key_queue", ",", "data_queue", ",", "batchify_fn", ")", ":", "while", "True", ":", "idx", ",", "samples", "=", "key_queue", ".", "get", "(", ")", "if", "idx", "is", "None", ":", "break", "batch", "=", "bat...
Worker loop for multiprocessing DataLoader.
[ "Worker", "loop", "for", "multiprocessing", "DataLoader", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L163-L170
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
fetcher_loop_v1
def fetcher_loop_v1(data_queue, data_buffer, pin_memory=False, pin_device_id=0, data_buffer_lock=None): """Fetcher loop for fetching data from queue and put in reorder dict.""" while True: idx, batch = data_queue.get() if idx is None: break if pin_memory: ...
python
def fetcher_loop_v1(data_queue, data_buffer, pin_memory=False, pin_device_id=0, data_buffer_lock=None): """Fetcher loop for fetching data from queue and put in reorder dict.""" while True: idx, batch = data_queue.get() if idx is None: break if pin_memory: ...
[ "def", "fetcher_loop_v1", "(", "data_queue", ",", "data_buffer", ",", "pin_memory", "=", "False", ",", "pin_device_id", "=", "0", ",", "data_buffer_lock", "=", "None", ")", ":", "while", "True", ":", "idx", ",", "batch", "=", "data_queue", ".", "get", "(",...
Fetcher loop for fetching data from queue and put in reorder dict.
[ "Fetcher", "loop", "for", "fetching", "data", "from", "queue", "and", "put", "in", "reorder", "dict", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L172-L187
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
_worker_fn
def _worker_fn(samples, batchify_fn, dataset=None): """Function for processing data in worker process.""" # pylint: disable=unused-argument # it is required that each worker process has to fork a new MXIndexedRecordIO handle # preserving dataset as global variable can save tons of overhead and is safe i...
python
def _worker_fn(samples, batchify_fn, dataset=None): """Function for processing data in worker process.""" # pylint: disable=unused-argument # it is required that each worker process has to fork a new MXIndexedRecordIO handle # preserving dataset as global variable can save tons of overhead and is safe i...
[ "def", "_worker_fn", "(", "samples", ",", "batchify_fn", ",", "dataset", "=", "None", ")", ":", "# pylint: disable=unused-argument", "# it is required that each worker process has to fork a new MXIndexedRecordIO handle", "# preserving dataset as global variable can save tons of overhead ...
Function for processing data in worker process.
[ "Function", "for", "processing", "data", "in", "worker", "process", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L394-L403
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
ConnectionWrapper.send
def send(self, obj): """Send object""" buf = io.BytesIO() ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj) self.send_bytes(buf.getvalue())
python
def send(self, obj): """Send object""" buf = io.BytesIO() ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj) self.send_bytes(buf.getvalue())
[ "def", "send", "(", "self", ",", "obj", ")", ":", "buf", "=", "io", ".", "BytesIO", "(", ")", "ForkingPickler", "(", "buf", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", ".", "dump", "(", "obj", ")", "self", ".", "send_bytes", "(", "buf", ".", "getv...
Send object
[ "Send", "object" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L81-L85
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
_MultiWorkerIterV1._push_next
def _push_next(self): """Assign next batch workload to workers.""" r = next(self._iter, None) if r is None: return self._key_queue.put((self._sent_idx, r)) self._sent_idx += 1
python
def _push_next(self): """Assign next batch workload to workers.""" r = next(self._iter, None) if r is None: return self._key_queue.put((self._sent_idx, r)) self._sent_idx += 1
[ "def", "_push_next", "(", "self", ")", ":", "r", "=", "next", "(", "self", ".", "_iter", ",", "None", ")", "if", "r", "is", "None", ":", "return", "self", ".", "_key_queue", ".", "put", "(", "(", "self", ".", "_sent_idx", ",", "r", ")", ")", "s...
Assign next batch workload to workers.
[ "Assign", "next", "batch", "workload", "to", "workers", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L237-L243
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
_MultiWorkerIterV1.shutdown
def shutdown(self): """Shutdown internal workers by pushing terminate signals.""" if not self._shutdown: # send shutdown signal to the fetcher and join data queue first # Remark: loop_fetcher need to be joined prior to the workers. # otherwise, the the fet...
python
def shutdown(self): """Shutdown internal workers by pushing terminate signals.""" if not self._shutdown: # send shutdown signal to the fetcher and join data queue first # Remark: loop_fetcher need to be joined prior to the workers. # otherwise, the the fet...
[ "def", "shutdown", "(", "self", ")", ":", "if", "not", "self", ".", "_shutdown", ":", "# send shutdown signal to the fetcher and join data queue first", "# Remark: loop_fetcher need to be joined prior to the workers.", "# otherwise, the the fetcher may fail at getting data", ...
Shutdown internal workers by pushing terminate signals.
[ "Shutdown", "internal", "workers", "by", "pushing", "terminate", "signals", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L266-L281
train
apache/incubator-mxnet
python/mxnet/gluon/data/dataloader.py
_MultiWorkerIter._push_next
def _push_next(self): """Assign next batch workload to workers.""" r = next(self._iter, None) if r is None: return async_ret = self._worker_pool.apply_async( self._worker_fn, (r, self._batchify_fn, self._dataset)) self._data_buffer[self._sent_idx] = async_...
python
def _push_next(self): """Assign next batch workload to workers.""" r = next(self._iter, None) if r is None: return async_ret = self._worker_pool.apply_async( self._worker_fn, (r, self._batchify_fn, self._dataset)) self._data_buffer[self._sent_idx] = async_...
[ "def", "_push_next", "(", "self", ")", ":", "r", "=", "next", "(", "self", ".", "_iter", ",", "None", ")", "if", "r", "is", "None", ":", "return", "async_ret", "=", "self", ".", "_worker_pool", ".", "apply_async", "(", "self", ".", "_worker_fn", ",",...
Assign next batch workload to workers.
[ "Assign", "next", "batch", "workload", "to", "workers", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L431-L439
train
apache/incubator-mxnet
python/mxnet/kvstore.py
_ctype_key_value
def _ctype_key_value(keys, vals): """ Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only. """ if isinstance(keys, (tuple, list)): assert(len(keys) == len(vals)) c_keys = [] c_vals = [] use_str_keys = None f...
python
def _ctype_key_value(keys, vals): """ Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only. """ if isinstance(keys, (tuple, list)): assert(len(keys) == len(vals)) c_keys = [] c_vals = [] use_str_keys = None f...
[ "def", "_ctype_key_value", "(", "keys", ",", "vals", ")", ":", "if", "isinstance", "(", "keys", ",", "(", "tuple", ",", "list", ")", ")", ":", "assert", "(", "len", "(", "keys", ")", "==", "len", "(", "vals", ")", ")", "c_keys", "=", "[", "]", ...
Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only.
[ "Returns", "ctype", "arrays", "for", "the", "key", "-", "value", "args", "and", "the", "whether", "string", "keys", "are", "used", ".", "For", "internal", "use", "only", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L33-L66
train