repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
tensorflow/hub
examples/image_retraining/retrain.py
add_jpeg_decoding
def add_jpeg_decoding(module_spec): """Adds operations that perform JPEG decoding and resizing to the graph.. Args: module_spec: The hub.ModuleSpec for the image module being used. Returns: Tensors for the node to feed JPEG data into, and the output of the preprocessing steps. """ input_height...
python
def add_jpeg_decoding(module_spec): """Adds operations that perform JPEG decoding and resizing to the graph.. Args: module_spec: The hub.ModuleSpec for the image module being used. Returns: Tensors for the node to feed JPEG data into, and the output of the preprocessing steps. """ input_height...
[ "def", "add_jpeg_decoding", "(", "module_spec", ")", ":", "input_height", ",", "input_width", "=", "hub", ".", "get_expected_image_size", "(", "module_spec", ")", "input_depth", "=", "hub", ".", "get_num_image_channels", "(", "module_spec", ")", "jpeg_data", "=", ...
Adds operations that perform JPEG decoding and resizing to the graph.. Args: module_spec: The hub.ModuleSpec for the image module being used. Returns: Tensors for the node to feed JPEG data into, and the output of the preprocessing steps.
[ "Adds", "operations", "that", "perform", "JPEG", "decoding", "and", "resizing", "to", "the", "graph", ".." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L926-L948
train
tensorflow/hub
examples/image_retraining/retrain.py
export_model
def export_model(module_spec, class_count, saved_model_dir): """Exports model for serving. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: The number of classes. saved_model_dir: Directory in which to save exported model and variables. """ # The SavedModel should...
python
def export_model(module_spec, class_count, saved_model_dir): """Exports model for serving. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: The number of classes. saved_model_dir: Directory in which to save exported model and variables. """ # The SavedModel should...
[ "def", "export_model", "(", "module_spec", ",", "class_count", ",", "saved_model_dir", ")", ":", "# The SavedModel should hold the eval graph.", "sess", ",", "in_image", ",", "_", ",", "_", ",", "_", ",", "_", "=", "build_eval_session", "(", "module_spec", ",", ...
Exports model for serving. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: The number of classes. saved_model_dir: Directory in which to save exported model and variables.
[ "Exports", "model", "for", "serving", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L951-L968
train
tensorflow/hub
examples/image_retraining/retrain.py
logging_level_verbosity
def logging_level_verbosity(logging_verbosity): """Converts logging_level into TensorFlow logging verbosity value Args: logging_level: String value representing logging level: 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL' """ name_to_level = { 'FATAL': tf.logging.FATAL, 'ERROR': tf.logging.ERROR, ...
python
def logging_level_verbosity(logging_verbosity): """Converts logging_level into TensorFlow logging verbosity value Args: logging_level: String value representing logging level: 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL' """ name_to_level = { 'FATAL': tf.logging.FATAL, 'ERROR': tf.logging.ERROR, ...
[ "def", "logging_level_verbosity", "(", "logging_verbosity", ")", ":", "name_to_level", "=", "{", "'FATAL'", ":", "tf", ".", "logging", ".", "FATAL", ",", "'ERROR'", ":", "tf", ".", "logging", ".", "ERROR", ",", "'WARN'", ":", "tf", ".", "logging", ".", "...
Converts logging_level into TensorFlow logging verbosity value Args: logging_level: String value representing logging level: 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'
[ "Converts", "logging_level", "into", "TensorFlow", "logging", "verbosity", "value" ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L971-L990
train
tensorflow/hub
tensorflow_hub/image_util.py
get_image_module_info
def get_image_module_info(module_or_spec, required=False): """Returns the module's attached ImageModuleInfo message, or None.""" return module_or_spec.get_attached_message( IMAGE_MODULE_INFO_KEY, ImageModuleInfo, required=required)
python
def get_image_module_info(module_or_spec, required=False): """Returns the module's attached ImageModuleInfo message, or None.""" return module_or_spec.get_attached_message( IMAGE_MODULE_INFO_KEY, ImageModuleInfo, required=required)
[ "def", "get_image_module_info", "(", "module_or_spec", ",", "required", "=", "False", ")", ":", "return", "module_or_spec", ".", "get_attached_message", "(", "IMAGE_MODULE_INFO_KEY", ",", "ImageModuleInfo", ",", "required", "=", "required", ")" ]
Returns the module's attached ImageModuleInfo message, or None.
[ "Returns", "the", "module", "s", "attached", "ImageModuleInfo", "message", "or", "None", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/image_util.py#L39-L42
train
tensorflow/hub
tensorflow_hub/image_util.py
get_expected_image_size
def get_expected_image_size(module_or_spec, signature=None, input_name=None): """Returns expected [height, width] dimensions of an image input. Args: module_or_spec: a Module or ModuleSpec that accepts image inputs. signature: a string with the key of the signature in question. If None, the default s...
python
def get_expected_image_size(module_or_spec, signature=None, input_name=None): """Returns expected [height, width] dimensions of an image input. Args: module_or_spec: a Module or ModuleSpec that accepts image inputs. signature: a string with the key of the signature in question. If None, the default s...
[ "def", "get_expected_image_size", "(", "module_or_spec", ",", "signature", "=", "None", ",", "input_name", "=", "None", ")", ":", "# First see if an attached ImageModuleInfo provides this information.", "image_module_info", "=", "get_image_module_info", "(", "module_or_spec", ...
Returns expected [height, width] dimensions of an image input. Args: module_or_spec: a Module or ModuleSpec that accepts image inputs. signature: a string with the key of the signature in question. If None, the default signature is used. input_name: a string with the input name for images. If None,...
[ "Returns", "expected", "[", "height", "width", "]", "dimensions", "of", "an", "image", "input", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/image_util.py#L45-L86
train
tensorflow/hub
tensorflow_hub/image_util.py
get_num_image_channels
def get_num_image_channels(module_or_spec, signature=None, input_name=None): """Returns expected num_channels dimensions of an image input. This is for advanced users only who expect to handle modules with image inputs that might not have the 3 usual RGB channels. Args: module_or_spec: a Module or ModuleS...
python
def get_num_image_channels(module_or_spec, signature=None, input_name=None): """Returns expected num_channels dimensions of an image input. This is for advanced users only who expect to handle modules with image inputs that might not have the 3 usual RGB channels. Args: module_or_spec: a Module or ModuleS...
[ "def", "get_num_image_channels", "(", "module_or_spec", ",", "signature", "=", "None", ",", "input_name", "=", "None", ")", ":", "if", "input_name", "is", "None", ":", "input_name", "=", "\"images\"", "input_info_dict", "=", "module_or_spec", ".", "get_input_info_...
Returns expected num_channels dimensions of an image input. This is for advanced users only who expect to handle modules with image inputs that might not have the 3 usual RGB channels. Args: module_or_spec: a Module or ModuleSpec that accepts image inputs. signature: a string with the key of the signatu...
[ "Returns", "expected", "num_channels", "dimensions", "of", "an", "image", "input", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/image_util.py#L89-L125
train
tensorflow/hub
tensorflow_hub/tensor_info.py
_parse_tensor_info_proto
def _parse_tensor_info_proto(tensor_info): """Returns a ParsedTensorInfo instance from a TensorInfo proto.""" encoding = tensor_info.WhichOneof("encoding") dtype = tf.DType(tensor_info.dtype) shape = tf.TensorShape(tensor_info.tensor_shape) if encoding == "name": return ParsedTensorInfo(dtype=dtype, shape...
python
def _parse_tensor_info_proto(tensor_info): """Returns a ParsedTensorInfo instance from a TensorInfo proto.""" encoding = tensor_info.WhichOneof("encoding") dtype = tf.DType(tensor_info.dtype) shape = tf.TensorShape(tensor_info.tensor_shape) if encoding == "name": return ParsedTensorInfo(dtype=dtype, shape...
[ "def", "_parse_tensor_info_proto", "(", "tensor_info", ")", ":", "encoding", "=", "tensor_info", ".", "WhichOneof", "(", "\"encoding\"", ")", "dtype", "=", "tf", ".", "DType", "(", "tensor_info", ".", "dtype", ")", "shape", "=", "tf", ".", "TensorShape", "("...
Returns a ParsedTensorInfo instance from a TensorInfo proto.
[ "Returns", "a", "ParsedTensorInfo", "instance", "from", "a", "TensorInfo", "proto", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L65-L75
train
tensorflow/hub
tensorflow_hub/tensor_info.py
_is_sparse
def _is_sparse(x): """Returns whether x is a SparseTensor or a parsed sparse tensor info.""" return ( isinstance(x, (tf.SparseTensor, tf_v1.SparseTensorValue)) or (hasattr(x, "is_sparse") and x.is_sparse))
python
def _is_sparse(x): """Returns whether x is a SparseTensor or a parsed sparse tensor info.""" return ( isinstance(x, (tf.SparseTensor, tf_v1.SparseTensorValue)) or (hasattr(x, "is_sparse") and x.is_sparse))
[ "def", "_is_sparse", "(", "x", ")", ":", "return", "(", "isinstance", "(", "x", ",", "(", "tf", ".", "SparseTensor", ",", "tf_v1", ".", "SparseTensorValue", ")", ")", "or", "(", "hasattr", "(", "x", ",", "\"is_sparse\"", ")", "and", "x", ".", "is_spa...
Returns whether x is a SparseTensor or a parsed sparse tensor info.
[ "Returns", "whether", "x", "is", "a", "SparseTensor", "or", "a", "parsed", "sparse", "tensor", "info", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L97-L101
train
tensorflow/hub
tensorflow_hub/tensor_info.py
_convert_to_compatible_tensor
def _convert_to_compatible_tensor(value, target, error_prefix): """Converts `value` into a tensor that can be feed into `tensor_info`. Args: value: A value to convert into Tensor or SparseTensor. target: An object returned by `parse_tensor_info_map`. error_prefix: A string to prefix on raised TypeError...
python
def _convert_to_compatible_tensor(value, target, error_prefix): """Converts `value` into a tensor that can be feed into `tensor_info`. Args: value: A value to convert into Tensor or SparseTensor. target: An object returned by `parse_tensor_info_map`. error_prefix: A string to prefix on raised TypeError...
[ "def", "_convert_to_compatible_tensor", "(", "value", ",", "target", ",", "error_prefix", ")", ":", "try", ":", "tensor", "=", "tf_v1", ".", "convert_to_tensor_or_indexed_slices", "(", "value", ",", "target", ".", "dtype", ")", "except", "TypeError", "as", "e", ...
Converts `value` into a tensor that can be feed into `tensor_info`. Args: value: A value to convert into Tensor or SparseTensor. target: An object returned by `parse_tensor_info_map`. error_prefix: A string to prefix on raised TypeErrors. Raises: TypeError: If it fails to convert. Returns: ...
[ "Converts", "value", "into", "a", "tensor", "that", "can", "be", "feed", "into", "tensor_info", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L104-L130
train
tensorflow/hub
tensorflow_hub/tensor_info.py
convert_dict_to_compatible_tensor
def convert_dict_to_compatible_tensor(values, targets): """Converts dict `values` in tensors that are compatible with `targets`. Args: values: A dict to objects to convert with same keys as `targets`. targets: A dict returned by `parse_tensor_info_map`. Returns: A map with the same keys as `values` ...
python
def convert_dict_to_compatible_tensor(values, targets): """Converts dict `values` in tensors that are compatible with `targets`. Args: values: A dict to objects to convert with same keys as `targets`. targets: A dict returned by `parse_tensor_info_map`. Returns: A map with the same keys as `values` ...
[ "def", "convert_dict_to_compatible_tensor", "(", "values", ",", "targets", ")", ":", "result", "=", "{", "}", "for", "key", ",", "value", "in", "sorted", "(", "values", ".", "items", "(", ")", ")", ":", "result", "[", "key", "]", "=", "_convert_to_compat...
Converts dict `values` in tensors that are compatible with `targets`. Args: values: A dict to objects to convert with same keys as `targets`. targets: A dict returned by `parse_tensor_info_map`. Returns: A map with the same keys as `values` but values converted into Tensor/SparseTensors that can b...
[ "Converts", "dict", "values", "in", "tensors", "that", "are", "compatible", "with", "targets", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L133-L151
train
tensorflow/hub
tensorflow_hub/tensor_info.py
build_input_map
def build_input_map(protomap, inputs): """Builds a map to feed tensors in `protomap` using `inputs`. Args: protomap: A proto map<string,TensorInfo>. inputs: A map with same keys as `protomap` of Tensors and SparseTensors. Returns: A map from nodes refered by TensorInfo protos to corresponding input ...
python
def build_input_map(protomap, inputs): """Builds a map to feed tensors in `protomap` using `inputs`. Args: protomap: A proto map<string,TensorInfo>. inputs: A map with same keys as `protomap` of Tensors and SparseTensors. Returns: A map from nodes refered by TensorInfo protos to corresponding input ...
[ "def", "build_input_map", "(", "protomap", ",", "inputs", ")", ":", "if", "set", "(", "protomap", ".", "keys", "(", ")", ")", "!=", "set", "(", "inputs", ".", "keys", "(", ")", ")", ":", "raise", "ValueError", "(", "\"build_input_map: keys do not match.\""...
Builds a map to feed tensors in `protomap` using `inputs`. Args: protomap: A proto map<string,TensorInfo>. inputs: A map with same keys as `protomap` of Tensors and SparseTensors. Returns: A map from nodes refered by TensorInfo protos to corresponding input tensors. Raises: ValueError: if a...
[ "Builds", "a", "map", "to", "feed", "tensors", "in", "protomap", "using", "inputs", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L154-L183
train
tensorflow/hub
tensorflow_hub/tensor_info.py
build_output_map
def build_output_map(protomap, get_tensor_by_name): """Builds a map of tensors from `protomap` using `get_tensor_by_name`. Args: protomap: A proto map<string,TensorInfo>. get_tensor_by_name: A lambda that receives a tensor name and returns a Tensor instance. Returns: A map from string to Tenso...
python
def build_output_map(protomap, get_tensor_by_name): """Builds a map of tensors from `protomap` using `get_tensor_by_name`. Args: protomap: A proto map<string,TensorInfo>. get_tensor_by_name: A lambda that receives a tensor name and returns a Tensor instance. Returns: A map from string to Tenso...
[ "def", "build_output_map", "(", "protomap", ",", "get_tensor_by_name", ")", ":", "def", "get_output_from_tensor_info", "(", "tensor_info", ")", ":", "encoding", "=", "tensor_info", ".", "WhichOneof", "(", "\"encoding\"", ")", "if", "encoding", "==", "\"name\"", ":...
Builds a map of tensors from `protomap` using `get_tensor_by_name`. Args: protomap: A proto map<string,TensorInfo>. get_tensor_by_name: A lambda that receives a tensor name and returns a Tensor instance. Returns: A map from string to Tensor or SparseTensor instances built from `protomap` and...
[ "Builds", "a", "map", "of", "tensors", "from", "protomap", "using", "get_tensor_by_name", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L186-L217
train
tensorflow/hub
tensorflow_hub/tensor_info.py
tensor_info_proto_maps_match
def tensor_info_proto_maps_match(map_a, map_b): """Whether two signature inputs/outputs match in dtype, shape and sparsity. Args: map_a: A proto map<string,TensorInfo>. map_b: A proto map<string,TensorInfo>. Returns: A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and sp...
python
def tensor_info_proto_maps_match(map_a, map_b): """Whether two signature inputs/outputs match in dtype, shape and sparsity. Args: map_a: A proto map<string,TensorInfo>. map_b: A proto map<string,TensorInfo>. Returns: A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and sp...
[ "def", "tensor_info_proto_maps_match", "(", "map_a", ",", "map_b", ")", ":", "iter_a", "=", "sorted", "(", "parse_tensor_info_map", "(", "map_a", ")", ".", "items", "(", ")", ")", "iter_b", "=", "sorted", "(", "parse_tensor_info_map", "(", "map_b", ")", ".",...
Whether two signature inputs/outputs match in dtype, shape and sparsity. Args: map_a: A proto map<string,TensorInfo>. map_b: A proto map<string,TensorInfo>. Returns: A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and sparsity.
[ "Whether", "two", "signature", "inputs", "/", "outputs", "match", "in", "dtype", "shape", "and", "sparsity", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L230-L254
train
tensorflow/hub
examples/text_embeddings/export.py
parse_line
def parse_line(line): """Parses a line of a text embedding file. Args: line: (str) One line of the text embedding file. Returns: A token string and its embedding vector in floats. """ columns = line.split() token = columns.pop(0) values = [float(column) for column in columns] return token, val...
python
def parse_line(line): """Parses a line of a text embedding file. Args: line: (str) One line of the text embedding file. Returns: A token string and its embedding vector in floats. """ columns = line.split() token = columns.pop(0) values = [float(column) for column in columns] return token, val...
[ "def", "parse_line", "(", "line", ")", ":", "columns", "=", "line", ".", "split", "(", ")", "token", "=", "columns", ".", "pop", "(", "0", ")", "values", "=", "[", "float", "(", "column", ")", "for", "column", "in", "columns", "]", "return", "token...
Parses a line of a text embedding file. Args: line: (str) One line of the text embedding file. Returns: A token string and its embedding vector in floats.
[ "Parses", "a", "line", "of", "a", "text", "embedding", "file", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L47-L59
train
tensorflow/hub
examples/text_embeddings/export.py
load
def load(file_path, parse_line_fn): """Loads a text embedding into memory as a numpy matrix. Args: file_path: Path to the text embedding file. parse_line_fn: callback function to parse each file line. Returns: A tuple of (list of vocabulary tokens, numpy matrix of embedding vectors). Raises: ...
python
def load(file_path, parse_line_fn): """Loads a text embedding into memory as a numpy matrix. Args: file_path: Path to the text embedding file. parse_line_fn: callback function to parse each file line. Returns: A tuple of (list of vocabulary tokens, numpy matrix of embedding vectors). Raises: ...
[ "def", "load", "(", "file_path", ",", "parse_line_fn", ")", ":", "vocabulary", "=", "[", "]", "embeddings", "=", "[", "]", "embeddings_dim", "=", "None", "for", "line", "in", "tf", ".", "gfile", ".", "GFile", "(", "file_path", ")", ":", "token", ",", ...
Loads a text embedding into memory as a numpy matrix. Args: file_path: Path to the text embedding file. parse_line_fn: callback function to parse each file line. Returns: A tuple of (list of vocabulary tokens, numpy matrix of embedding vectors). Raises: ValueError: if the data in the sstable is...
[ "Loads", "a", "text", "embedding", "into", "memory", "as", "a", "numpy", "matrix", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L62-L90
train
tensorflow/hub
examples/text_embeddings/export.py
make_module_spec
def make_module_spec(vocabulary_file, vocab_size, embeddings_dim, num_oov_buckets, preprocess_text): """Makes a module spec to simply perform token to embedding lookups. Input of this module is a 1-D list of string tokens. For T tokens input and an M dimensional embedding table, the lookup r...
python
def make_module_spec(vocabulary_file, vocab_size, embeddings_dim, num_oov_buckets, preprocess_text): """Makes a module spec to simply perform token to embedding lookups. Input of this module is a 1-D list of string tokens. For T tokens input and an M dimensional embedding table, the lookup r...
[ "def", "make_module_spec", "(", "vocabulary_file", ",", "vocab_size", ",", "embeddings_dim", ",", "num_oov_buckets", ",", "preprocess_text", ")", ":", "def", "module_fn", "(", ")", ":", "\"\"\"Spec function for a token embedding module.\"\"\"", "tokens", "=", "tf", ".",...
Makes a module spec to simply perform token to embedding lookups. Input of this module is a 1-D list of string tokens. For T tokens input and an M dimensional embedding table, the lookup result is a [T, M] shaped Tensor. Args: vocabulary_file: Text file where each line is a key in the vocabulary. vocab_...
[ "Makes", "a", "module", "spec", "to", "simply", "perform", "token", "to", "embedding", "lookups", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L93-L177
train
tensorflow/hub
examples/text_embeddings/export.py
export
def export(export_path, vocabulary, embeddings, num_oov_buckets, preprocess_text): """Exports a TF-Hub module that performs embedding lookups. Args: export_path: Location to export the module. vocabulary: List of the N tokens in the vocabulary. embeddings: Numpy array of shape [N+K,M] the fi...
python
def export(export_path, vocabulary, embeddings, num_oov_buckets, preprocess_text): """Exports a TF-Hub module that performs embedding lookups. Args: export_path: Location to export the module. vocabulary: List of the N tokens in the vocabulary. embeddings: Numpy array of shape [N+K,M] the fi...
[ "def", "export", "(", "export_path", ",", "vocabulary", ",", "embeddings", ",", "num_oov_buckets", ",", "preprocess_text", ")", ":", "# Write temporary vocab file for module construction.", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "vocabulary_file", "=", "...
Exports a TF-Hub module that performs embedding lookups. Args: export_path: Location to export the module. vocabulary: List of the N tokens in the vocabulary. embeddings: Numpy array of shape [N+K,M] the first N rows are the M dimensional embeddings for the respective tokens and the next K ro...
[ "Exports", "a", "TF", "-", "Hub", "module", "that", "performs", "embedding", "lookups", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L180-L219
train
tensorflow/hub
examples/text_embeddings/export.py
maybe_append_oov_vectors
def maybe_append_oov_vectors(embeddings, num_oov_buckets): """Adds zero vectors for oov buckets if num_oov_buckets > 0. Since we are assigning zero vectors, adding more that one oov bucket is only meaningful if we perform fine-tuning. Args: embeddings: Embeddings to extend. num_oov_buckets: Number of ...
python
def maybe_append_oov_vectors(embeddings, num_oov_buckets): """Adds zero vectors for oov buckets if num_oov_buckets > 0. Since we are assigning zero vectors, adding more that one oov bucket is only meaningful if we perform fine-tuning. Args: embeddings: Embeddings to extend. num_oov_buckets: Number of ...
[ "def", "maybe_append_oov_vectors", "(", "embeddings", ",", "num_oov_buckets", ")", ":", "num_embeddings", "=", "np", ".", "shape", "(", "embeddings", ")", "[", "0", "]", "embedding_dim", "=", "np", ".", "shape", "(", "embeddings", ")", "[", "1", "]", "embe...
Adds zero vectors for oov buckets if num_oov_buckets > 0. Since we are assigning zero vectors, adding more that one oov bucket is only meaningful if we perform fine-tuning. Args: embeddings: Embeddings to extend. num_oov_buckets: Number of OOV buckets in the extended embedding.
[ "Adds", "zero", "vectors", "for", "oov", "buckets", "if", "num_oov_buckets", ">", "0", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L222-L235
train
tensorflow/hub
tensorflow_hub/saved_model_module.py
create_module_spec_from_saved_model
def create_module_spec_from_saved_model(saved_model_path, drop_collections=None): """Experimental: Create a ModuleSpec out of a SavedModel. Define a ModuleSpec from a SavedModel. Note that this is not guaranteed to work in all cases and it assumes the SavedModel has follow...
python
def create_module_spec_from_saved_model(saved_model_path, drop_collections=None): """Experimental: Create a ModuleSpec out of a SavedModel. Define a ModuleSpec from a SavedModel. Note that this is not guaranteed to work in all cases and it assumes the SavedModel has follow...
[ "def", "create_module_spec_from_saved_model", "(", "saved_model_path", ",", "drop_collections", "=", "None", ")", ":", "saved_model_handler", "=", "saved_model_lib", ".", "load", "(", "saved_model_path", ")", "checkpoint_filename", "=", "saved_model_lib", ".", "get_variab...
Experimental: Create a ModuleSpec out of a SavedModel. Define a ModuleSpec from a SavedModel. Note that this is not guaranteed to work in all cases and it assumes the SavedModel has followed some conventions: - The serialized SaverDef can be ignored and instead can be reconstructed. - The init op and main op ...
[ "Experimental", ":", "Create", "a", "ModuleSpec", "out", "of", "a", "SavedModel", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_module.py#L56-L91
train
tensorflow/hub
tensorflow_hub/estimator.py
register_module_for_export
def register_module_for_export(module, export_name): """Register a Module to be exported under `export_name`. This function registers `module` to be exported by `LatestModuleExporter` under a subdirectory named `export_name`. Note that `export_name` must be unique for each module exported from the current ...
python
def register_module_for_export(module, export_name): """Register a Module to be exported under `export_name`. This function registers `module` to be exported by `LatestModuleExporter` under a subdirectory named `export_name`. Note that `export_name` must be unique for each module exported from the current ...
[ "def", "register_module_for_export", "(", "module", ",", "export_name", ")", ":", "for", "used_name", ",", "_", "in", "tf_v1", ".", "get_collection", "(", "_EXPORT_MODULES_COLLECTION", ")", ":", "if", "used_name", "==", "export_name", ":", "raise", "ValueError", ...
Register a Module to be exported under `export_name`. This function registers `module` to be exported by `LatestModuleExporter` under a subdirectory named `export_name`. Note that `export_name` must be unique for each module exported from the current graph. It only controls the export subdirectory name and i...
[ "Register", "a", "Module", "to", "be", "exported", "under", "export_name", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/estimator.py#L37-L60
train
tensorflow/hub
tensorflow_hub/estimator.py
_make_estimator_serving_session
def _make_estimator_serving_session(estimator, serving_input_fn, checkpoint_path): """Returns a session constructed using `estimator` and `serving_input_fn`. The Estimator API does not provide an API to construct a graph and session, making it necessary for this function to re...
python
def _make_estimator_serving_session(estimator, serving_input_fn, checkpoint_path): """Returns a session constructed using `estimator` and `serving_input_fn`. The Estimator API does not provide an API to construct a graph and session, making it necessary for this function to re...
[ "def", "_make_estimator_serving_session", "(", "estimator", ",", "serving_input_fn", ",", "checkpoint_path", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", "as", "g", ":", "mode", "=", "tf_v1", ".", "estimator", ".", "ModeKeys",...
Returns a session constructed using `estimator` and `serving_input_fn`. The Estimator API does not provide an API to construct a graph and session, making it necessary for this function to replicate how an estimator builds a graph. This code is based on `Estimator.export_savedmodel` (another function that h...
[ "Returns", "a", "session", "constructed", "using", "estimator", "and", "serving_input_fn", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/estimator.py#L171-L214
train
tensorflow/hub
tensorflow_hub/native_module.py
create_module_spec
def create_module_spec(module_fn, tags_and_args=None, drop_collections=None): """Creates a ModuleSpec from a function that builds the module's graph. The `module_fn` is called on a new graph (not the current one) to build the graph of the module and define its signatures via `hub.add_signature()`. Example: ...
python
def create_module_spec(module_fn, tags_and_args=None, drop_collections=None): """Creates a ModuleSpec from a function that builds the module's graph. The `module_fn` is called on a new graph (not the current one) to build the graph of the module and define its signatures via `hub.add_signature()`. Example: ...
[ "def", "create_module_spec", "(", "module_fn", ",", "tags_and_args", "=", "None", ",", "drop_collections", "=", "None", ")", ":", "if", "not", "drop_collections", ":", "drop_collections", "=", "[", "]", "report_tags", "=", "True", "if", "not", "tags_and_args", ...
Creates a ModuleSpec from a function that builds the module's graph. The `module_fn` is called on a new graph (not the current one) to build the graph of the module and define its signatures via `hub.add_signature()`. Example: ```python # Define a text embedding module. def my_text_module_fn(): text_i...
[ "Creates", "a", "ModuleSpec", "from", "a", "function", "that", "builds", "the", "module", "s", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L121-L195
train
tensorflow/hub
tensorflow_hub/native_module.py
add_signature
def add_signature(name=None, inputs=None, outputs=None): """Adds a signature to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. Args: name: Signature name as a string. If omitted, it is interpreted as 'default' and is the signature used when `Module.__c...
python
def add_signature(name=None, inputs=None, outputs=None): """Adds a signature to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. Args: name: Signature name as a string. If omitted, it is interpreted as 'default' and is the signature used when `Module.__c...
[ "def", "add_signature", "(", "name", "=", "None", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "\"default\"", "if", "inputs", "is", "None", ":", "inputs", "=", "{", "}", "if", "outputs", ...
Adds a signature to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. Args: name: Signature name as a string. If omitted, it is interpreted as 'default' and is the signature used when `Module.__call__` `signature` is not specified. inputs: A dict ...
[ "Adds", "a", "signature", "to", "the", "module", "definition", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L198-L231
train
tensorflow/hub
tensorflow_hub/native_module.py
attach_message
def attach_message(key, message): """Adds an attached message to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. See ModuleSpec.get_attached_message() for an introduction to attached messages and the API for module consumers. To define a new type of attached...
python
def attach_message(key, message): """Adds an attached message to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. See ModuleSpec.get_attached_message() for an introduction to attached messages and the API for module consumers. To define a new type of attached...
[ "def", "attach_message", "(", "key", ",", "message", ")", ":", "if", "not", "re", ".", "match", "(", "r\"[a-zA-Z][a-zA-Z0-9_]*$\"", ",", "key", ")", ":", "raise", "ValueError", "(", "\"hub.attach_message() called with malformed key '%s'\"", "%", "key", ")", "saved...
Adds an attached message to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. See ModuleSpec.get_attached_message() for an introduction to attached messages and the API for module consumers. To define a new type of attached message: * Select a reasonably de...
[ "Adds", "an", "attached", "message", "to", "the", "module", "definition", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L234-L276
train
tensorflow/hub
tensorflow_hub/native_module.py
list_registered_stateful_ops_without_inputs
def list_registered_stateful_ops_without_inputs(): """Returns set of registered stateful ops that do not expect inputs. This list is used to identify the ops to be included in the state-graph and that are subsequently fed into the apply-graphs. Returns: A set of strings. """ return set([ name ...
python
def list_registered_stateful_ops_without_inputs(): """Returns set of registered stateful ops that do not expect inputs. This list is used to identify the ops to be included in the state-graph and that are subsequently fed into the apply-graphs. Returns: A set of strings. """ return set([ name ...
[ "def", "list_registered_stateful_ops_without_inputs", "(", ")", ":", "return", "set", "(", "[", "name", "for", "name", ",", "op", "in", "op_def_registry", ".", "get_registered_ops", "(", ")", ".", "items", "(", ")", "if", "op", ".", "is_stateful", "and", "no...
Returns set of registered stateful ops that do not expect inputs. This list is used to identify the ops to be included in the state-graph and that are subsequently fed into the apply-graphs. Returns: A set of strings.
[ "Returns", "set", "of", "registered", "stateful", "ops", "that", "do", "not", "expect", "inputs", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L586-L599
train
tensorflow/hub
tensorflow_hub/native_module.py
get_state_map
def get_state_map(meta_graph, state_ops, unsupported_state_ops, get_tensor_by_name): """Returns a map from tensor names to tensors that hold the state.""" state_map = {} for node in meta_graph.graph_def.node: if node.op in state_ops: tensor_name = node.name + ":0" tensor = get_te...
python
def get_state_map(meta_graph, state_ops, unsupported_state_ops, get_tensor_by_name): """Returns a map from tensor names to tensors that hold the state.""" state_map = {} for node in meta_graph.graph_def.node: if node.op in state_ops: tensor_name = node.name + ":0" tensor = get_te...
[ "def", "get_state_map", "(", "meta_graph", ",", "state_ops", ",", "unsupported_state_ops", ",", "get_tensor_by_name", ")", ":", "state_map", "=", "{", "}", "for", "node", "in", "meta_graph", ".", "graph_def", ".", "node", ":", "if", "node", ".", "op", "in", ...
Returns a map from tensor names to tensors that hold the state.
[ "Returns", "a", "map", "from", "tensor", "names", "to", "tensors", "that", "hold", "the", "state", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L602-L617
train
tensorflow/hub
tensorflow_hub/native_module.py
replace_apply_state
def replace_apply_state(meta_graph, state_ops, feed_map): """Replaces state ops with non state Placeholder ops for the apply graph.""" for node in meta_graph.graph_def.node: keys_to_purge = [] tensor_name = node.name + ":0" # Verify that the node is a state op and that its due to be rewired # in the...
python
def replace_apply_state(meta_graph, state_ops, feed_map): """Replaces state ops with non state Placeholder ops for the apply graph.""" for node in meta_graph.graph_def.node: keys_to_purge = [] tensor_name = node.name + ":0" # Verify that the node is a state op and that its due to be rewired # in the...
[ "def", "replace_apply_state", "(", "meta_graph", ",", "state_ops", ",", "feed_map", ")", ":", "for", "node", "in", "meta_graph", ".", "graph_def", ".", "node", ":", "keys_to_purge", "=", "[", "]", "tensor_name", "=", "node", ".", "name", "+", "\":0\"", "# ...
Replaces state ops with non state Placeholder ops for the apply graph.
[ "Replaces", "state", "ops", "with", "non", "state", "Placeholder", "ops", "for", "the", "apply", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L620-L636
train
tensorflow/hub
tensorflow_hub/native_module.py
_split_tensor_name
def _split_tensor_name(tensor_name): """Given a tensor name as node_name:output_number, returns both parts.""" result = re.match(r"(.*):(\d+)$", tensor_name) if not result: raise ValueError( "Unexpected format for tensor name. Expected node_name:output_number. " "Got %r" % tensor_name) retur...
python
def _split_tensor_name(tensor_name): """Given a tensor name as node_name:output_number, returns both parts.""" result = re.match(r"(.*):(\d+)$", tensor_name) if not result: raise ValueError( "Unexpected format for tensor name. Expected node_name:output_number. " "Got %r" % tensor_name) retur...
[ "def", "_split_tensor_name", "(", "tensor_name", ")", ":", "result", "=", "re", ".", "match", "(", "r\"(.*):(\\d+)$\"", ",", "tensor_name", ")", "if", "not", "result", ":", "raise", "ValueError", "(", "\"Unexpected format for tensor name. Expected node_name:output_numbe...
Given a tensor name as node_name:output_number, returns both parts.
[ "Given", "a", "tensor", "name", "as", "node_name", ":", "output_number", "returns", "both", "parts", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L654-L661
train
tensorflow/hub
tensorflow_hub/native_module.py
_extract_variable_parts
def _extract_variable_parts(variable_key, variable): """Matches a variable to individual parts. Args: variable_key: String identifier of the variable in the module scope. variable: Variable tensor. Returns: partitioned: Whether the variable is partitioned. name: Name of the variable up to the pa...
python
def _extract_variable_parts(variable_key, variable): """Matches a variable to individual parts. Args: variable_key: String identifier of the variable in the module scope. variable: Variable tensor. Returns: partitioned: Whether the variable is partitioned. name: Name of the variable up to the pa...
[ "def", "_extract_variable_parts", "(", "variable_key", ",", "variable", ")", ":", "name", ",", "offset", ",", "partitioned", "=", "None", ",", "None", ",", "False", "# pylint: disable=protected-access", "if", "variable", ".", "_save_slice_info", ":", "name", "=", ...
Matches a variable to individual parts. Args: variable_key: String identifier of the variable in the module scope. variable: Variable tensor. Returns: partitioned: Whether the variable is partitioned. name: Name of the variable up to the partitioning. offset: Offset of the variable into the fu...
[ "Matches", "a", "variable", "to", "individual", "parts", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L664-L688
train
tensorflow/hub
tensorflow_hub/native_module.py
recover_partitioned_variable_map
def recover_partitioned_variable_map(var_node_map): """Builds a proper variable map if it contains PartitionedVariables. Args: var_node_map: A map to tf.Variables. PartitionedVariables show up in this map as N entries with keys "<var_name>/part_n". Returns: A map to tf.Variables or to list of tf.V...
python
def recover_partitioned_variable_map(var_node_map): """Builds a proper variable map if it contains PartitionedVariables. Args: var_node_map: A map to tf.Variables. PartitionedVariables show up in this map as N entries with keys "<var_name>/part_n". Returns: A map to tf.Variables or to list of tf.V...
[ "def", "recover_partitioned_variable_map", "(", "var_node_map", ")", ":", "offset_variables_map", "=", "{", "}", "for", "var_key", ",", "var_tensor", "in", "var_node_map", ".", "items", "(", ")", ":", "match", ",", "var_name", ",", "offset", "=", "_extract_varia...
Builds a proper variable map if it contains PartitionedVariables. Args: var_node_map: A map to tf.Variables. PartitionedVariables show up in this map as N entries with keys "<var_name>/part_n". Returns: A map to tf.Variables or to list of tf.Variables for each PartitionedVariables in `var_node_m...
[ "Builds", "a", "proper", "variable", "map", "if", "it", "contains", "PartitionedVariables", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L691-L745
train
tensorflow/hub
tensorflow_hub/native_module.py
check_unique_tags
def check_unique_tags(tag_list): """Checks that tag list contains each set of tags only once.""" frozen_tags_seen = set() for tags in tag_list: frozen_tags = frozenset(tags) if frozen_tags in frozen_tags_seen: raise ValueError("Tags %r used repeatedly" % tags) frozen_tags_seen.add(frozen_tags)
python
def check_unique_tags(tag_list): """Checks that tag list contains each set of tags only once.""" frozen_tags_seen = set() for tags in tag_list: frozen_tags = frozenset(tags) if frozen_tags in frozen_tags_seen: raise ValueError("Tags %r used repeatedly" % tags) frozen_tags_seen.add(frozen_tags)
[ "def", "check_unique_tags", "(", "tag_list", ")", ":", "frozen_tags_seen", "=", "set", "(", ")", "for", "tags", "in", "tag_list", ":", "frozen_tags", "=", "frozenset", "(", "tags", ")", "if", "frozen_tags", "in", "frozen_tags_seen", ":", "raise", "ValueError",...
Checks that tag list contains each set of tags only once.
[ "Checks", "that", "tag", "list", "contains", "each", "set", "of", "tags", "only", "once", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L748-L755
train
tensorflow/hub
tensorflow_hub/native_module.py
check_collections_are_supported
def check_collections_are_supported(saved_model_handler, supported): """Checks that SavedModelHandler only uses supported collections.""" for meta_graph in saved_model_handler.meta_graphs: used_collection_keys = set(meta_graph.collection_def.keys()) unsupported = used_collection_keys - supported if unsu...
python
def check_collections_are_supported(saved_model_handler, supported): """Checks that SavedModelHandler only uses supported collections.""" for meta_graph in saved_model_handler.meta_graphs: used_collection_keys = set(meta_graph.collection_def.keys()) unsupported = used_collection_keys - supported if unsu...
[ "def", "check_collections_are_supported", "(", "saved_model_handler", ",", "supported", ")", ":", "for", "meta_graph", "in", "saved_model_handler", ".", "meta_graphs", ":", "used_collection_keys", "=", "set", "(", "meta_graph", ".", "collection_def", ".", "keys", "(",...
Checks that SavedModelHandler only uses supported collections.
[ "Checks", "that", "SavedModelHandler", "only", "uses", "supported", "collections", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L758-L766
train
tensorflow/hub
tensorflow_hub/native_module.py
register_ops_if_needed
def register_ops_if_needed(graph_ops): """Register graph ops absent in op_def_registry, if present in c++ registry. Args: graph_ops: set with graph op names to register. Raises: RuntimeError: if `graph_ops` contains ops that are not in either python or c++ registry. """ missing_ops = graph_ops...
python
def register_ops_if_needed(graph_ops): """Register graph ops absent in op_def_registry, if present in c++ registry. Args: graph_ops: set with graph op names to register. Raises: RuntimeError: if `graph_ops` contains ops that are not in either python or c++ registry. """ missing_ops = graph_ops...
[ "def", "register_ops_if_needed", "(", "graph_ops", ")", ":", "missing_ops", "=", "graph_ops", "-", "set", "(", "op_def_registry", ".", "get_registered_ops", "(", ")", ".", "keys", "(", ")", ")", "if", "not", "missing_ops", ":", "return", "p_buffer", "=", "c_...
Register graph ops absent in op_def_registry, if present in c++ registry. Args: graph_ops: set with graph op names to register. Raises: RuntimeError: if `graph_ops` contains ops that are not in either python or c++ registry.
[ "Register", "graph", "ops", "absent", "in", "op_def_registry", "if", "present", "in", "c", "++", "registry", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L773-L814
train
tensorflow/hub
tensorflow_hub/native_module.py
fix_colocation_after_import
def fix_colocation_after_import(input_map, absolute_import_scope): """Fixes colocation attributes after import according to input_map. This function is meant to be called after importing a GraphDef, in order to rewrite colocate_with constrains analogous to how inputs to ops are rewritten by input_map during im...
python
def fix_colocation_after_import(input_map, absolute_import_scope): """Fixes colocation attributes after import according to input_map. This function is meant to be called after importing a GraphDef, in order to rewrite colocate_with constrains analogous to how inputs to ops are rewritten by input_map during im...
[ "def", "fix_colocation_after_import", "(", "input_map", ",", "absolute_import_scope", ")", ":", "attr_map", "=", "_build_colocation_attr_map", "(", "input_map", ",", "absolute_import_scope", ")", "_apply_colocation_attr_map", "(", "attr_map", ",", "absolute_import_scope", "...
Fixes colocation attributes after import according to input_map. This function is meant to be called after importing a GraphDef, in order to rewrite colocate_with constrains analogous to how inputs to ops are rewritten by input_map during import. It also updates devices accordingly. The nodes in the given imp...
[ "Fixes", "colocation", "attributes", "after", "import", "according", "to", "input_map", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L817-L870
train
tensorflow/hub
tensorflow_hub/native_module.py
_build_colocation_attr_map
def _build_colocation_attr_map(input_map, absolute_import_scope): """Returns a dict mapping from pre-import to post-import colocation attrs. Args: input_map: as for fix_colocation_after_import. absolute_import_scope: as for fix_colocation_after_import. Returns: A dict that maps bytes `"loc:@" + abso...
python
def _build_colocation_attr_map(input_map, absolute_import_scope): """Returns a dict mapping from pre-import to post-import colocation attrs. Args: input_map: as for fix_colocation_after_import. absolute_import_scope: as for fix_colocation_after_import. Returns: A dict that maps bytes `"loc:@" + abso...
[ "def", "_build_colocation_attr_map", "(", "input_map", ",", "absolute_import_scope", ")", ":", "colocation_attr_map", "=", "collections", ".", "defaultdict", "(", "_ConsistentValue", ")", "used_outputs_of_imported_ops", "=", "collections", ".", "defaultdict", "(", "set", ...
Returns a dict mapping from pre-import to post-import colocation attrs. Args: input_map: as for fix_colocation_after_import. absolute_import_scope: as for fix_colocation_after_import. Returns: A dict that maps bytes `"loc:@" + absolute_import_scope + "/foo"` to _ConsistentValues set to the lists o...
[ "Returns", "a", "dict", "mapping", "from", "pre", "-", "import", "to", "post", "-", "import", "colocation", "attrs", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L918-L965
train
tensorflow/hub
tensorflow_hub/native_module.py
_apply_colocation_attr_map
def _apply_colocation_attr_map(colocation_attr_map, absolute_import_scope): """Rewrites colocation constraints in the current default graph. Nodes in `absolute_import_scope` get their "_class" attr lists rewritten according to `colocation_attr_map`: each entry that matches a key gets replaced by the associated...
python
def _apply_colocation_attr_map(colocation_attr_map, absolute_import_scope): """Rewrites colocation constraints in the current default graph. Nodes in `absolute_import_scope` get their "_class" attr lists rewritten according to `colocation_attr_map`: each entry that matches a key gets replaced by the associated...
[ "def", "_apply_colocation_attr_map", "(", "colocation_attr_map", ",", "absolute_import_scope", ")", ":", "graph", "=", "tf_v1", ".", "get_default_graph", "(", ")", "for", "op", "in", "graph", ".", "get_operations", "(", ")", ":", "# Rewrite the values of the \"_class\...
Rewrites colocation constraints in the current default graph. Nodes in `absolute_import_scope` get their "_class" attr lists rewritten according to `colocation_attr_map`: each entry that matches a key gets replaced by the associated values (with deduplication). The node's device is updated accordingly. Args...
[ "Rewrites", "colocation", "constraints", "in", "the", "current", "default", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L968-L1037
train
tensorflow/hub
tensorflow_hub/native_module.py
find_state_op_colocation_error
def find_state_op_colocation_error(graph, reported_tags=None): """Returns error message for colocation of state ops, or None if ok.""" state_op_types = list_registered_stateful_ops_without_inputs() state_op_map = {op.name: op for op in graph.get_operations() if op.type in state_op_types} for o...
python
def find_state_op_colocation_error(graph, reported_tags=None): """Returns error message for colocation of state ops, or None if ok.""" state_op_types = list_registered_stateful_ops_without_inputs() state_op_map = {op.name: op for op in graph.get_operations() if op.type in state_op_types} for o...
[ "def", "find_state_op_colocation_error", "(", "graph", ",", "reported_tags", "=", "None", ")", ":", "state_op_types", "=", "list_registered_stateful_ops_without_inputs", "(", ")", "state_op_map", "=", "{", "op", ".", "name", ":", "op", "for", "op", "in", "graph", ...
Returns error message for colocation of state ops, or None if ok.
[ "Returns", "error", "message", "for", "colocation", "of", "state", "ops", "or", "None", "if", "ok", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L1040-L1058
train
tensorflow/hub
tensorflow_hub/native_module.py
find_signature_input_colocation_error
def find_signature_input_colocation_error(signature_name, inputs): """Returns error message for colocation of signature inputs, or None if ok.""" for input_name, tensor in inputs.items(): expected_colocation_groups = [tf.compat.as_bytes("loc:@" + tensor.op.name)] if tensor.op.colocation_groups() != expected...
python
def find_signature_input_colocation_error(signature_name, inputs): """Returns error message for colocation of signature inputs, or None if ok.""" for input_name, tensor in inputs.items(): expected_colocation_groups = [tf.compat.as_bytes("loc:@" + tensor.op.name)] if tensor.op.colocation_groups() != expected...
[ "def", "find_signature_input_colocation_error", "(", "signature_name", ",", "inputs", ")", ":", "for", "input_name", ",", "tensor", "in", "inputs", ".", "items", "(", ")", ":", "expected_colocation_groups", "=", "[", "tf", ".", "compat", ".", "as_bytes", "(", ...
Returns error message for colocation of signature inputs, or None if ok.
[ "Returns", "error", "message", "for", "colocation", "of", "signature", "inputs", "or", "None", "if", "ok", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L1061-L1072
train
tensorflow/hub
tensorflow_hub/native_module.py
find_signature_inputs_from_multivalued_ops
def find_signature_inputs_from_multivalued_ops(inputs): """Returns error message for module inputs from ops with multiple outputs.""" dense_inputs = [] # List of (str, Tensor), with SparseTensors decomposed. for name, tensor in sorted(inputs.items()): if isinstance(tensor, tf.SparseTensor): dense_input...
python
def find_signature_inputs_from_multivalued_ops(inputs): """Returns error message for module inputs from ops with multiple outputs.""" dense_inputs = [] # List of (str, Tensor), with SparseTensors decomposed. for name, tensor in sorted(inputs.items()): if isinstance(tensor, tf.SparseTensor): dense_input...
[ "def", "find_signature_inputs_from_multivalued_ops", "(", "inputs", ")", ":", "dense_inputs", "=", "[", "]", "# List of (str, Tensor), with SparseTensors decomposed.", "for", "name", ",", "tensor", "in", "sorted", "(", "inputs", ".", "items", "(", ")", ")", ":", "if...
Returns error message for module inputs from ops with multiple outputs.
[ "Returns", "error", "message", "for", "module", "inputs", "from", "ops", "with", "multiple", "outputs", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L1075-L1093
train
tensorflow/hub
tensorflow_hub/native_module.py
_ModuleSpec._export
def _export(self, path, variables_saver): """Internal. Args: path: string where to export the module to. variables_saver: an unary-function that writes the module variables checkpoint on the given path. """ self._saved_model_handler.export(path, variables_saver=variables_saver) ...
python
def _export(self, path, variables_saver): """Internal. Args: path: string where to export the module to. variables_saver: an unary-function that writes the module variables checkpoint on the given path. """ self._saved_model_handler.export(path, variables_saver=variables_saver) ...
[ "def", "_export", "(", "self", ",", "path", ",", "variables_saver", ")", ":", "self", ".", "_saved_model_handler", ".", "export", "(", "path", ",", "variables_saver", "=", "variables_saver", ")", "module_def_proto", "=", "module_def_pb2", ".", "ModuleDef", "(", ...
Internal. Args: path: string where to export the module to. variables_saver: an unary-function that writes the module variables checkpoint on the given path.
[ "Internal", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L342-L359
train
tensorflow/hub
tensorflow_hub/native_module.py
_ModuleImpl._create_state_graph
def _create_state_graph(self, name): """Creates the graph nodes that hold the state of the Module. Args: name: name scope to create the state graph in. Returns: A tuple consisting of: variables_tensor_map: a map from tensor names in the original graph def to the created Varia...
python
def _create_state_graph(self, name): """Creates the graph nodes that hold the state of the Module. Args: name: name scope to create the state graph in. Returns: A tuple consisting of: variables_tensor_map: a map from tensor names in the original graph def to the created Varia...
[ "def", "_create_state_graph", "(", "self", ",", "name", ")", ":", "import_collections", "=", "[", "tf_v1", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ",", "tf_v1", ".", "GraphKeys", ".", "MODEL_VARIABLES", ",", "tf_v1", ".", "GraphKeys", ".", "TABLE_INITIALIZERS...
Creates the graph nodes that hold the state of the Module. Args: name: name scope to create the state graph in. Returns: A tuple consisting of: variables_tensor_map: a map from tensor names in the original graph def to the created Variables objects. state_map: a map from ...
[ "Creates", "the", "graph", "nodes", "that", "hold", "the", "state", "of", "the", "Module", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L410-L470
train
tensorflow/hub
tensorflow_hub/native_module.py
_ModuleImpl.create_apply_graph
def create_apply_graph(self, signature, input_tensors, name): """See `ModuleImpl.create_apply_graph`.""" signature_def = self._meta_graph.signature_def.get(signature) meta_graph = meta_graph_pb2.MetaGraphDef() meta_graph.CopyFrom(self._meta_graph) apply_graph = tf_v1.get_default_graph() infeed_m...
python
def create_apply_graph(self, signature, input_tensors, name): """See `ModuleImpl.create_apply_graph`.""" signature_def = self._meta_graph.signature_def.get(signature) meta_graph = meta_graph_pb2.MetaGraphDef() meta_graph.CopyFrom(self._meta_graph) apply_graph = tf_v1.get_default_graph() infeed_m...
[ "def", "create_apply_graph", "(", "self", ",", "signature", ",", "input_tensors", ",", "name", ")", ":", "signature_def", "=", "self", ".", "_meta_graph", ".", "signature_def", ".", "get", "(", "signature", ")", "meta_graph", "=", "meta_graph_pb2", ".", "MetaG...
See `ModuleImpl.create_apply_graph`.
[ "See", "ModuleImpl", ".", "create_apply_graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L472-L561
train
tensorflow/hub
tensorflow_hub/native_module.py
_ModuleImpl.export
def export(self, path, session): """See `Module.export`.""" def variables_saver(variables_path): if self._saver: self._saver.save( session, variables_path, write_meta_graph=False, write_state=False) self._spec._export(path, variables_saver)
python
def export(self, path, session): """See `Module.export`.""" def variables_saver(variables_path): if self._saver: self._saver.save( session, variables_path, write_meta_graph=False, write_state=False) self._spec._export(path, variables_saver)
[ "def", "export", "(", "self", ",", "path", ",", "session", ")", ":", "def", "variables_saver", "(", "variables_path", ")", ":", "if", "self", ".", "_saver", ":", "self", ".", "_saver", ".", "save", "(", "session", ",", "variables_path", ",", "write_meta_...
See `Module.export`.
[ "See", "Module", ".", "export", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L569-L578
train
tensorflow/hub
tensorflow_hub/native_module.py
_ConsistentValue.Set
def Set(self, value, context=None): """Receives a value for the object and some context on its source.""" if self.has_error: return if self.value is None: self.value = value self._context["old_value"] = value self._context.update({"old_" + k: v for k, v in context.items()}) elif self.v...
python
def Set(self, value, context=None): """Receives a value for the object and some context on its source.""" if self.has_error: return if self.value is None: self.value = value self._context["old_value"] = value self._context.update({"old_" + k: v for k, v in context.items()}) elif self.v...
[ "def", "Set", "(", "self", ",", "value", ",", "context", "=", "None", ")", ":", "if", "self", ".", "has_error", ":", "return", "if", "self", ".", "value", "is", "None", ":", "self", ".", "value", "=", "value", "self", ".", "_context", "[", "\"old_v...
Receives a value for the object and some context on its source.
[ "Receives", "a", "value", "for", "the", "object", "and", "some", "context", "on", "its", "source", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L897-L907
train
tensorflow/hub
tensorflow_hub/native_module.py
_ConsistentValue.GetConsistentValueOrRaise
def GetConsistentValueOrRaise(self, error_format, context=None): """Gets consistent value or raises ValueError with formatted contexts.""" if self.has_error: full_context = dict(self._context) if context: full_context.update(context) raise ValueError(error_format.format(**full_context)) re...
python
def GetConsistentValueOrRaise(self, error_format, context=None): """Gets consistent value or raises ValueError with formatted contexts.""" if self.has_error: full_context = dict(self._context) if context: full_context.update(context) raise ValueError(error_format.format(**full_context)) re...
[ "def", "GetConsistentValueOrRaise", "(", "self", ",", "error_format", ",", "context", "=", "None", ")", ":", "if", "self", ".", "has_error", ":", "full_context", "=", "dict", "(", "self", ".", "_context", ")", "if", "context", ":", "full_context", ".", "up...
Gets consistent value or raises ValueError with formatted contexts.
[ "Gets", "consistent", "value", "or", "raises", "ValueError", "with", "formatted", "contexts", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L909-L915
train
tensorflow/hub
tensorflow_hub/compressed_module_resolver.py
_module_dir
def _module_dir(handle): """Returns the directory where to cache the module.""" cache_dir = resolver.tfhub_cache_dir(use_temp=True) return resolver.create_local_module_dir( cache_dir, hashlib.sha1(handle.encode("utf8")).hexdigest())
python
def _module_dir(handle): """Returns the directory where to cache the module.""" cache_dir = resolver.tfhub_cache_dir(use_temp=True) return resolver.create_local_module_dir( cache_dir, hashlib.sha1(handle.encode("utf8")).hexdigest())
[ "def", "_module_dir", "(", "handle", ")", ":", "cache_dir", "=", "resolver", ".", "tfhub_cache_dir", "(", "use_temp", "=", "True", ")", "return", "resolver", ".", "create_local_module_dir", "(", "cache_dir", ",", "hashlib", ".", "sha1", "(", "handle", ".", "...
Returns the directory where to cache the module.
[ "Returns", "the", "directory", "where", "to", "cache", "the", "module", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/compressed_module_resolver.py#L44-L49
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
get_variables_path
def get_variables_path(export_dir): """Returns the path for storing variables checkpoints.""" return os.path.join( tf.compat.as_bytes(export_dir), tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_DIRECTORY), tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_FILENAME))
python
def get_variables_path(export_dir): """Returns the path for storing variables checkpoints.""" return os.path.join( tf.compat.as_bytes(export_dir), tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_DIRECTORY), tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_FILENAME))
[ "def", "get_variables_path", "(", "export_dir", ")", ":", "return", "os", ".", "path", ".", "join", "(", "tf", ".", "compat", ".", "as_bytes", "(", "export_dir", ")", ",", "tf", ".", "compat", ".", "as_bytes", "(", "tf_v1", ".", "saved_model", ".", "co...
Returns the path for storing variables checkpoints.
[ "Returns", "the", "path", "for", "storing", "variables", "checkpoints", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L52-L57
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_get_node_name_from_tensor
def _get_node_name_from_tensor(tensor_name): """tensor_name must have format node_name:output_number. Returns node_name.""" result = re.match(r"([^:]*):\d+$", tensor_name) if not result: raise ValueError( "Unexpected format for tensor name. Expected node_name:output_number. " "Got %r" % tensor...
python
def _get_node_name_from_tensor(tensor_name): """tensor_name must have format node_name:output_number. Returns node_name.""" result = re.match(r"([^:]*):\d+$", tensor_name) if not result: raise ValueError( "Unexpected format for tensor name. Expected node_name:output_number. " "Got %r" % tensor...
[ "def", "_get_node_name_from_tensor", "(", "tensor_name", ")", ":", "result", "=", "re", ".", "match", "(", "r\"([^:]*):\\d+$\"", ",", "tensor_name", ")", "if", "not", "result", ":", "raise", "ValueError", "(", "\"Unexpected format for tensor name. Expected node_name:out...
tensor_name must have format node_name:output_number. Returns node_name.
[ "tensor_name", "must", "have", "format", "node_name", ":", "output_number", ".", "Returns", "node_name", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L84-L91
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
add_signature
def add_signature(key, inputs, outputs): """Adds a signature to current graph. Args: key: Signature key as a string. inputs: Signature inputs as a map from string to Tensor or SparseTensor. outputs: Signature outputs as a map from string to Tensor or SparseTensor. (Recall that a Variable is not a...
python
def add_signature(key, inputs, outputs): """Adds a signature to current graph. Args: key: Signature key as a string. inputs: Signature inputs as a map from string to Tensor or SparseTensor. outputs: Signature outputs as a map from string to Tensor or SparseTensor. (Recall that a Variable is not a...
[ "def", "add_signature", "(", "key", ",", "inputs", ",", "outputs", ")", ":", "_check_dict_maps_to_tensors_or_sparse_tensors", "(", "inputs", ")", "_check_dict_maps_to_tensors_or_sparse_tensors", "(", "outputs", ")", "input_info", "=", "{", "input_name", ":", "tf_v1", ...
Adds a signature to current graph. Args: key: Signature key as a string. inputs: Signature inputs as a map from string to Tensor or SparseTensor. outputs: Signature outputs as a map from string to Tensor or SparseTensor. (Recall that a Variable is not a Tensor, but Variable.value() is.) Raises: ...
[ "Adds", "a", "signature", "to", "current", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L94-L118
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_export_signatures
def _export_signatures(meta_graph): """Exports signatures from current graph into a MetaGraphDef.""" named_signatures = tf_v1.get_collection(_SIGNATURE_COLLECTION) if not named_signatures: raise ValueError("No signatures present. Please call hub.add_signature(...)" "at least once in the m...
python
def _export_signatures(meta_graph): """Exports signatures from current graph into a MetaGraphDef.""" named_signatures = tf_v1.get_collection(_SIGNATURE_COLLECTION) if not named_signatures: raise ValueError("No signatures present. Please call hub.add_signature(...)" "at least once in the m...
[ "def", "_export_signatures", "(", "meta_graph", ")", ":", "named_signatures", "=", "tf_v1", ".", "get_collection", "(", "_SIGNATURE_COLLECTION", ")", "if", "not", "named_signatures", ":", "raise", "ValueError", "(", "\"No signatures present. Please call hub.add_signature(.....
Exports signatures from current graph into a MetaGraphDef.
[ "Exports", "signatures", "from", "current", "graph", "into", "a", "MetaGraphDef", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L129-L136
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
attach_bytes
def attach_bytes(key, the_bytes): """Adds a ModuleAttachment to the current graph. Args: key: A string with the unique key of the attachment. the_bytes: A bytes object with the serialized attachment. """ tf_v1.add_to_collection( _ATTACHMENT_COLLECTION_INTERNAL, module_attachment_pb2.ModuleA...
python
def attach_bytes(key, the_bytes): """Adds a ModuleAttachment to the current graph. Args: key: A string with the unique key of the attachment. the_bytes: A bytes object with the serialized attachment. """ tf_v1.add_to_collection( _ATTACHMENT_COLLECTION_INTERNAL, module_attachment_pb2.ModuleA...
[ "def", "attach_bytes", "(", "key", ",", "the_bytes", ")", ":", "tf_v1", ".", "add_to_collection", "(", "_ATTACHMENT_COLLECTION_INTERNAL", ",", "module_attachment_pb2", ".", "ModuleAttachment", "(", "key", "=", "key", ",", "value", "=", "the_bytes", ")", ")" ]
Adds a ModuleAttachment to the current graph. Args: key: A string with the unique key of the attachment. the_bytes: A bytes object with the serialized attachment.
[ "Adds", "a", "ModuleAttachment", "to", "the", "current", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L139-L148
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_export_module_attachments
def _export_module_attachments(meta_graph): """Exports ModuleAttachments from the current tf.Graph into `meta_graph`.""" added_attachments = tf_v1.get_collection(_ATTACHMENT_COLLECTION_INTERNAL) if not added_attachments: return # Don't touch `meta_graph`. unique_attachments = collections.OrderedDict( # Avoid ...
python
def _export_module_attachments(meta_graph): """Exports ModuleAttachments from the current tf.Graph into `meta_graph`.""" added_attachments = tf_v1.get_collection(_ATTACHMENT_COLLECTION_INTERNAL) if not added_attachments: return # Don't touch `meta_graph`. unique_attachments = collections.OrderedDict( # Avoid ...
[ "def", "_export_module_attachments", "(", "meta_graph", ")", ":", "added_attachments", "=", "tf_v1", ".", "get_collection", "(", "_ATTACHMENT_COLLECTION_INTERNAL", ")", "if", "not", "added_attachments", ":", "return", "# Don't touch `meta_graph`.", "unique_attachments", "="...
Exports ModuleAttachments from the current tf.Graph into `meta_graph`.
[ "Exports", "ModuleAttachments", "from", "the", "current", "tf", ".", "Graph", "into", "meta_graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L151-L160
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
get_attached_bytes_map
def get_attached_bytes_map(meta_graph): """Returns the dict of ModuleAttachments stored in `meta_graph`. Args: meta_graph: A MetaGraphDef, as built by SavedModelHandler.add_graph_copy() from some graph. Returns: A dict, containing the `(key, bytes)` items passed to `attach_bytes()` when the gr...
python
def get_attached_bytes_map(meta_graph): """Returns the dict of ModuleAttachments stored in `meta_graph`. Args: meta_graph: A MetaGraphDef, as built by SavedModelHandler.add_graph_copy() from some graph. Returns: A dict, containing the `(key, bytes)` items passed to `attach_bytes()` when the gr...
[ "def", "get_attached_bytes_map", "(", "meta_graph", ")", ":", "result", "=", "{", "}", "if", "ATTACHMENT_COLLECTION_SAVED", "not", "in", "meta_graph", ".", "collection_def", ":", "return", "result", "collection_def", "=", "meta_graph", ".", "collection_def", "[", ...
Returns the dict of ModuleAttachments stored in `meta_graph`. Args: meta_graph: A MetaGraphDef, as built by SavedModelHandler.add_graph_copy() from some graph. Returns: A dict, containing the `(key, bytes)` items passed to `attach_bytes()` when the graph had been built. Raises: ValueError...
[ "Returns", "the", "dict", "of", "ModuleAttachments", "stored", "in", "meta_graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L163-L189
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_check_asset_node_def
def _check_asset_node_def(node_def): """Raises TypeError if `node_def` does not match the expectations.""" if node_def.op != "Const": raise TypeError("Asset node must be of type constant.") if tf.as_dtype(node_def.attr["dtype"].type) != tf.string: raise TypeError("Asset node must be of dtype string.") i...
python
def _check_asset_node_def(node_def): """Raises TypeError if `node_def` does not match the expectations.""" if node_def.op != "Const": raise TypeError("Asset node must be of type constant.") if tf.as_dtype(node_def.attr["dtype"].type) != tf.string: raise TypeError("Asset node must be of dtype string.") i...
[ "def", "_check_asset_node_def", "(", "node_def", ")", ":", "if", "node_def", ".", "op", "!=", "\"Const\"", ":", "raise", "TypeError", "(", "\"Asset node must be of type constant.\"", ")", "if", "tf", ".", "as_dtype", "(", "node_def", ".", "attr", "[", "\"dtype\"...
Raises TypeError if `node_def` does not match the expectations.
[ "Raises", "TypeError", "if", "node_def", "does", "not", "match", "the", "expectations", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L198-L205
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_merge_assets_key_collection
def _merge_assets_key_collection(saved_model_proto, path): """Merges the ASSETS_KEY collection into the GraphDefs in saved_model_proto. Removes the ASSETS_KEY collection from the GraphDefs in the SavedModel and modifies nodes with the assets filenames to point to the assets in `path`. After this transformation...
python
def _merge_assets_key_collection(saved_model_proto, path): """Merges the ASSETS_KEY collection into the GraphDefs in saved_model_proto. Removes the ASSETS_KEY collection from the GraphDefs in the SavedModel and modifies nodes with the assets filenames to point to the assets in `path`. After this transformation...
[ "def", "_merge_assets_key_collection", "(", "saved_model_proto", ",", "path", ")", ":", "for", "meta_graph", "in", "saved_model_proto", ".", "meta_graphs", ":", "node_asset_map", "=", "{", "}", "if", "tf_v1", ".", "saved_model", ".", "constants", ".", "ASSETS_KEY"...
Merges the ASSETS_KEY collection into the GraphDefs in saved_model_proto. Removes the ASSETS_KEY collection from the GraphDefs in the SavedModel and modifies nodes with the assets filenames to point to the assets in `path`. After this transformation, the SavedModel GraphDefs can be used without feeding asset t...
[ "Merges", "the", "ASSETS_KEY", "collection", "into", "the", "GraphDefs", "in", "saved_model_proto", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L208-L237
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_make_assets_key_collection
def _make_assets_key_collection(saved_model_proto, export_path): """Creates an ASSETS_KEY collection in the GraphDefs in saved_model_proto. Adds an ASSETS_KEY collection to the GraphDefs in the SavedModel and returns a map from original asset filename to filename when exporting the SavedModel to `export_path`....
python
def _make_assets_key_collection(saved_model_proto, export_path): """Creates an ASSETS_KEY collection in the GraphDefs in saved_model_proto. Adds an ASSETS_KEY collection to the GraphDefs in the SavedModel and returns a map from original asset filename to filename when exporting the SavedModel to `export_path`....
[ "def", "_make_assets_key_collection", "(", "saved_model_proto", ",", "export_path", ")", ":", "asset_filenames", "=", "{", "}", "used_asset_filenames", "=", "set", "(", ")", "def", "_make_asset_filename", "(", "original_filename", ")", ":", "\"\"\"Returns the asset file...
Creates an ASSETS_KEY collection in the GraphDefs in saved_model_proto. Adds an ASSETS_KEY collection to the GraphDefs in the SavedModel and returns a map from original asset filename to filename when exporting the SavedModel to `export_path`. This is roughly the inverse operation of `_merge_assets_key_collec...
[ "Creates", "an", "ASSETS_KEY", "collection", "in", "the", "GraphDefs", "in", "saved_model_proto", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L240-L320
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_parse_saved_model
def _parse_saved_model(path): """Reads the savedmodel.pb file containing `SavedModel`.""" # Based on tensorflow/python/saved_model/loader.py implementation. path_to_pb = _get_saved_model_proto_path(path) file_content = tf_v1.gfile.Open(path_to_pb, "rb").read() saved_model = saved_model_pb2.SavedModel() try:...
python
def _parse_saved_model(path): """Reads the savedmodel.pb file containing `SavedModel`.""" # Based on tensorflow/python/saved_model/loader.py implementation. path_to_pb = _get_saved_model_proto_path(path) file_content = tf_v1.gfile.Open(path_to_pb, "rb").read() saved_model = saved_model_pb2.SavedModel() try:...
[ "def", "_parse_saved_model", "(", "path", ")", ":", "# Based on tensorflow/python/saved_model/loader.py implementation.", "path_to_pb", "=", "_get_saved_model_proto_path", "(", "path", ")", "file_content", "=", "tf_v1", ".", "gfile", ".", "Open", "(", "path_to_pb", ",", ...
Reads the savedmodel.pb file containing `SavedModel`.
[ "Reads", "the", "savedmodel", ".", "pb", "file", "containing", "SavedModel", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L441-L451
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
load
def load(path): """Creates a SavedModelHandler from a SavedModel in `path`.""" proto = _parse_saved_model(path) _merge_assets_key_collection(proto, path) handler = SavedModelHandler() handler._proto = proto # pylint: disable=protected-access return handler
python
def load(path): """Creates a SavedModelHandler from a SavedModel in `path`.""" proto = _parse_saved_model(path) _merge_assets_key_collection(proto, path) handler = SavedModelHandler() handler._proto = proto # pylint: disable=protected-access return handler
[ "def", "load", "(", "path", ")", ":", "proto", "=", "_parse_saved_model", "(", "path", ")", "_merge_assets_key_collection", "(", "proto", ",", "path", ")", "handler", "=", "SavedModelHandler", "(", ")", "handler", ".", "_proto", "=", "proto", "# pylint: disabl...
Creates a SavedModelHandler from a SavedModel in `path`.
[ "Creates", "a", "SavedModelHandler", "from", "a", "SavedModel", "in", "path", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L454-L460
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
SavedModelHandler.add_graph_copy
def add_graph_copy(self, graph, tags=None): """Adds a copy of Graph with the specified set of tags.""" with graph.as_default(): # Remove default attrs so that Modules created by a tensorflow version # with ops that have new attrs that are left to their default values can # still be loaded by o...
python
def add_graph_copy(self, graph, tags=None): """Adds a copy of Graph with the specified set of tags.""" with graph.as_default(): # Remove default attrs so that Modules created by a tensorflow version # with ops that have new attrs that are left to their default values can # still be loaded by o...
[ "def", "add_graph_copy", "(", "self", ",", "graph", ",", "tags", "=", "None", ")", ":", "with", "graph", ".", "as_default", "(", ")", ":", "# Remove default attrs so that Modules created by a tensorflow version", "# with ops that have new attrs that are left to their default ...
Adds a copy of Graph with the specified set of tags.
[ "Adds", "a", "copy", "of", "Graph", "with", "the", "specified", "set", "of", "tags", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L357-L367
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
SavedModelHandler.get_meta_graph_copy
def get_meta_graph_copy(self, tags=None): """Returns a copy of a MetaGraph with the identical set of tags.""" meta_graph = self.get_meta_graph(tags) copy = tf_v1.MetaGraphDef() copy.CopyFrom(meta_graph) return copy
python
def get_meta_graph_copy(self, tags=None): """Returns a copy of a MetaGraph with the identical set of tags.""" meta_graph = self.get_meta_graph(tags) copy = tf_v1.MetaGraphDef() copy.CopyFrom(meta_graph) return copy
[ "def", "get_meta_graph_copy", "(", "self", ",", "tags", "=", "None", ")", ":", "meta_graph", "=", "self", ".", "get_meta_graph", "(", "tags", ")", "copy", "=", "tf_v1", ".", "MetaGraphDef", "(", ")", "copy", ".", "CopyFrom", "(", "meta_graph", ")", "retu...
Returns a copy of a MetaGraph with the identical set of tags.
[ "Returns", "a", "copy", "of", "a", "MetaGraph", "with", "the", "identical", "set", "of", "tags", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L372-L377
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
SavedModelHandler.get_tags
def get_tags(self): """Returns a list of set of tags.""" return sorted([frozenset(meta_graph.meta_info_def.tags) for meta_graph in self.meta_graphs])
python
def get_tags(self): """Returns a list of set of tags.""" return sorted([frozenset(meta_graph.meta_info_def.tags) for meta_graph in self.meta_graphs])
[ "def", "get_tags", "(", "self", ")", ":", "return", "sorted", "(", "[", "frozenset", "(", "meta_graph", ".", "meta_info_def", ".", "tags", ")", "for", "meta_graph", "in", "self", ".", "meta_graphs", "]", ")" ]
Returns a list of set of tags.
[ "Returns", "a", "list", "of", "set", "of", "tags", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L383-L386
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
SavedModelHandler.export
def export(self, path, variables_saver=None): """Exports to SavedModel directory. Args: path: path where to export the SavedModel to. variables_saver: lambda that receives a directory path where to export checkpoints of variables. """ # Operate on a copy of self._proto since it need...
python
def export(self, path, variables_saver=None): """Exports to SavedModel directory. Args: path: path where to export the SavedModel to. variables_saver: lambda that receives a directory path where to export checkpoints of variables. """ # Operate on a copy of self._proto since it need...
[ "def", "export", "(", "self", ",", "path", ",", "variables_saver", "=", "None", ")", ":", "# Operate on a copy of self._proto since it needs to be modified.", "proto", "=", "saved_model_pb2", ".", "SavedModel", "(", ")", "proto", ".", "CopyFrom", "(", "self", ".", ...
Exports to SavedModel directory. Args: path: path where to export the SavedModel to. variables_saver: lambda that receives a directory path where to export checkpoints of variables.
[ "Exports", "to", "SavedModel", "directory", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L391-L406
train
tensorflow/hub
tensorflow_hub/saved_model_lib.py
SavedModelHandler.get_meta_graph
def get_meta_graph(self, tags=None): """Returns the matching MetaGraphDef or raises KeyError.""" matches = [meta_graph for meta_graph in self.meta_graphs if set(meta_graph.meta_info_def.tags) == set(tags or [])] if not matches: raise KeyError("SavedModelHandler has no gra...
python
def get_meta_graph(self, tags=None): """Returns the matching MetaGraphDef or raises KeyError.""" matches = [meta_graph for meta_graph in self.meta_graphs if set(meta_graph.meta_info_def.tags) == set(tags or [])] if not matches: raise KeyError("SavedModelHandler has no gra...
[ "def", "get_meta_graph", "(", "self", ",", "tags", "=", "None", ")", ":", "matches", "=", "[", "meta_graph", "for", "meta_graph", "in", "self", ".", "meta_graphs", "if", "set", "(", "meta_graph", ".", "meta_info_def", ".", "tags", ")", "==", "set", "(", ...
Returns the matching MetaGraphDef or raises KeyError.
[ "Returns", "the", "matching", "MetaGraphDef", "or", "raises", "KeyError", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L408-L418
train
tensorflow/hub
tensorflow_hub/keras_layer.py
KerasLayer._add_existing_weight
def _add_existing_weight(self, weight, trainable=None): """Calls add_weight() to register but not create an existing weight.""" if trainable is None: trainable = weight.trainable self.add_weight(name=weight.name, shape=weight.shape, dtype=weight.dtype, trainable=trainable, getter=lambda ...
python
def _add_existing_weight(self, weight, trainable=None): """Calls add_weight() to register but not create an existing weight.""" if trainable is None: trainable = weight.trainable self.add_weight(name=weight.name, shape=weight.shape, dtype=weight.dtype, trainable=trainable, getter=lambda ...
[ "def", "_add_existing_weight", "(", "self", ",", "weight", ",", "trainable", "=", "None", ")", ":", "if", "trainable", "is", "None", ":", "trainable", "=", "weight", ".", "trainable", "self", ".", "add_weight", "(", "name", "=", "weight", ".", "name", ",...
Calls add_weight() to register but not create an existing weight.
[ "Calls", "add_weight", "()", "to", "register", "but", "not", "create", "an", "existing", "weight", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/keras_layer.py#L138-L142
train
tensorflow/hub
tensorflow_hub/module.py
export_module_spec
def export_module_spec(spec, path, checkpoint_path, name_transform_fn): """Helper function to ModuleSpec.export().""" with tf.Graph().as_default(): m = Module(spec) assign_map = { name_transform_fn(name): value for name, value in m.variable_map.items() } tf_v1.train.init_from_checkpoint(chec...
python
def export_module_spec(spec, path, checkpoint_path, name_transform_fn): """Helper function to ModuleSpec.export().""" with tf.Graph().as_default(): m = Module(spec) assign_map = { name_transform_fn(name): value for name, value in m.variable_map.items() } tf_v1.train.init_from_checkpoint(chec...
[ "def", "export_module_spec", "(", "spec", ",", "path", ",", "checkpoint_path", ",", "name_transform_fn", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "m", "=", "Module", "(", "spec", ")", "assign_map", "=", "{", "na...
Helper function to ModuleSpec.export().
[ "Helper", "function", "to", "ModuleSpec", ".", "export", "()", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L64-L75
train
tensorflow/hub
tensorflow_hub/module.py
_try_get_state_scope
def _try_get_state_scope(name, mark_name_scope_used=True): """Returns a fresh variable/name scope for a module's state. In order to import a module into a given scope without major complications we require the scope to be empty. This function deals with deciding an unused scope where to define the module state...
python
def _try_get_state_scope(name, mark_name_scope_used=True): """Returns a fresh variable/name scope for a module's state. In order to import a module into a given scope without major complications we require the scope to be empty. This function deals with deciding an unused scope where to define the module state...
[ "def", "_try_get_state_scope", "(", "name", ",", "mark_name_scope_used", "=", "True", ")", ":", "tmp_scope_name", "=", "tf_v1", ".", "get_variable_scope", "(", ")", ".", "name", "if", "tmp_scope_name", ":", "tmp_scope_name", "+=", "\"/\"", "with", "tf", ".", "...
Returns a fresh variable/name scope for a module's state. In order to import a module into a given scope without major complications we require the scope to be empty. This function deals with deciding an unused scope where to define the module state. This is non trivial in cases where name_scope and variable_s...
[ "Returns", "a", "fresh", "variable", "/", "name", "scope", "for", "a", "module", "s", "state", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L352-L385
train
tensorflow/hub
tensorflow_hub/module.py
_prepare_dict_inputs
def _prepare_dict_inputs(inputs, tensor_info_map): """Converts inputs to a dict of inputs and checks extra/missing args. Args: inputs: inputs fed to Module.__call__(). tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo` describing the signature inputs. Returns: A dict of value...
python
def _prepare_dict_inputs(inputs, tensor_info_map): """Converts inputs to a dict of inputs and checks extra/missing args. Args: inputs: inputs fed to Module.__call__(). tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo` describing the signature inputs. Returns: A dict of value...
[ "def", "_prepare_dict_inputs", "(", "inputs", ",", "tensor_info_map", ")", ":", "if", "inputs", "is", "None", ":", "dict_inputs", "=", "{", "}", "elif", "isinstance", "(", "inputs", ",", "dict", ")", ":", "dict_inputs", "=", "inputs", "elif", "len", "(", ...
Converts inputs to a dict of inputs and checks extra/missing args. Args: inputs: inputs fed to Module.__call__(). tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo` describing the signature inputs. Returns: A dict of values with the same keys as tensor_info_map. Raises: ...
[ "Converts", "inputs", "to", "a", "dict", "of", "inputs", "and", "checks", "extra", "/", "missing", "args", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L388-L421
train
tensorflow/hub
tensorflow_hub/module.py
_convert_dict_inputs
def _convert_dict_inputs(inputs, tensor_info_map): """Converts from inputs into dict of input tensors. This handles: - putting inputs into a dict, per _prepare_dict_inputs(), - converting all input values into tensors compatible with the expected input tensor (dtype, shape). - check sparse/non-sp...
python
def _convert_dict_inputs(inputs, tensor_info_map): """Converts from inputs into dict of input tensors. This handles: - putting inputs into a dict, per _prepare_dict_inputs(), - converting all input values into tensors compatible with the expected input tensor (dtype, shape). - check sparse/non-sp...
[ "def", "_convert_dict_inputs", "(", "inputs", ",", "tensor_info_map", ")", ":", "dict_inputs", "=", "_prepare_dict_inputs", "(", "inputs", ",", "tensor_info_map", ")", "return", "tensor_info", ".", "convert_dict_to_compatible_tensor", "(", "dict_inputs", ",", "tensor_in...
Converts from inputs into dict of input tensors. This handles: - putting inputs into a dict, per _prepare_dict_inputs(), - converting all input values into tensors compatible with the expected input tensor (dtype, shape). - check sparse/non-sparse tensor types. Args: inputs: inputs fed to Mo...
[ "Converts", "from", "inputs", "into", "dict", "of", "input", "tensors", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L424-L447
train
tensorflow/hub
tensorflow_hub/module.py
eval_function_for_module
def eval_function_for_module(spec, tags=None): """Context manager that yields a function to directly evaluate a Module. This creates a separate graph, in which all of the signatures of the module are instantiated. Then, it creates a session and initializes the module variables. Finally, it returns a function w...
python
def eval_function_for_module(spec, tags=None): """Context manager that yields a function to directly evaluate a Module. This creates a separate graph, in which all of the signatures of the module are instantiated. Then, it creates a session and initializes the module variables. Finally, it returns a function w...
[ "def", "eval_function_for_module", "(", "spec", ",", "tags", "=", "None", ")", ":", "# We create a separate graph and add all the signatures of the module to it.", "original_graph", "=", "tf_v1", ".", "get_default_graph", "(", ")", "with", "tf", ".", "Graph", "(", ")", ...
Context manager that yields a function to directly evaluate a Module. This creates a separate graph, in which all of the signatures of the module are instantiated. Then, it creates a session and initializes the module variables. Finally, it returns a function which can be used to evaluate the module signatures...
[ "Context", "manager", "that", "yields", "a", "function", "to", "directly", "evaluate", "a", "Module", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L474-L559
train
tensorflow/hub
tensorflow_hub/module.py
load
def load(handle): """Loads a module from a handle. Currently this method only works with Tensorflow 2.x and can only load modules created by calling tensorflow.saved_model.save(). The method works in both eager and graph modes. Depending on the type of handle used, the call may involve downloading a Tenso...
python
def load(handle): """Loads a module from a handle. Currently this method only works with Tensorflow 2.x and can only load modules created by calling tensorflow.saved_model.save(). The method works in both eager and graph modes. Depending on the type of handle used, the call may involve downloading a Tenso...
[ "def", "load", "(", "handle", ")", ":", "if", "hasattr", "(", "tf_v1", ".", "saved_model", ",", "\"load_v2\"", ")", ":", "module_handle", "=", "resolve", "(", "handle", ")", "return", "tf_v1", ".", "saved_model", ".", "load_v2", "(", "module_handle", ")", ...
Loads a module from a handle. Currently this method only works with Tensorflow 2.x and can only load modules created by calling tensorflow.saved_model.save(). The method works in both eager and graph modes. Depending on the type of handle used, the call may involve downloading a Tensorflow Hub module to a l...
[ "Loads", "a", "module", "from", "a", "handle", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L577-L613
train
tensorflow/hub
tensorflow_hub/module.py
Module.get_input_info_dict
def get_input_info_dict(self, signature=None): """Describes the inputs required by a signature. Args: signature: A string with the signature to get inputs information for. If None, the default signature is used if defined. Returns: The result of ModuleSpec.get_input_info_dict() for the...
python
def get_input_info_dict(self, signature=None): """Describes the inputs required by a signature. Args: signature: A string with the signature to get inputs information for. If None, the default signature is used if defined. Returns: The result of ModuleSpec.get_input_info_dict() for the...
[ "def", "get_input_info_dict", "(", "self", ",", "signature", "=", "None", ")", ":", "return", "self", ".", "_spec", ".", "get_input_info_dict", "(", "signature", "=", "signature", ",", "tags", "=", "self", ".", "_tags", ")" ]
Describes the inputs required by a signature. Args: signature: A string with the signature to get inputs information for. If None, the default signature is used if defined. Returns: The result of ModuleSpec.get_input_info_dict() for the given signature, and the graph variant selected...
[ "Describes", "the", "inputs", "required", "by", "a", "signature", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L257-L271
train
tensorflow/hub
tensorflow_hub/module.py
Module.get_output_info_dict
def get_output_info_dict(self, signature=None): """Describes the outputs provided by a signature. Args: signature: A string with the signature to get ouputs information for. If None, the default signature is used if defined. Returns: The result of ModuleSpec.get_output_info_dict() for ...
python
def get_output_info_dict(self, signature=None): """Describes the outputs provided by a signature. Args: signature: A string with the signature to get ouputs information for. If None, the default signature is used if defined. Returns: The result of ModuleSpec.get_output_info_dict() for ...
[ "def", "get_output_info_dict", "(", "self", ",", "signature", "=", "None", ")", ":", "return", "self", ".", "_spec", ".", "get_output_info_dict", "(", "signature", "=", "signature", ",", "tags", "=", "self", ".", "_tags", ")" ]
Describes the outputs provided by a signature. Args: signature: A string with the signature to get ouputs information for. If None, the default signature is used if defined. Returns: The result of ModuleSpec.get_output_info_dict() for the given signature, and the graph variant select...
[ "Describes", "the", "outputs", "provided", "by", "a", "signature", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L273-L287
train
tensorflow/hub
tensorflow_hub/module.py
Module.get_attached_message
def get_attached_message(self, key, message_type, required=False): """Calls ModuleSpec.get_attached_message(); see there for more.""" return self._spec.get_attached_message(key, message_type, tags=self._tags, required=required)
python
def get_attached_message(self, key, message_type, required=False): """Calls ModuleSpec.get_attached_message(); see there for more.""" return self._spec.get_attached_message(key, message_type, tags=self._tags, required=required)
[ "def", "get_attached_message", "(", "self", ",", "key", ",", "message_type", ",", "required", "=", "False", ")", ":", "return", "self", ".", "_spec", ".", "get_attached_message", "(", "key", ",", "message_type", ",", "tags", "=", "self", ".", "_tags", ",",...
Calls ModuleSpec.get_attached_message(); see there for more.
[ "Calls", "ModuleSpec", ".", "get_attached_message", "()", ";", "see", "there", "for", "more", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L289-L292
train
tensorflow/hub
tensorflow_hub/module.py
Module.export
def export(self, path, session): """Exports the module with the variables from the session in `path`. Note that it is the module definition in the ModuleSpec used to create this module that gets exported. The session is only used to provide the value of variables. Args: path: path where to e...
python
def export(self, path, session): """Exports the module with the variables from the session in `path`. Note that it is the module definition in the ModuleSpec used to create this module that gets exported. The session is only used to provide the value of variables. Args: path: path where to e...
[ "def", "export", "(", "self", ",", "path", ",", "session", ")", ":", "if", "self", ".", "_graph", "is", "not", "tf_v1", ".", "get_default_graph", "(", ")", ":", "raise", "RuntimeError", "(", "\"default graph differs from the graph where the \"", "\"module was inst...
Exports the module with the variables from the session in `path`. Note that it is the module definition in the ModuleSpec used to create this module that gets exported. The session is only used to provide the value of variables. Args: path: path where to export the module to. session: sess...
[ "Exports", "the", "module", "with", "the", "variables", "from", "the", "session", "in", "path", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L294-L314
train
tensorflow/hub
tensorflow_hub/module.py
Module.variables
def variables(self): """Returns the list of all tf.Variables created by module instantiation.""" result = [] for _, value in sorted(self.variable_map.items()): if isinstance(value, list): result.extend(value) else: result.append(value) return result
python
def variables(self): """Returns the list of all tf.Variables created by module instantiation.""" result = [] for _, value in sorted(self.variable_map.items()): if isinstance(value, list): result.extend(value) else: result.append(value) return result
[ "def", "variables", "(", "self", ")", ":", "result", "=", "[", "]", "for", "_", ",", "value", "in", "sorted", "(", "self", ".", "variable_map", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "result", "...
Returns the list of all tf.Variables created by module instantiation.
[ "Returns", "the", "list", "of", "all", "tf", ".", "Variables", "created", "by", "module", "instantiation", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L341-L349
train
tensorflow/hub
tensorflow_hub/feature_column.py
text_embedding_column
def text_embedding_column(key, module_spec, trainable=False): """Uses a Module to construct a dense representation from a text feature. This feature column can be used on an input feature whose values are strings of arbitrary size. The result of this feature column is the result of passing its `input` throu...
python
def text_embedding_column(key, module_spec, trainable=False): """Uses a Module to construct a dense representation from a text feature. This feature column can be used on an input feature whose values are strings of arbitrary size. The result of this feature column is the result of passing its `input` throu...
[ "def", "text_embedding_column", "(", "key", ",", "module_spec", ",", "trainable", "=", "False", ")", ":", "module_spec", "=", "module", ".", "as_module_spec", "(", "module_spec", ")", "_check_module_is_text_embedding", "(", "module_spec", ")", "return", "_TextEmbedd...
Uses a Module to construct a dense representation from a text feature. This feature column can be used on an input feature whose values are strings of arbitrary size. The result of this feature column is the result of passing its `input` through the module `m` instantiated from `module_spec`, as per `result...
[ "Uses", "a", "Module", "to", "construct", "a", "dense", "representation", "from", "a", "text", "feature", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/feature_column.py#L33-L80
train
tensorflow/hub
tensorflow_hub/feature_column.py
_check_module_is_text_embedding
def _check_module_is_text_embedding(module_spec): """Raises ValueError if `module_spec` is not a text-embedding module. Args: module_spec: A `ModuleSpec` to test. Raises: ValueError: if `module_spec` default signature is not compatible with Tensor(string, shape=(?,)) -> Tensor(float32, shape=(?,K))....
python
def _check_module_is_text_embedding(module_spec): """Raises ValueError if `module_spec` is not a text-embedding module. Args: module_spec: A `ModuleSpec` to test. Raises: ValueError: if `module_spec` default signature is not compatible with Tensor(string, shape=(?,)) -> Tensor(float32, shape=(?,K))....
[ "def", "_check_module_is_text_embedding", "(", "module_spec", ")", ":", "issues", "=", "[", "]", "# Find issues with signature inputs.", "input_info_dict", "=", "module_spec", ".", "get_input_info_dict", "(", ")", "if", "len", "(", "input_info_dict", ")", "!=", "1", ...
Raises ValueError if `module_spec` is not a text-embedding module. Args: module_spec: A `ModuleSpec` to test. Raises: ValueError: if `module_spec` default signature is not compatible with Tensor(string, shape=(?,)) -> Tensor(float32, shape=(?,K)).
[ "Raises", "ValueError", "if", "module_spec", "is", "not", "a", "text", "-", "embedding", "module", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/feature_column.py#L83-L124
train
tensorflow/hub
tensorflow_hub/feature_column.py
image_embedding_column
def image_embedding_column(key, module_spec): """Uses a Module to get a dense 1-D representation from the pixels of images. This feature column can be used on images, represented as float32 tensors of RGB pixel data in the range [0,1]. This can be read from a numeric_column() if the tf.Example input data happe...
python
def image_embedding_column(key, module_spec): """Uses a Module to get a dense 1-D representation from the pixels of images. This feature column can be used on images, represented as float32 tensors of RGB pixel data in the range [0,1]. This can be read from a numeric_column() if the tf.Example input data happe...
[ "def", "image_embedding_column", "(", "key", ",", "module_spec", ")", ":", "module_spec", "=", "module", ".", "as_module_spec", "(", "module_spec", ")", "_check_module_is_image_embedding", "(", "module_spec", ")", "return", "_ImageEmbeddingColumn", "(", "key", "=", ...
Uses a Module to get a dense 1-D representation from the pixels of images. This feature column can be used on images, represented as float32 tensors of RGB pixel data in the range [0,1]. This can be read from a numeric_column() if the tf.Example input data happens to have decoded images, all with the same shap...
[ "Uses", "a", "Module", "to", "get", "a", "dense", "1", "-", "D", "representation", "from", "the", "pixels", "of", "images", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/feature_column.py#L162-L201
train
tensorflow/hub
tensorflow_hub/feature_column.py
_check_module_is_image_embedding
def _check_module_is_image_embedding(module_spec): """Raises ValueError if `module_spec` is not usable as image embedding. Args: module_spec: A `_ModuleSpec` to test. Raises: ValueError: if `module_spec` default signature is not compatible with mappingan "images" input to a Tensor(float32, shape...
python
def _check_module_is_image_embedding(module_spec): """Raises ValueError if `module_spec` is not usable as image embedding. Args: module_spec: A `_ModuleSpec` to test. Raises: ValueError: if `module_spec` default signature is not compatible with mappingan "images" input to a Tensor(float32, shape...
[ "def", "_check_module_is_image_embedding", "(", "module_spec", ")", ":", "issues", "=", "[", "]", "# Find issues with \"default\" signature inputs. The common signatures for", "# image models prescribe a specific name; we trust it if we find it", "# and if we can do the necessary inference o...
Raises ValueError if `module_spec` is not usable as image embedding. Args: module_spec: A `_ModuleSpec` to test. Raises: ValueError: if `module_spec` default signature is not compatible with mappingan "images" input to a Tensor(float32, shape=(_,K)).
[ "Raises", "ValueError", "if", "module_spec", "is", "not", "usable", "as", "image", "embedding", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/feature_column.py#L204-L245
train
tensorflow/hub
tensorflow_hub/feature_column.py
_TextEmbeddingColumn.name
def name(self): """Returns string. Used for variable_scope and naming.""" if not hasattr(self, "_name"): self._name = "{}_hub_module_embedding".format(self.key) return self._name
python
def name(self): """Returns string. Used for variable_scope and naming.""" if not hasattr(self, "_name"): self._name = "{}_hub_module_embedding".format(self.key) return self._name
[ "def", "name", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_name\"", ")", ":", "self", ".", "_name", "=", "\"{}_hub_module_embedding\"", ".", "format", "(", "self", ".", "key", ")", "return", "self", ".", "_name" ]
Returns string. Used for variable_scope and naming.
[ "Returns", "string", ".", "Used", "for", "variable_scope", "and", "naming", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/feature_column.py#L134-L138
train
tensorflow/hub
tensorflow_hub/feature_column.py
_TextEmbeddingColumn._get_dense_tensor
def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): """Returns a `Tensor`.""" del weight_collections text_batch = tf.reshape(inputs.get(self), shape=[-1]) m = module.Module(self.module_spec, trainable=self.trainable and trainable) return m(text_batch)
python
def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): """Returns a `Tensor`.""" del weight_collections text_batch = tf.reshape(inputs.get(self), shape=[-1]) m = module.Module(self.module_spec, trainable=self.trainable and trainable) return m(text_batch)
[ "def", "_get_dense_tensor", "(", "self", ",", "inputs", ",", "weight_collections", "=", "None", ",", "trainable", "=", "None", ")", ":", "del", "weight_collections", "text_batch", "=", "tf", ".", "reshape", "(", "inputs", ".", "get", "(", "self", ")", ",",...
Returns a `Tensor`.
[ "Returns", "a", "Tensor", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/feature_column.py#L154-L159
train
tensorflow/hub
tensorflow_hub/feature_column.py
_ImageEmbeddingColumn._parse_example_spec
def _parse_example_spec(self): """Returns a `tf.Example` parsing spec as dict.""" height, width = image_util.get_expected_image_size(self.module_spec) input_shape = [height, width, 3] return {self.key: tf_v1.FixedLenFeature(input_shape, tf.float32)}
python
def _parse_example_spec(self): """Returns a `tf.Example` parsing spec as dict.""" height, width = image_util.get_expected_image_size(self.module_spec) input_shape = [height, width, 3] return {self.key: tf_v1.FixedLenFeature(input_shape, tf.float32)}
[ "def", "_parse_example_spec", "(", "self", ")", ":", "height", ",", "width", "=", "image_util", ".", "get_expected_image_size", "(", "self", ".", "module_spec", ")", "input_shape", "=", "[", "height", ",", "width", ",", "3", "]", "return", "{", "self", "."...
Returns a `tf.Example` parsing spec as dict.
[ "Returns", "a", "tf", ".", "Example", "parsing", "spec", "as", "dict", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/feature_column.py#L265-L269
train
tensorflow/hub
tensorflow_hub/feature_column.py
_ImageEmbeddingColumn._get_dense_tensor
def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): """Returns a `Tensor` to represent this feature in the input_layer().""" del weight_collections, trainable # Unused. m = module.Module(self.module_spec, trainable=False) images = inputs.get(self) return m({"images": image...
python
def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): """Returns a `Tensor` to represent this feature in the input_layer().""" del weight_collections, trainable # Unused. m = module.Module(self.module_spec, trainable=False) images = inputs.get(self) return m({"images": image...
[ "def", "_get_dense_tensor", "(", "self", ",", "inputs", ",", "weight_collections", "=", "None", ",", "trainable", "=", "None", ")", ":", "del", "weight_collections", ",", "trainable", "# Unused.", "m", "=", "module", ".", "Module", "(", "self", ".", "module_...
Returns a `Tensor` to represent this feature in the input_layer().
[ "Returns", "a", "Tensor", "to", "represent", "this", "feature", "in", "the", "input_layer", "()", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/feature_column.py#L276-L281
train
tensorflow/hub
tensorflow_hub/module_v2.py
load
def load(handle): """Loads a module from a handle. Currently this method only works with Tensorflow 2.x and can only load modules created by calling tensorflow.saved_model.save(). The method works in both eager and graph modes. Depending on the type of handle used, the call may involve downloading a Tenso...
python
def load(handle): """Loads a module from a handle. Currently this method only works with Tensorflow 2.x and can only load modules created by calling tensorflow.saved_model.save(). The method works in both eager and graph modes. Depending on the type of handle used, the call may involve downloading a Tenso...
[ "def", "load", "(", "handle", ")", ":", "if", "hasattr", "(", "tf_v1", ".", "saved_model", ",", "\"load_v2\"", ")", ":", "module_handle", "=", "resolve", "(", "handle", ")", "if", "tf_v1", ".", "gfile", ".", "Exists", "(", "native_module", ".", "get_modu...
Loads a module from a handle. Currently this method only works with Tensorflow 2.x and can only load modules created by calling tensorflow.saved_model.save(). The method works in both eager and graph modes. Depending on the type of handle used, the call may involve downloading a Tensorflow Hub module to a l...
[ "Loads", "a", "module", "from", "a", "handle", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module_v2.py#L43-L83
train
tensorflow/hub
tensorflow_hub/resolver.py
tfhub_cache_dir
def tfhub_cache_dir(default_cache_dir=None, use_temp=False): """Returns cache directory. Returns cache directory from either TFHUB_CACHE_DIR environment variable or --tfhub_cache_dir or default, if set. Args: default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR ...
python
def tfhub_cache_dir(default_cache_dir=None, use_temp=False): """Returns cache directory. Returns cache directory from either TFHUB_CACHE_DIR environment variable or --tfhub_cache_dir or default, if set. Args: default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR ...
[ "def", "tfhub_cache_dir", "(", "default_cache_dir", "=", "None", ",", "use_temp", "=", "False", ")", ":", "# Note: We are using FLAGS[\"tfhub_cache_dir\"] (and not FLAGS.tfhub_cache_dir)", "# to access the flag value in order to avoid parsing argv list. The flags", "# should have been pa...
Returns cache directory. Returns cache directory from either TFHUB_CACHE_DIR environment variable or --tfhub_cache_dir or default, if set. Args: default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR environment variable nor --tfhub_cache_dir are ...
[ "Returns", "cache", "directory", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L50-L80
train
tensorflow/hub
tensorflow_hub/resolver.py
create_local_module_dir
def create_local_module_dir(cache_dir, module_name): """Creates and returns the name of directory where to cache a module.""" tf_v1.gfile.MakeDirs(cache_dir) return os.path.join(cache_dir, module_name)
python
def create_local_module_dir(cache_dir, module_name): """Creates and returns the name of directory where to cache a module.""" tf_v1.gfile.MakeDirs(cache_dir) return os.path.join(cache_dir, module_name)
[ "def", "create_local_module_dir", "(", "cache_dir", ",", "module_name", ")", ":", "tf_v1", ".", "gfile", ".", "MakeDirs", "(", "cache_dir", ")", "return", "os", ".", "path", ".", "join", "(", "cache_dir", ",", "module_name", ")" ]
Creates and returns the name of directory where to cache a module.
[ "Creates", "and", "returns", "the", "name", "of", "directory", "where", "to", "cache", "a", "module", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L83-L86
train
tensorflow/hub
tensorflow_hub/resolver.py
_merge_relative_path
def _merge_relative_path(dst_path, rel_path): """Merge a relative tar file to a destination (which can be "gs://...").""" # Convert rel_path to be relative and normalize it to remove ".", "..", "//", # which are valid directories in fileystems like "gs://". norm_rel_path = os.path.normpath(rel_path.lstrip("/"))...
python
def _merge_relative_path(dst_path, rel_path): """Merge a relative tar file to a destination (which can be "gs://...").""" # Convert rel_path to be relative and normalize it to remove ".", "..", "//", # which are valid directories in fileystems like "gs://". norm_rel_path = os.path.normpath(rel_path.lstrip("/"))...
[ "def", "_merge_relative_path", "(", "dst_path", ",", "rel_path", ")", ":", "# Convert rel_path to be relative and normalize it to remove \".\", \"..\", \"//\",", "# which are valid directories in fileystems like \"gs://\".", "norm_rel_path", "=", "os", ".", "path", ".", "normpath", ...
Merge a relative tar file to a destination (which can be "gs://...").
[ "Merge", "a", "relative", "tar", "file", "to", "a", "destination", "(", "which", "can", "be", "gs", ":", "//", "...", ")", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L192-L211
train
tensorflow/hub
tensorflow_hub/resolver.py
_write_module_descriptor_file
def _write_module_descriptor_file(handle, module_dir): """Writes a descriptor file about the directory containing a module. Args: handle: Module name/handle. module_dir: Directory where a module was downloaded. """ readme = _module_descriptor_file(module_dir) readme_content = ( "Module: %s\nDow...
python
def _write_module_descriptor_file(handle, module_dir): """Writes a descriptor file about the directory containing a module. Args: handle: Module name/handle. module_dir: Directory where a module was downloaded. """ readme = _module_descriptor_file(module_dir) readme_content = ( "Module: %s\nDow...
[ "def", "_write_module_descriptor_file", "(", "handle", ",", "module_dir", ")", ":", "readme", "=", "_module_descriptor_file", "(", "module_dir", ")", "readme_content", "=", "(", "\"Module: %s\\nDownload Time: %s\\nDownloader Hostname: %s (PID:%d)\"", "%", "(", "handle", ","...
Writes a descriptor file about the directory containing a module. Args: handle: Module name/handle. module_dir: Directory where a module was downloaded.
[ "Writes", "a", "descriptor", "file", "about", "the", "directory", "containing", "a", "module", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L219-L234
train
tensorflow/hub
tensorflow_hub/resolver.py
_dir_size
def _dir_size(directory): """Returns total size (in bytes) of the given 'directory'.""" size = 0 for elem in tf_v1.gfile.ListDirectory(directory): elem_full_path = os.path.join(directory, elem) stat = tf_v1.gfile.Stat(elem_full_path) size += _dir_size(elem_full_path) if stat.is_directory else stat.len...
python
def _dir_size(directory): """Returns total size (in bytes) of the given 'directory'.""" size = 0 for elem in tf_v1.gfile.ListDirectory(directory): elem_full_path = os.path.join(directory, elem) stat = tf_v1.gfile.Stat(elem_full_path) size += _dir_size(elem_full_path) if stat.is_directory else stat.len...
[ "def", "_dir_size", "(", "directory", ")", ":", "size", "=", "0", "for", "elem", "in", "tf_v1", ".", "gfile", ".", "ListDirectory", "(", "directory", ")", ":", "elem_full_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "elem", ")", ...
Returns total size (in bytes) of the given 'directory'.
[ "Returns", "total", "size", "(", "in", "bytes", ")", "of", "the", "given", "directory", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L273-L280
train
tensorflow/hub
tensorflow_hub/resolver.py
_locked_tmp_dir_size
def _locked_tmp_dir_size(lock_filename): """Returns the size of the temp dir pointed to by the given lock file.""" task_uid = _task_uid_from_lock_file(lock_filename) try: return _dir_size( _temp_download_dir(_module_dir(lock_filename), task_uid)) except tf.errors.NotFoundError: return 0
python
def _locked_tmp_dir_size(lock_filename): """Returns the size of the temp dir pointed to by the given lock file.""" task_uid = _task_uid_from_lock_file(lock_filename) try: return _dir_size( _temp_download_dir(_module_dir(lock_filename), task_uid)) except tf.errors.NotFoundError: return 0
[ "def", "_locked_tmp_dir_size", "(", "lock_filename", ")", ":", "task_uid", "=", "_task_uid_from_lock_file", "(", "lock_filename", ")", "try", ":", "return", "_dir_size", "(", "_temp_download_dir", "(", "_module_dir", "(", "lock_filename", ")", ",", "task_uid", ")", ...
Returns the size of the temp dir pointed to by the given lock file.
[ "Returns", "the", "size", "of", "the", "temp", "dir", "pointed", "to", "by", "the", "given", "lock", "file", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L283-L290
train
tensorflow/hub
tensorflow_hub/resolver.py
_wait_for_lock_to_disappear
def _wait_for_lock_to_disappear(handle, lock_file, lock_file_timeout_sec): """Waits for the lock file to disappear. The lock file was created by another process that is performing a download into its own temporary directory. The name of this temp directory is sha1(<module>).<uuid>.tmp where <uuid> comes from t...
python
def _wait_for_lock_to_disappear(handle, lock_file, lock_file_timeout_sec): """Waits for the lock file to disappear. The lock file was created by another process that is performing a download into its own temporary directory. The name of this temp directory is sha1(<module>).<uuid>.tmp where <uuid> comes from t...
[ "def", "_wait_for_lock_to_disappear", "(", "handle", ",", "lock_file", ",", "lock_file_timeout_sec", ")", ":", "locked_tmp_dir_size", "=", "0", "locked_tmp_dir_size_check_time", "=", "time", ".", "time", "(", ")", "lock_file_content", "=", "None", "while", "tf_v1", ...
Waits for the lock file to disappear. The lock file was created by another process that is performing a download into its own temporary directory. The name of this temp directory is sha1(<module>).<uuid>.tmp where <uuid> comes from the lock file. Args: handle: The location from where a module is being dow...
[ "Waits", "for", "the", "lock", "file", "to", "disappear", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L293-L342
train
tensorflow/hub
tensorflow_hub/resolver.py
atomic_download
def atomic_download(handle, download_fn, module_dir, lock_file_timeout_sec=10 * 60): """Returns the path to a Module directory for a given TF-Hub Module handle. Args: handle: (string) Location of a TF-Hub Module. download_fn: Callback function tha...
python
def atomic_download(handle, download_fn, module_dir, lock_file_timeout_sec=10 * 60): """Returns the path to a Module directory for a given TF-Hub Module handle. Args: handle: (string) Location of a TF-Hub Module. download_fn: Callback function tha...
[ "def", "atomic_download", "(", "handle", ",", "download_fn", ",", "module_dir", ",", "lock_file_timeout_sec", "=", "10", "*", "60", ")", ":", "lock_file", "=", "_lock_filename", "(", "module_dir", ")", "task_uid", "=", "uuid", ".", "uuid4", "(", ")", ".", ...
Returns the path to a Module directory for a given TF-Hub Module handle. Args: handle: (string) Location of a TF-Hub Module. download_fn: Callback function that actually performs download. The callback receives two arguments, handle and the location of a temporary directory ...
[ "Returns", "the", "path", "to", "a", "Module", "directory", "for", "a", "given", "TF", "-", "Hub", "Module", "handle", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L345-L434
train
tensorflow/hub
tensorflow_hub/resolver.py
DownloadManager._print_download_progress_msg
def _print_download_progress_msg(self, msg, flush=False): """Prints a message about download progress either to the console or TF log. Args: msg: Message to print. flush: Indicates whether to flush the output (only used in interactive mode). """ if self._interactive_mode(): ...
python
def _print_download_progress_msg(self, msg, flush=False): """Prints a message about download progress either to the console or TF log. Args: msg: Message to print. flush: Indicates whether to flush the output (only used in interactive mode). """ if self._interactive_mode(): ...
[ "def", "_print_download_progress_msg", "(", "self", ",", "msg", ",", "flush", "=", "False", ")", ":", "if", "self", ".", "_interactive_mode", "(", ")", ":", "# Print progress message to console overwriting previous progress", "# message.", "self", ".", "_max_prog_str", ...
Prints a message about download progress either to the console or TF log. Args: msg: Message to print. flush: Indicates whether to flush the output (only used in interactive mode).
[ "Prints", "a", "message", "about", "download", "progress", "either", "to", "the", "console", "or", "TF", "log", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L103-L122
train
tensorflow/hub
tensorflow_hub/resolver.py
DownloadManager._log_progress
def _log_progress(self, bytes_downloaded): """Logs progress information about ongoing module download. Args: bytes_downloaded: Number of bytes downloaded. """ self._total_bytes_downloaded += bytes_downloaded now = time.time() if (self._interactive_mode() or now - self._last_progre...
python
def _log_progress(self, bytes_downloaded): """Logs progress information about ongoing module download. Args: bytes_downloaded: Number of bytes downloaded. """ self._total_bytes_downloaded += bytes_downloaded now = time.time() if (self._interactive_mode() or now - self._last_progre...
[ "def", "_log_progress", "(", "self", ",", "bytes_downloaded", ")", ":", "self", ".", "_total_bytes_downloaded", "+=", "bytes_downloaded", "now", "=", "time", ".", "time", "(", ")", "if", "(", "self", ".", "_interactive_mode", "(", ")", "or", "now", "-", "s...
Logs progress information about ongoing module download. Args: bytes_downloaded: Number of bytes downloaded.
[ "Logs", "progress", "information", "about", "ongoing", "module", "download", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L124-L140
train
tensorflow/hub
tensorflow_hub/resolver.py
DownloadManager._extract_file
def _extract_file(self, tgz, tarinfo, dst_path, buffer_size=10<<20): """Extracts 'tarinfo' from 'tgz' and writes to 'dst_path'.""" src = tgz.extractfile(tarinfo) dst = tf_v1.gfile.GFile(dst_path, "wb") while 1: buf = src.read(buffer_size) if not buf: break dst.write(buf) ...
python
def _extract_file(self, tgz, tarinfo, dst_path, buffer_size=10<<20): """Extracts 'tarinfo' from 'tgz' and writes to 'dst_path'.""" src = tgz.extractfile(tarinfo) dst = tf_v1.gfile.GFile(dst_path, "wb") while 1: buf = src.read(buffer_size) if not buf: break dst.write(buf) ...
[ "def", "_extract_file", "(", "self", ",", "tgz", ",", "tarinfo", ",", "dst_path", ",", "buffer_size", "=", "10", "<<", "20", ")", ":", "src", "=", "tgz", ".", "extractfile", "(", "tarinfo", ")", "dst", "=", "tf_v1", ".", "gfile", ".", "GFile", "(", ...
Extracts 'tarinfo' from 'tgz' and writes to 'dst_path'.
[ "Extracts", "tarinfo", "from", "tgz", "and", "writes", "to", "dst_path", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L146-L157
train
tensorflow/hub
tensorflow_hub/resolver.py
DownloadManager.download_and_uncompress
def download_and_uncompress(self, fileobj, dst_path): """Streams the content for the 'fileobj' and stores the result in dst_path. Args: fileobj: File handle pointing to .tar/.tar.gz content. dst_path: Absolute path where to store uncompressed data from 'fileobj'. Raises: ValueError: Unkn...
python
def download_and_uncompress(self, fileobj, dst_path): """Streams the content for the 'fileobj' and stores the result in dst_path. Args: fileobj: File handle pointing to .tar/.tar.gz content. dst_path: Absolute path where to store uncompressed data from 'fileobj'. Raises: ValueError: Unkn...
[ "def", "download_and_uncompress", "(", "self", ",", "fileobj", ",", "dst_path", ")", ":", "try", ":", "with", "tarfile", ".", "open", "(", "mode", "=", "\"r|*\"", ",", "fileobj", "=", "fileobj", ")", "as", "tgz", ":", "for", "tarinfo", "in", "tgz", ":"...
Streams the content for the 'fileobj' and stores the result in dst_path. Args: fileobj: File handle pointing to .tar/.tar.gz content. dst_path: Absolute path where to store uncompressed data from 'fileobj'. Raises: ValueError: Unknown object encountered inside the TAR file.
[ "Streams", "the", "content", "for", "the", "fileobj", "and", "stores", "the", "result", "in", "dst_path", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/resolver.py#L159-L189
train
tensorflow/hub
tensorflow_hub/meta_graph_lib.py
prepend_name_scope
def prepend_name_scope(name, import_scope): """Prepends name scope to a name.""" # Based on tensorflow/python/framework/ops.py implementation. if import_scope: try: str_to_replace = r"([\^]|loc:@|^)(.*)" return re.sub(str_to_replace, r"\1" + import_scope + r"/\2", tf.compat.as_...
python
def prepend_name_scope(name, import_scope): """Prepends name scope to a name.""" # Based on tensorflow/python/framework/ops.py implementation. if import_scope: try: str_to_replace = r"([\^]|loc:@|^)(.*)" return re.sub(str_to_replace, r"\1" + import_scope + r"/\2", tf.compat.as_...
[ "def", "prepend_name_scope", "(", "name", ",", "import_scope", ")", ":", "# Based on tensorflow/python/framework/ops.py implementation.", "if", "import_scope", ":", "try", ":", "str_to_replace", "=", "r\"([\\^]|loc:@|^)(.*)\"", "return", "re", ".", "sub", "(", "str_to_rep...
Prepends name scope to a name.
[ "Prepends", "name", "scope", "to", "a", "name", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/meta_graph_lib.py#L32-L45
train
tensorflow/hub
tensorflow_hub/meta_graph_lib.py
prefix_shared_name_attributes
def prefix_shared_name_attributes(meta_graph, absolute_import_scope): """In-place prefixes shared_name attributes of nodes.""" shared_name_attr = "shared_name" for node in meta_graph.graph_def.node: shared_name_value = node.attr.get(shared_name_attr, None) if shared_name_value and shared_name_value.HasFie...
python
def prefix_shared_name_attributes(meta_graph, absolute_import_scope): """In-place prefixes shared_name attributes of nodes.""" shared_name_attr = "shared_name" for node in meta_graph.graph_def.node: shared_name_value = node.attr.get(shared_name_attr, None) if shared_name_value and shared_name_value.HasFie...
[ "def", "prefix_shared_name_attributes", "(", "meta_graph", ",", "absolute_import_scope", ")", ":", "shared_name_attr", "=", "\"shared_name\"", "for", "node", "in", "meta_graph", ".", "graph_def", ".", "node", ":", "shared_name_value", "=", "node", ".", "attr", ".", ...
In-place prefixes shared_name attributes of nodes.
[ "In", "-", "place", "prefixes", "shared_name", "attributes", "of", "nodes", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/meta_graph_lib.py#L48-L57
train
tensorflow/hub
tensorflow_hub/meta_graph_lib.py
mark_backward
def mark_backward(output_tensor, used_node_names): """Function to propagate backwards in the graph and mark nodes as used. Traverses recursively through the graph from the end tensor, through the op that generates the tensor, and then to the input tensors that feed the op. Nodes encountered are stored in used_...
python
def mark_backward(output_tensor, used_node_names): """Function to propagate backwards in the graph and mark nodes as used. Traverses recursively through the graph from the end tensor, through the op that generates the tensor, and then to the input tensors that feed the op. Nodes encountered are stored in used_...
[ "def", "mark_backward", "(", "output_tensor", ",", "used_node_names", ")", ":", "op", "=", "output_tensor", ".", "op", "if", "op", ".", "name", "in", "used_node_names", ":", "return", "used_node_names", ".", "add", "(", "op", ".", "name", ")", "for", "inpu...
Function to propagate backwards in the graph and mark nodes as used. Traverses recursively through the graph from the end tensor, through the op that generates the tensor, and then to the input tensors that feed the op. Nodes encountered are stored in used_node_names. Args: output_tensor: A Tensor which w...
[ "Function", "to", "propagate", "backwards", "in", "the", "graph", "and", "mark", "nodes", "as", "used", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/meta_graph_lib.py#L60-L81
train
tensorflow/hub
tensorflow_hub/meta_graph_lib.py
prune_unused_nodes
def prune_unused_nodes(meta_graph, signature_def): """Function to prune unused ops given a signature def. This function does a graph traversal through from all outputs as defined in the signature_def to collect all used nodes. Then, any nodes which are unused can be discarded. This is useful for graph which ar...
python
def prune_unused_nodes(meta_graph, signature_def): """Function to prune unused ops given a signature def. This function does a graph traversal through from all outputs as defined in the signature_def to collect all used nodes. Then, any nodes which are unused can be discarded. This is useful for graph which ar...
[ "def", "prune_unused_nodes", "(", "meta_graph", ",", "signature_def", ")", ":", "# Instantiate a temporary empty graph so that we have access to Graph API", "# and import the meta_graph.", "graph", "=", "tf_v1", ".", "Graph", "(", ")", "with", "graph", ".", "as_default", "(...
Function to prune unused ops given a signature def. This function does a graph traversal through from all outputs as defined in the signature_def to collect all used nodes. Then, any nodes which are unused can be discarded. This is useful for graph which are executing eagerly or on TPUs. Args: meta_grap...
[ "Function", "to", "prune", "unused", "ops", "given", "a", "signature", "def", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/meta_graph_lib.py#L84-L118
train