text stringlengths 81 112k |
|---|
Close all connections
def close(self):
"""Close all connections
"""
keys = set(self._conns.keys())
for key in keys:
self.stop_socket(key)
self._conns = {} |
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]].
... |
Contains options and constants shared between vector overlays
(Polygon, Polyline, Circle, CircleMarker, and Rectangle).
Parameters
----------
stroke: Bool, True
Whether to draw stroke along the path.
Set it to false to disable borders on polygons or circles.
color: str, '#3388ff'
... |
Renders the HTML representation of the element.
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
self.json = json.dumps(self.data)
self._parent.html.add_child(Element(Template("""
<div id="{{this.get_name()}}"></div>
""").render(this=sel... |
Renders the HTML representation of the element.
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
vegalite_major_version = self._get_vegalite_major_versions(self.data)
self._parent.html.add_child(Element(Template("""
<div id="{{this.get_name()}}"></d... |
Convert an unknown data input into a geojson dictionary.
def process_data(self, data):
"""Convert an unknown data input into a geojson dictionary."""
if isinstance(data, dict):
self.embed = True
return data
elif isinstance(data, str):
if data.lower().startswi... |
Convert data into a FeatureCollection if it is not already.
def convert_to_feature_collection(self):
"""Convert data into a FeatureCollection if it is not already."""
if self.data['type'] == 'FeatureCollection':
return
if not self.embed:
raise ValueError(
... |
Tests `self.style_function` and `self.highlight_function` to ensure
they are functions returning dictionaries.
def _validate_function(self, func, name):
"""
Tests `self.style_function` and `self.highlight_function` to ensure
they are functions returning dictionaries.
"""
... |
Find a unique identifier for each feature, create it if needed.
def find_identifier(self):
"""Find a unique identifier for each feature, create it if needed."""
features = self.data['features']
n = len(features)
feature = features[0]
if 'id' in feature and len(set(feat['id'] for... |
Internal function to create the mapping.
def _create_mapping(self, func, switch):
"""Internal function to create the mapping."""
mapping = {}
for feature in self.data['features']:
content = func(feature)
if switch == 'style':
for key, value in content.ite... |
Return a value identifying the feature.
def get_feature_id(self, feature):
"""Return a value identifying the feature."""
fields = self.feature_identifier.split('.')[1:]
return functools.reduce(operator.getitem, fields, feature) |
Convert dict to str and enable Jinja2 template syntax.
def _to_key(d):
"""Convert dict to str and enable Jinja2 template syntax."""
as_str = json.dumps(d, sort_keys=True)
return as_str.replace('"{{', '{{').replace('}}"', '}}') |
Replace the field with the most features with a 'default' field.
def _set_default_key(mapping):
"""Replace the field with the most features with a 'default' field."""
key_longest = sorted([(len(v), k) for k, v in mapping.items()],
reverse=True)[0][1]
mapping['defaul... |
Applies self.style_function to each feature of self.data.
def style_data(self):
"""Applies self.style_function to each feature of self.data."""
def recursive_get(data, keys):
if len(keys):
return recursive_get(data.get(keys[0]), keys[1:])
else:
r... |
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_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]]
"""
... |
Checks for GeoJson GeometryCollection features to warn user about incompatibility.
def warn_for_geometry_collections(self):
"""Checks for GeoJson GeometryCollection features to warn user about incompatibility."""
geom_collections = [
feature.get('properties') if feature.get('properties') is... |
Renders the HTML representation of the element.
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
if isinstance(self._parent, GeoJson):
keys = tuple(self._parent.data['features'][0]['properties'].keys())
self.warn_for_geometry_collections()
... |
Render the GeoJson/TopoJson and color scale objects.
def render(self, **kwargs):
"""Render the GeoJson/TopoJson and color scale objects."""
if self.color_scale:
# ColorMap needs Map as its parent
assert isinstance(self._parent, Map), ('Choropleth must be added'
... |
Validate a single lat/lon coordinate pair and convert to a list
Validate that location:
* is a sized variable
* with size 2
* allows indexing (i.e. has an ordering)
* where both values are floats (or convertible to float)
* and both values are not NaN
Returns
-------
list[float, fl... |
Validate an iterable with multiple lat/lon coordinate pairs.
Returns
-------
list[list[float, float]] or list[list[list[float, float]]]
def validate_locations(locations):
"""Validate an iterable with multiple lat/lon coordinate pairs.
Returns
-------
list[list[float, float]] or list[list[... |
Return a Numpy array from a Pandas dataframe.
Iterating over a DataFrame has weird side effects, such as the first
row being the column names. Converting to Numpy is more safe.
def if_pandas_df_convert_to_numpy(obj):
"""Return a Numpy array from a Pandas dataframe.
Iterating over a DataFrame has weir... |
Infers the type of an image argument and transforms it into a URL.
Parameters
----------
image: string, file or array-like object
* If string, it will be written directly in the output file.
* If file, it's content will be converted as embedded in the
output file.
* If arr... |
Transform an array of data into a PNG string.
This can be written to disk using binary I/O, or encoded using base64
for an inline PNG like this:
>>> png_str = write_png(array)
>>> "data:image/png;base64,"+png_str.encode('base64')
Inspired from
https://stackoverflow.com/questions/902761/saving-... |
Transforms an image computed in (longitude,latitude) coordinates into
the a Mercator projection image.
Parameters
----------
data: numpy array or equivalent list-like object.
Must be NxM (mono), NxMx3 (RGB) or NxMx4 (RGBA)
lat_bounds : length 2 tuple
Minimal and maximal value of t... |
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 ob... |
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_m... |
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(loca... |
Convert a python_style_variable_name to lowerCamelCase.
Examples
--------
>>> camelize('variable_name')
'variableName'
>>> camelize('variableName')
'variableName'
def camelize(key):
"""Convert a python_style_variable_name to lowerCamelCase.
Examples
--------
>>> camelize('vari... |
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(', ', ... |
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)
... |
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:
childr... |
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 {}'
.form... |
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
... |
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 rende... |
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_... |
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 ... |
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()
>>> m._to_png(time=10) # Wait 10 s... |
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.... |
Fit the map to contain a bounding box with the
maximum zoom level possible.
Parameters
----------
bounds: list of (latitude, longitude) points
Bounding box specified as two points [southwest, northeast]
padding_top_left: (x, y) point, default None
Padding... |
Call the Choropleth class with the same arguments.
This method may be deleted after a year from now (Nov 2018).
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).
"""
warning... |
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]].
... |
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)
s... |
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:
A TFManager instance, which is also cached in l... |
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 at the supplied address.
def connect... |
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
# ... |
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.
def data_files(self):
"""Returns a python list of all (sharded) data subset files.
Returns:
python lis... |
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
def _activation_summary(x):
"""Helper to create summaries for activations.
Creates a summary that ... |
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
def _variable_on_cpu(name, shape, initializer):
"""Helper to create a Variable stored on CPU memory.
Args:
name: name of t... |
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
stddev: standard deviation of a truncated Gaussian
wd: ad... |
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
def distorted_inputs():
"""Construct distorted input for CIFAR tr... |
Build the CIFAR-10 model.
Args:
images: Images returned from distorted_inputs() or inputs().
Returns:
Logits.
def inference(images):
"""Build the CIFAR-10 model.
Args:
images: Images returned from distorted_inputs() or inputs().
Returns:
Logits.
"""
# We instantiate all variables usin... |
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.
def loss(logits, labels):
"""Add L2Loss to al... |
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 of losses.
def _add_loss_summaries(total_... |
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.
Returns:
train_op: op for training.
def tr... |
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.
def add_variable(var, restore=True):
"""Adds a variable to ... |
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 suffix.
def get_variables(scope=None, suffix=None):
... |
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.
def get_unique_variable(name):
"""Gets the variable uniquely identified by that... |
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:
... |
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.
def global_step(device=''):
"""Returns the global step variable.
... |
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 name of the new or existing variable.
shape: shape of the new or existing variable.
dtype: type of the new or existing variable (defaults to `DT_FLOAT`).
initializer... |
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.
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... |
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.
... |
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 inferencing code, in argparse or ARGV format.
... |
Sets up environment for a single-node TF session.
Args:
:args: command line arguments as either argparse args or argv list
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 th... |
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_model.
:tag_set: list of string tags identifying th... |
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 of ``num_tensors`` arrays, each of length `batch_size`
def ... |
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 model, backed on disk by a Tenso... |
Transforms the input DataFrame by applying the _run_model() mapPartitions function.
Args:
:dataset: A Spark DataFrame for TensorFlow inferencing.
def _transform(self, dataset):
"""Transforms the input DataFrame by applying the _run_model() mapPartitions function.
Args:
:dataset: A Spark DataF... |
Starts the TensorFlowOnSpark cluster and Runs the TensorFlow "main" function on the Spark executors
Args:
:sc: SparkContext
:map_fun: user-supplied TensorFlow "main" function
:tf_args: ``argparse`` args, or command-line ``ARGV``. These will be passed to the ``map_fun``.
:num_executors: number of Spa... |
*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()`` and the entire RDD must generally be processed in full, it is recommended
t... |
*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 output RDD.
This will use the distributed TensorFlow cluster for infe... |
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()` and will wait until the TF worker nodes complete.
Args:
... |
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.
Args:
filename: string, path to an image file, e.g., '/path/to/example.JPG'
image_buffer: string, JPEG encoding of RGB image
label: integer, identifier for the ground truth for the network
synset: string, unique WordNet ID specifying the label, e.g., 'n02323233'... |
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, image height in pixels.
width: integer, im... |
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-readable strings corresponding to each synset.
def _find_human_readab... |
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 boxes.
Returns:
List of bounding boxes for each image. Note th... |
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 shards for this data set.
synset_to_human: dict of synset to human labels, e.g.,
'n02119022' --> 'red... |
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
n02119359 silver fox
n02119477 red fox, Vulpes f... |
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 line corresponds to one bounding box annotation associated
... |
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])
# Convolutiona... |
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.
Args:
filename_queue: A queue of... |
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, minimum number of samples to retain
in the queue that provides of batches of examples.
batch_size: Number of images per batch.... |
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.
labels: Labels. 1D tensor of [batch_size] size.
def d... |
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: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZ... |
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
def saveAsTFRecords(df, output_dir):
"""Save a Spark DataFrame as TFRecords.
This will convert the DataFrame rows to TFRecords prior ... |
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, and we need to
disambiguate these types for Spark DataFrame... |
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 coerced into one of these typ... |
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 require a "hint"
from the caller in the ``binary_featu... |
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 and BinaryType), so we require a "hint"
from the c... |
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.... |
Construct all necessary functions and call run_loop.
Args:
flags_obj: Object containing user specified flags.
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... |
Latest Inception from http://arxiv.org/abs/1512.00567.
"Rethinking the Inception Architecture for Computer Vision"
Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens,
Zbigniew Wojna
Args:
inputs: a tensor of size [batch_size, height, width, channels].
dropout_keep_prob: dropout... |
Yields the scope with the default parameters for inception_v3.
Args:
weight_decay: the weight decay for weights variables.
stddev: standard deviation of the truncated guassian weight distribution.
batch_norm_decay: decay for the moving average of batch_norm momentums.
batch_norm_epsilon: small float ... |
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.... |
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:
... |
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.
Args:
weight: scale the loss by this factor.
scope: Optional scope for name_scope.
Returns:
a regularizer function.
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.