INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns all the coordinate tuples from a geometry or feature.
def iter_coords(obj): """ Returns all the coordinate tuples from a geometry or feature. """ if isinstance(obj, (tuple, list)): coords = obj elif 'features' in obj: coords = [geom['geometry']['coordinates'] for geom in obj['features']] elif 'geometry' in obj: coords = obj...
Mirrors the points in a list - of - list - of -... - of - list - of - points. For example: >>> _locations_mirror ( [[[ 1 2 ] [ 3 4 ]] [ 5 6 ] [ 7 8 ]] ) [[[ 2 1 ] [ 4 3 ]] [ 6 5 ] [ 8 7 ]]
def _locations_mirror(x): """ Mirrors the points in a list-of-list-of-...-of-list-of-points. For example: >>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]]) [[[2, 1], [4, 3]], [6, 5], [8, 7]] """ if hasattr(x, '__iter__'): if hasattr(x[0], '__iter__'): return list...
Computes the bounds of the object in the form [[ lat_min lon_min ] [ lat_max lon_max ]]
def get_bounds(locations, lonlat=False): """ Computes the bounds of the object in the form [[lat_min, lon_min], [lat_max, lon_max]] """ bounds = [[None, None], [None, None]] for point in iter_coords(locations): bounds = [ [ none_min(bounds[0][0], point[0]), ...
Convert a python_style_variable_name to lowerCamelCase.
def camelize(key): """Convert a python_style_variable_name to lowerCamelCase. Examples -------- >>> camelize('variable_name') 'variableName' >>> camelize('variableName') 'variableName' """ return ''.join(x.capitalize() if i > 0 else x for i, x in enumerate(key.spl...
Return the input string without non - functional spaces or newlines.
def normalize(rendered): """Return the input string without non-functional spaces or newlines.""" out = ''.join([line.strip() for line in rendered.splitlines() if line.strip()]) out = out.replace(', ', ',') return out
Yields the path of a temporary HTML file containing data.
def _tmp_html(data): """Yields the path of a temporary HTML file containing data.""" filepath = '' try: fid, filepath = tempfile.mkstemp(suffix='.html', prefix='folium_') os.write(fid, data.encode('utf8')) os.close(fid) yield filepath finally: if os.path.isfile(fi...
Return a recursive deep - copy of item where each copy has a new ID.
def deep_copy(item_original): """Return a recursive deep-copy of item where each copy has a new ID.""" item = copy.copy(item_original) item._id = uuid.uuid4().hex if hasattr(item, '_children') and len(item._children) > 0: children_new = collections.OrderedDict() for subitem_original in i...
Return the first object in the parent tree of class cls.
def get_obj_in_upper_tree(element, cls): """Return the first object in the parent tree of class `cls`.""" if not hasattr(element, '_parent'): raise ValueError('The top of the tree was reached without finding a {}' .format(cls)) parent = element._parent if not isinstance(...
Return a dict with lower - camelcase keys and non - None values..
def parse_options(**kwargs): """Return a dict with lower-camelcase keys and non-None values..""" return {camelize(key): value for key, value in kwargs.items() if value is not None}
Renders the HTML representation of the element.
def render(self, **kwargs): """Renders the HTML representation of the element.""" for item in self._parent._children.values(): if not isinstance(item, Layer) or not item.control: continue key = item.layer_name if not item.overlay: self....
Renders the HTML representation of the element.
def render(self, **kwargs): """Renders the HTML representation of the element.""" for name, child in self._children.items(): child.render(**kwargs) figure = self.get_root() assert isinstance(figure, Figure), ('You cannot render this Element ' ...
Validate the provided kwargs and return options as json string.
def parse_options(self, kwargs): """Validate the provided kwargs and return options as json string.""" kwargs = {camelize(key): value for key, value in kwargs.items()} for key in kwargs.keys(): assert key in self.valid_options, ( 'The option {} is not in the available...
Displays the HTML Map in a Jupyter notebook.
def _repr_html_(self, **kwargs): """Displays the HTML Map in a Jupyter notebook.""" if self._parent is None: self.add_to(Figure()) out = self._parent._repr_html_(**kwargs) self._parent = None else: out = self._parent._repr_html_(**kwargs) r...
Export the HTML to byte representation of a PNG image.
def _to_png(self, delay=3): """Export the HTML to byte representation of a PNG image. Uses selenium to render the HTML and record a PNG. You may need to adjust the `delay` time keyword argument if maps render without data or tiles. Examples -------- >>> m._to_png() ...
Renders the HTML representation of the element.
def render(self, **kwargs): """Renders the HTML representation of the element.""" figure = self.get_root() assert isinstance(figure, Figure), ('You cannot render this Element ' 'if it is not in a Figure.') # Set global switches figure....
Fit the map to contain a bounding box with the maximum zoom level possible.
def fit_bounds(self, bounds, padding_top_left=None, padding_bottom_right=None, padding=None, max_zoom=None): """Fit the map to contain a bounding box with the maximum zoom level possible. Parameters ---------- bounds: list of (latitude, longitude) points ...
Call the Choropleth class with the same arguments.
def choropleth(self, *args, **kwargs): """Call the Choropleth class with the same arguments. This method may be deleted after a year from now (Nov 2018). """ warnings.warn( 'The choropleth method has been deprecated. Instead use the new ' 'Choropleth class, whic...
Computes the bounds of the object itself ( not including it s children ) in the form [[ lat_min lon_min ] [ lat_max lon_max ]].
def _get_self_bounds(self): """ Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]]. """ if not self.embed: raise ValueError('Cannot compute bounds of non-embedded GeoJSON.') data = json...
Add object child to the first map and store it for the second.
def add_child(self, child, name=None, index=None): """Add object `child` to the first map and store it for the second.""" self.m1.add_child(child, name, index) if index is None: index = len(self.m2._children) self.children_for_m2.append((child, name, index))
Create a new multiprocess. Manager ( or return existing one ).
def start(authkey, queues, mode='local'): """Create a new multiprocess.Manager (or return existing one). Args: :authkey: string authorization key :queues: *INTERNAL_USE* :mode: 'local' indicates that the manager will only be accessible from the same host, otherwise remotely accessible. Returns: ...
Connect to a multiprocess. Manager.
def connect(address, authkey): """Connect to a multiprocess.Manager. Args: :address: unique address to the TFManager, either a unique connection string for 'local', or a (host, port) tuple for remote. :authkey: string authorization key Returns: A TFManager instance referencing the remote TFManager a...
Process a single XML file containing a bounding box.
def ProcessXMLAnnotation(xml_file): """Process a single XML file containing a bounding box.""" # pylint: disable=broad-except try: tree = ET.parse(xml_file) except Exception: print('Failed to parse: ' + xml_file, file=sys.stderr) return None # pylint: enable=broad-except root = tree.getroot() ...
Returns a python list of all ( sharded ) data subset files.
def data_files(self): """Returns a python list of all (sharded) data subset files. Returns: python list of all (sharded) data set files. Raises: ValueError: if there are not data_files matching the subset. """ tf_record_pattern = os.path.join(FLAGS.data_dir, '%s-*' % self.subset) da...
Helper to create summaries for activations.
def _activation_summary(x): """Helper to create summaries for activations. Creates a summary that provides a histogram of activations. Creates a summary that measures the sparsity of activations. Args: x: Tensor Returns: nothing """ # Remove 'tower_[0-9]/' from the name in case this is a multi-G...
Helper to create a Variable stored on CPU memory.
def _variable_on_cpu(name, shape, initializer): """Helper to create a Variable stored on CPU memory. Args: name: name of the variable shape: list of ints initializer: initializer for Variable Returns: Variable Tensor """ with tf.device('/cpu:0'): dtype = tf.float16 if FLAGS.use_fp16 else...
Helper to create an initialized Variable with weight decay.
def _variable_with_weight_decay(name, shape, stddev, wd): """Helper to create an initialized Variable with weight decay. Note that the Variable is initialized with a truncated normal distribution. A weight decay is added only if one is specified. Args: name: name of the variable shape: list of ints ...
Construct distorted input for CIFAR training using the Reader ops.
def distorted_inputs(): """Construct distorted input for CIFAR training using the Reader ops. Returns: images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. labels: Labels. 1D tensor of [batch_size] size. Raises: ValueError: If no data_dir """ if not FLAGS.data_dir: rais...
Build the CIFAR - 10 model.
def inference(images): """Build the CIFAR-10 model. Args: images: Images returned from distorted_inputs() or inputs(). Returns: Logits. """ # We instantiate all variables using tf.get_variable() instead of # tf.Variable() in order to share variables across multiple GPU training runs. # If we onl...
Add L2Loss to all the trainable variables.
def loss(logits, labels): """Add L2Loss to all the trainable variables. Add summary for "Loss" and "Loss/avg". Args: logits: Logits from inference(). labels: Labels from distorted_inputs or inputs(). 1-D tensor of shape [batch_size] Returns: Loss tensor of type float. """ # Calcula...
Add summaries for losses in CIFAR - 10 model.
def _add_loss_summaries(total_loss): """Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages ...
Train CIFAR - 10 model.
def train(total_loss, global_step): """Train CIFAR-10 model. Create an optimizer and apply to all trainable variables. Add moving average for all trainable variables. Args: total_loss: Total loss from loss(). global_step: Integer Variable counting the number of training steps processed. Return...
Adds a variable to the MODEL_VARIABLES collection.
def add_variable(var, restore=True): """Adds a variable to the MODEL_VARIABLES collection. Optionally it will add the variable to the VARIABLES_TO_RESTORE collection. Args: var: a variable. restore: whether the variable should be added to the VARIABLES_TO_RESTORE collection. """ collections...
Gets the list of variables filtered by scope and/ or suffix.
def get_variables(scope=None, suffix=None): """Gets the list of variables, filtered by scope and/or suffix. Args: scope: an optional scope for filtering the variables to return. suffix: an optional suffix for filtering the variables to return. Returns: a copied list of variables with scope and suffi...
Gets the variable uniquely identified by that name.
def get_unique_variable(name): """Gets the variable uniquely identified by that name. Args: name: a name that uniquely identifies the variable. Returns: a tensorflow variable. Raises: ValueError: if no variable uniquely identified by the name exists. """ candidates = tf.get_collection(tf.Grap...
Fix the variable device to colocate its ops.
def variable_device(device, name): """Fix the variable device to colocate its ops.""" if callable(device): var_name = tf.get_variable_scope().name + '/' + name var_def = tf.NodeDef(name=var_name, op='Variable') device = device(var_def) if device is None: device = '' return device
Returns the global step variable.
def global_step(device=''): """Returns the global step variable. Args: device: Optional device to place the variable. It can be an string or a function that is called to get the device for the variable. Returns: the tensor representing the global step variable. """ global_step_ref = tf.get_col...
Gets an existing variable with these parameters or creates a new one.
def variable(name, shape=None, dtype=tf.float32, initializer=None, regularizer=None, trainable=True, collections=None, device='', restore=True): """Gets an existing variable with these parameters or creates a new one. It also add itself to a group with its name. Args: name: the n...
Runs Eval once.
def _eval_once(saver, summary_writer, top_1_op, top_5_op, summary_op): """Runs Eval once. Args: saver: Saver. summary_writer: Summary writer. top_1_op: Top 1 op. top_5_op: Top 5 op. summary_op: Summary op. """ with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpo...
Evaluate model on Dataset for a number of steps.
def evaluate(dataset): """Evaluate model on Dataset for a number of steps.""" with tf.Graph().as_default(): # Get images and labels from the dataset. images, labels = image_processing.inputs(dataset) # Number of classes in the Dataset label set plus 1. # Label 0 is reserved for an (unused) backgrou...
mapPartitions function to run single - node inferencing from a checkpoint/ saved_model using the model s input/ output mappings.
def _run_model(iterator, args, tf_args): """mapPartitions function to run single-node inferencing from a checkpoint/saved_model, using the model's input/output mappings. Args: :iterator: input RDD partition iterator. :args: arguments for TFModel, in argparse format :tf_args: arguments for TensorFlow in...
Sets up environment for a single - node TF session.
def single_node_env(args): """Sets up environment for a single-node TF session. Args: :args: command line arguments as either argparse args or argv list """ # setup ARGV for the TF process if isinstance(args, list): sys.argv = args elif args.argv: sys.argv = args.argv # setup ENV for Had...
Utility function to read a meta_graph_def from disk.
def get_meta_graph_def(saved_model_dir, tag_set): """Utility function to read a meta_graph_def from disk. From `saved_model_cli.py <https://github.com/tensorflow/tensorflow/blob/8e0e8d41a3a8f2d4a6100c2ea1dc9d6c6c4ad382/tensorflow/python/tools/saved_model_cli.py#L186>`_ Args: :saved_model_dir: path to saved_...
Generator that yields batches of a DataFrame iterator.
def yield_batch(iterable, batch_size, num_tensors=1): """Generator that yields batches of a DataFrame iterator. Args: :iterable: Spark partition iterator. :batch_size: number of items to retrieve per invocation. :num_tensors: number of tensors (columns) expected in each item. Returns: An array o...
Trains a TensorFlow model and returns a TFModel instance with the same args/ params pointing to a checkpoint or saved_model on disk.
def _fit(self, dataset): """Trains a TensorFlow model and returns a TFModel instance with the same args/params pointing to a checkpoint or saved_model on disk. Args: :dataset: A Spark DataFrame with columns that will be mapped to TensorFlow tensors. Returns: A TFModel representing the trained ...
Transforms the input DataFrame by applying the _run_model () mapPartitions function.
def _transform(self, dataset): """Transforms the input DataFrame by applying the _run_model() mapPartitions function. Args: :dataset: A Spark DataFrame for TensorFlow inferencing. """ spark = SparkSession.builder.getOrCreate() # set a deterministic order for input/output columns (lexicograph...
Starts the TensorFlowOnSpark cluster and Runs the TensorFlow main function on the Spark executors
def run(sc, map_fun, tf_args, num_executors, num_ps, tensorboard=False, input_mode=InputMode.TENSORFLOW, log_dir=None, driver_ps_nodes=False, master_node=None, reservation_timeout=600, queues=['input', 'output', 'error'], eval_node=False): """Starts the TensorFlowOnSpark cluster and Runs the TensorFlo...
* For InputMode. SPARK only *. Feeds Spark RDD partitions into the TensorFlow worker nodes
def train(self, dataRDD, num_epochs=0, feed_timeout=600, qname='input'): """*For InputMode.SPARK only*. Feeds Spark RDD partitions into the TensorFlow worker nodes It is the responsibility of the TensorFlow "main" function to interpret the rows of the RDD. Since epochs are implemented via ``RDD.union()``...
* For InputMode. SPARK only *: Feeds Spark RDD partitions into the TensorFlow worker nodes and returns an RDD of results
def inference(self, dataRDD, feed_timeout=600, qname='input'): """*For InputMode.SPARK only*: Feeds Spark RDD partitions into the TensorFlow worker nodes and returns an RDD of results It is the responsibility of the TensorFlow "main" function to interpret the rows of the RDD and provide valid data for the outp...
Stops the distributed TensorFlow cluster.
def shutdown(self, ssc=None, grace_secs=0, timeout=259200): """Stops the distributed TensorFlow cluster. For InputMode.SPARK, this will be executed AFTER the `TFCluster.train()` or `TFCluster.inference()` method completes. For InputMode.TENSORFLOW, this will be executed IMMEDIATELY after `TFCluster.run()` ...
Wrapper for inserting int64 features into Example proto.
def _int64_feature(value): """Wrapper for inserting int64 features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
Wrapper for inserting float features into Example proto.
def _float_feature(value): """Wrapper for inserting float features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(float_list=tf.train.FloatList(value=value))
Build an Example proto for an example.
def _convert_to_example(filename, image_buffer, label, synset, human, bbox, height, width): """Build an Example proto for an example. Args: filename: string, path to an image file, e.g., '/path/to/example.JPG' image_buffer: string, JPEG encoding of RGB image label: integer, iden...
Process a single image file.
def _process_image(filename, coder): """Process a single image file. Args: filename: string, path to an image file e.g., '/path/to/example.JPG'. coder: instance of ImageCoder to provide TensorFlow image coding utils. Returns: image_buffer: string, JPEG encoding of RGB image. height: integer, imag...
Build a list of human - readable labels.
def _find_human_readable_labels(synsets, synset_to_human): """Build a list of human-readable labels. Args: synsets: list of strings; each string is a unique WordNet ID. synset_to_human: dict of synset to human labels, e.g., 'n02119022' --> 'red fox, Vulpes vulpes' Returns: List of human-readab...
Find the bounding boxes for a given image file.
def _find_image_bounding_boxes(filenames, image_to_bboxes): """Find the bounding boxes for a given image file. Args: filenames: list of strings; each string is a path to an image file. image_to_bboxes: dictionary mapping image file names to a list of bounding boxes. This list contains 0+ bounding box...
Process a complete data set and save it as a TFRecord.
def _process_dataset(name, directory, num_shards, synset_to_human, image_to_bboxes): """Process a complete data set and save it as a TFRecord. Args: name: string, unique identifier specifying the data set. directory: string, root path to the data set. num_shards: integer number of ...
Build lookup for synset to human - readable label.
def _build_synset_lookup(imagenet_metadata_file): """Build lookup for synset to human-readable label. Args: imagenet_metadata_file: string, path to file containing mapping from synset to human-readable label. Assumes each line of the file looks like: n02119247 black fox n021193...
Build a lookup from image file to bounding boxes.
def _build_bounding_box_lookup(bounding_box_file): """Build a lookup from image file to bounding boxes. Args: bounding_box_file: string, path to file with bounding boxes annotations. Assumes each line of the file looks like: n00007846_64193.JPEG,0.0060,0.2620,0.7545,0.9940 where each lin...
Model function for CNN.
def cnn_model_fn(features, labels, mode): """Model function for CNN.""" # Input Layer # Reshape X to 4-D tensor: [batch_size, width, height, channels] # MNIST images are 28x28 pixels, and have one color channel input_layer = tf.reshape(features["x"], [-1, 28, 28, 1]) # Convolutional Layer #1 # Computes 3...
Reads and parses examples from CIFAR10 data files.
def read_cifar10(filename_queue): """Reads and parses examples from CIFAR10 data files. Recommendation: if you want N-way read parallelism, call this function N times. This will give you N independent Readers reading different files & positions within those files, which will give better mixing of examples. ...
Construct a queued batch of images and labels.
def _generate_image_and_label_batch(image, label, min_queue_examples, batch_size, shuffle): """Construct a queued batch of images and labels. Args: image: 3-D Tensor of [height, width, 3] of type.float32. label: 1-D Tensor of type.int32 min_queue_examples: int32, min...
Construct distorted input for CIFAR training using the Reader ops.
def distorted_inputs(data_dir, batch_size): """Construct distorted input for CIFAR training using the Reader ops. Args: data_dir: Path to the CIFAR-10 data directory. batch_size: Number of images per batch. Returns: images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. label...
Construct input for CIFAR evaluation using the Reader ops.
def inputs(eval_data, data_dir, batch_size): """Construct input for CIFAR evaluation using the Reader ops. Args: eval_data: bool, indicating if one should use the train or eval data set. data_dir: Path to the CIFAR-10 data directory. batch_size: Number of images per batch. Returns: images: Image...
Save a Spark DataFrame as TFRecords.
def saveAsTFRecords(df, output_dir): """Save a Spark DataFrame as TFRecords. This will convert the DataFrame rows to TFRecords prior to saving. Args: :df: Spark DataFrame :output_dir: Path to save TFRecords """ tf_rdd = df.rdd.mapPartitions(toTFExample(df.dtypes)) tf_rdd.saveAsNewAPIHadoopFile(out...
Load TFRecords from disk into a Spark DataFrame.
def loadTFRecords(sc, input_dir, binary_features=[]): """Load TFRecords from disk into a Spark DataFrame. This will attempt to automatically convert the tf.train.Example features into Spark DataFrame columns of equivalent types. Note: TensorFlow represents both strings and binary types as tf.train.BytesList, an...
mapPartition function to convert a Spark RDD of Row into an RDD of serialized tf. train. Example bytestring.
def toTFExample(dtypes): """mapPartition function to convert a Spark RDD of Row into an RDD of serialized tf.train.Example bytestring. Note that tf.train.Example is a fairly flat structure with limited datatypes, e.g. tf.train.FloatList, tf.train.Int64List, and tf.train.BytesList, so most DataFrame types will be...
Given a tf. train. Example infer the Spark DataFrame schema ( StructFields ).
def infer_schema(example, binary_features=[]): """Given a tf.train.Example, infer the Spark DataFrame schema (StructFields). Note: TensorFlow represents both strings and binary types as tf.train.BytesList, and we need to disambiguate these types for Spark DataFrames DTypes (StringType and BinaryType), so we requ...
mapPartition function to convert an RDD of serialized tf. train. Example bytestring into an RDD of Row.
def fromTFExample(iter, binary_features=[]): """mapPartition function to convert an RDD of serialized tf.train.Example bytestring into an RDD of Row. Note: TensorFlow represents both strings and binary types as tf.train.BytesList, and we need to disambiguate these types for Spark DataFrames DTypes (StringType an...
Build an estimator appropriate for the given model type.
def build_estimator(model_dir, model_type, model_column_fn, inter_op, intra_op, ctx): """Build an estimator appropriate for the given model type.""" wide_columns, deep_columns = model_column_fn() hidden_units = [100, 75, 50, 25] # Create a tf.estimator.RunConfig to ensure the model is run on CPU, which # tra...
Construct all necessary functions and call run_loop.
def run_census(flags_obj, ctx): """Construct all necessary functions and call run_loop. Args: flags_obj: Object containing user specified flags. """ train_file = os.path.join(flags_obj.data_dir, census_dataset.TRAINING_FILE) test_file = os.path.join(flags_obj.data_dir, census_dataset.EVAL_FILE) # Trai...
Latest Inception from http:// arxiv. org/ abs/ 1512. 00567.
def inception_v3(inputs, dropout_keep_prob=0.8, num_classes=1000, is_training=True, restore_logits=True, scope=''): """Latest Inception from http://arxiv.org/abs/1512.00567. "Rethinking the Inception Architecture for Computer Vi...
Yields the scope with the default parameters for inception_v3.
def inception_v3_parameters(weight_decay=0.00004, stddev=0.1, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Yields the scope with the default parameters for inception_v3. Args: weight_decay: the weight decay for weights variables. stddev: standard deviation of the trunc...
Setup environment variables for Hadoop compatibility and GPU allocation
def single_node_env(num_gpus=1): """Setup environment variables for Hadoop compatibility and GPU allocation""" import tensorflow as tf # ensure expanded CLASSPATH w/o glob characters (required for Spark 2.1 + JNI) if 'HADOOP_PREFIX' in os.environ and 'TFOS_CLASSPATH_UPDATED' not in os.environ: classpath =...
Simple utility to get host IP address.
def get_ip_address(): """Simple utility to get host IP address.""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip_address = s.getsockname()[0] except socket_error as sockerr: if sockerr.errno != errno.ENETUNREACH: raise sockerr ip_address = socket...
Find a file in a given path string.
def find_in_path(path, file): """Find a file in a given path string.""" for p in path.split(os.pathsep): candidate = os.path.join(p, file) if os.path.exists(candidate) and os.path.isfile(candidate): return candidate return False
Define a L1 regularizer.
def l1_regularizer(weight=1.0, scope=None): """Define a L1 regularizer. Args: weight: scale the loss by this factor. scope: Optional scope for name_scope. Returns: a regularizer function. """ def regularizer(tensor): with tf.name_scope(scope, 'L1Regularizer', [tensor]): l1_weight = tf....
Define a L2 regularizer.
def l2_regularizer(weight=1.0, scope=None): """Define a L2 regularizer. Args: weight: scale the loss by this factor. scope: Optional scope for name_scope. Returns: a regularizer function. """ def regularizer(tensor): with tf.name_scope(scope, 'L2Regularizer', [tensor]): l2_weight = tf....
Define a L1L2 regularizer.
def l1_l2_regularizer(weight_l1=1.0, weight_l2=1.0, scope=None): """Define a L1L2 regularizer. Args: weight_l1: scale the L1 loss by this factor. weight_l2: scale the L2 loss by this factor. scope: Optional scope for name_scope. Returns: a regularizer function. """ def regularizer(tensor): ...
Define a L1Loss useful for regularize i. e. lasso.
def l1_loss(tensor, weight=1.0, scope=None): """Define a L1Loss, useful for regularize, i.e. lasso. Args: tensor: tensor to regularize. weight: scale the loss by this factor. scope: Optional scope for name_scope. Returns: the L1 loss op. """ with tf.name_scope(scope, 'L1Loss', [tensor]): ...
Define a L2Loss useful for regularize i. e. weight decay.
def l2_loss(tensor, weight=1.0, scope=None): """Define a L2Loss, useful for regularize, i.e. weight decay. Args: tensor: tensor to regularize. weight: an optional weight to modulate the loss. scope: Optional scope for name_scope. Returns: the L2 loss op. """ with tf.name_scope(scope, 'L2Loss...
Define a Cross Entropy loss using softmax_cross_entropy_with_logits.
def cross_entropy_loss(logits, one_hot_labels, label_smoothing=0, weight=1.0, scope=None): """Define a Cross Entropy loss using softmax_cross_entropy_with_logits. It can scale the loss by weight factor, and smooth the labels. Args: logits: [batch_size, num_classes] logits outputs of t...
Stores the default arguments for the given set of list_ops.
def arg_scope(list_ops_or_scope, **kwargs): """Stores the default arguments for the given set of list_ops. For usage, please see examples at top of the file. Args: list_ops_or_scope: List or tuple of operations to set argument scope for or a dictionary containg the current scope. When list_ops_or_scop...
Decorates a function with args so it can be used within an arg_scope.
def add_arg_scope(func): """Decorates a function with args so it can be used within an arg_scope. Args: func: function to decorate. Returns: A tuple with the decorated function func_with_args(). """ @functools.wraps(func) def func_with_args(*args, **kwargs): current_scope = _current_arg_scope(...
Returns this executor s singleton instance of the multiprocessing. Manager reconnecting per python - worker if needed.
def _get_manager(cluster_info, host, executor_id): """Returns this executor's "singleton" instance of the multiprocessing.Manager, reconnecting per python-worker if needed. Args: :cluster_info: cluster node reservations :host: host IP address :executor_id: unique id per executor (created during initial...
Wraps the user - provided TensorFlow main function in a Spark mapPartitions function.
def run(fn, tf_args, cluster_meta, tensorboard, log_dir, queues, background): """Wraps the user-provided TensorFlow main function in a Spark mapPartitions function. Args: :fn: TensorFlow "main" function provided by the user. :tf_args: ``argparse`` args, or command line ``ARGV``. These will be passed to th...
Feeds Spark partitions into the shared multiprocessing. Queue.
def train(cluster_info, cluster_meta, feed_timeout=600, qname='input'): """Feeds Spark partitions into the shared multiprocessing.Queue. Args: :cluster_info: node reservation information for the cluster (e.g. host, executor_id, pid, ports, etc) :cluster_meta: dictionary of cluster metadata (e.g. cluster_id...
Feeds Spark partitions into the shared multiprocessing. Queue and returns inference results.
def inference(cluster_info, feed_timeout=600, qname='input'): """Feeds Spark partitions into the shared multiprocessing.Queue and returns inference results. Args: :cluster_info: node reservation information for the cluster (e.g. host, executor_id, pid, ports, etc) :feed_timeout: number of seconds after whi...
Stops all TensorFlow nodes by feeding None into the multiprocessing. Queues.
def shutdown(cluster_info, queues=['input']): """Stops all TensorFlow nodes by feeding ``None`` into the multiprocessing.Queues. Args: :cluster_info: node reservation information for the cluster (e.g. host, executor_id, pid, ports, etc). :queues: *INTERNAL_USE* Returns: A nodeRDD.mapPartitions() fun...
Convenience function to access TFNode. start_cluster_server directly from this object instance.
def start_cluster_server(self, num_gpus=1, rdma=False): """Convenience function to access ``TFNode.start_cluster_server`` directly from this object instance.""" return TFNode.start_cluster_server(self, num_gpus, rdma)
Convenience function to access TFNode. export_saved_model directly from this object instance.
def export_saved_model(self, sess, export_dir, tag_set, signatures): """Convenience function to access ``TFNode.export_saved_model`` directly from this object instance.""" TFNode.export_saved_model(sess, export_dir, tag_set, signatures)
Convenience function to access TFNode. DataFeed directly from this object instance.
def get_data_feed(self, train_mode=True, qname_in='input', qname_out='output', input_mapping=None): """Convenience function to access ``TFNode.DataFeed`` directly from this object instance.""" return TFNode.DataFeed(self.mgr, train_mode, qname_in, qname_out, input_mapping)
Downloads data from url and makes changes to match the CSV format.
def _download_and_clean_file(filename, url): """Downloads data from url, and makes changes to match the CSV format.""" temp_file, _ = urllib.request.urlretrieve(url) with tf.gfile.Open(temp_file, 'r') as temp_eval_file: with tf.gfile.Open(filename, 'w') as eval_file: for line in temp_eval_file: ...
Download census data if it is not already present.
def download(data_dir): """Download census data if it is not already present.""" tf.gfile.MakeDirs(data_dir) training_file_path = os.path.join(data_dir, TRAINING_FILE) if not tf.gfile.Exists(training_file_path): _download_and_clean_file(training_file_path, TRAINING_URL) eval_file_path = os.path.join(dat...
Builds a set of wide and deep feature columns.
def build_model_columns(): """Builds a set of wide and deep feature columns.""" # Continuous variable columns age = tf.feature_column.numeric_column('age') education_num = tf.feature_column.numeric_column('education_num') capital_gain = tf.feature_column.numeric_column('capital_gain') capital_loss = tf.feat...
Generate an input function for the Estimator.
def input_fn(data_file, num_epochs, shuffle, batch_size): """Generate an input function for the Estimator.""" assert tf.gfile.Exists(data_file), ( '%s not found. Please make sure you have run census_dataset.py and ' 'set the --data_dir argument to the correct path.' % data_file) def parse_csv(value):...
Receive a message on sock.
def receive(self, sock): """Receive a message on ``sock``.""" msg = None data = b'' recv_done = False recv_len = -1 while not recv_done: buf = sock.recv(BUFSIZE) if buf is None or len(buf) == 0: raise Exception("socket closed") if recv_len == -1: recv_len = stru...
Send msg to destination sock.
def send(self, sock, msg): """Send ``msg`` to destination ``sock``.""" data = pickle.dumps(msg) buf = struct.pack('>I', len(data)) + data sock.sendall(buf)
Block until all reservations are received.
def await_reservations(self, sc, status={}, timeout=600): """Block until all reservations are received.""" timespent = 0 while not self.reservations.done(): logging.info("waiting for {0} reservations".format(self.reservations.remaining())) # check status flags for any errors if 'error' in ...
Start listener in a background thread
def start(self): """Start listener in a background thread Returns: address of the Server as a tuple of (host, port) """ server_sock = self.start_listening_socket() # hostname may not be resolvable but IP address probably will be host = self.get_server_ip() port = server_sock.getsockn...
Helper function to wrap msg w/ msg_type.
def _request(self, msg_type, msg_data=None): """Helper function to wrap msg w/ msg_type.""" msg = {} msg['type'] = msg_type if msg_data: msg['data'] = msg_data done = False tries = 0 while not done and tries < MAX_RETRIES: try: MessageSocket.send(self, self.sock, msg) ...