repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
sammchardy/python-binance
binance/websockets.py
BinanceSocketManager.close
def close(self): """Close all connections """ keys = set(self._conns.keys()) for key in keys: self.stop_socket(key) self._conns = {}
python
def close(self): """Close all connections """ keys = set(self._conns.keys()) for key in keys: self.stop_socket(key) self._conns = {}
[ "def", "close", "(", "self", ")", ":", "keys", "=", "set", "(", "self", ".", "_conns", ".", "keys", "(", ")", ")", "for", "key", "in", "keys", ":", "self", ".", "stop_socket", "(", "key", ")", "self", ".", "_conns", "=", "{", "}" ]
Close all connections
[ "Close", "all", "connections" ]
31c0d0a32f9edd528c6c2c1dd3044d9a34ce43cc
https://github.com/sammchardy/python-binance/blob/31c0d0a32f9edd528c6c2c1dd3044d9a34ce43cc/binance/websockets.py#L519-L527
train
python-visualization/folium
folium/plugins/heat_map_withtime.py
HeatMapWithTime._get_self_bounds
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]]. """ bounds = [[None, None], [None, None]] for point in self.data: bounds = [ [ ...
python
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]]. """ bounds = [[None, None], [None, None]] for point in self.data: bounds = [ [ ...
[ "def", "_get_self_bounds", "(", "self", ")", ":", "bounds", "=", "[", "[", "None", ",", "None", "]", ",", "[", "None", ",", "None", "]", "]", "for", "point", "in", "self", ".", "data", ":", "bounds", "=", "[", "[", "none_min", "(", "bounds", "[",...
Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]].
[ "Computes", "the", "bounds", "of", "the", "object", "itself", "(", "not", "including", "it", "s", "children", ")", "in", "the", "form", "[[", "lat_min", "lon_min", "]", "[", "lat_max", "lon_max", "]]", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/plugins/heat_map_withtime.py#L267-L285
train
python-visualization/folium
folium/vector_layers.py
path_options
def path_options(line=False, radius=False, **kwargs): """ 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 di...
python
def path_options(line=False, radius=False, **kwargs): """ 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 di...
[ "def", "path_options", "(", "line", "=", "False", ",", "radius", "=", "False", ",", "*", "*", "kwargs", ")", ":", "extra_options", "=", "{", "}", "if", "line", ":", "extra_options", "=", "{", "'smoothFactor'", ":", "kwargs", ".", "pop", "(", "'smooth_f...
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' ...
[ "Contains", "options", "and", "constants", "shared", "between", "vector", "overlays", "(", "Polygon", "Polyline", "Circle", "CircleMarker", "and", "Rectangle", ")", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/vector_layers.py#L16-L99
train
python-visualization/folium
folium/features.py
Vega.render
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=self, kwargs=kwargs)), name=self.get_name()) ...
python
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=self, kwargs=kwargs)), name=self.get_name()) ...
[ "def", "render", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "json", "=", "json", ".", "dumps", "(", "self", ".", "data", ")", "self", ".", "_parent", ".", "html", ".", "add_child", "(", "Element", "(", "Template", "(", "\"\"\"\n ...
Renders the HTML representation of the element.
[ "Renders", "the", "HTML", "representation", "of", "the", "element", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L147-L188
train
python-visualization/folium
folium/features.py
VegaLite.render
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()}}"></div> """).render(this=self, kwargs=kwa...
python
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()}}"></div> """).render(this=self, kwargs=kwa...
[ "def", "render", "(", "self", ",", "*", "*", "kwargs", ")", ":", "vegalite_major_version", "=", "self", ".", "_get_vegalite_major_versions", "(", "self", ".", "data", ")", "self", ".", "_parent", ".", "html", ".", "add_child", "(", "Element", "(", "Templat...
Renders the HTML representation of the element.
[ "Renders", "the", "HTML", "representation", "of", "the", "element", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L241-L271
train
python-visualization/folium
folium/features.py
GeoJson.process_data
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().startswith(('http:', 'ftp:', 'https:')): if not se...
python
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().startswith(('http:', 'ftp:', 'https:')): if not se...
[ "def", "process_data", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "self", ".", "embed", "=", "True", "return", "data", "elif", "isinstance", "(", "data", ",", "str", ")", ":", "if", "data", ".", "low...
Convert an unknown data input into a geojson dictionary.
[ "Convert", "an", "unknown", "data", "input", "into", "a", "geojson", "dictionary", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L469-L494
train
python-visualization/folium
folium/features.py
GeoJson.convert_to_feature_collection
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( 'Data is not a FeatureCollection, but it should be to apply ...
python
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( 'Data is not a FeatureCollection, but it should be to apply ...
[ "def", "convert_to_feature_collection", "(", "self", ")", ":", "if", "self", ".", "data", "[", "'type'", "]", "==", "'FeatureCollection'", ":", "return", "if", "not", "self", ".", "embed", ":", "raise", "ValueError", "(", "'Data is not a FeatureCollection, but it ...
Convert data into a FeatureCollection if it is not already.
[ "Convert", "data", "into", "a", "FeatureCollection", "if", "it", "is", "not", "already", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L496-L510
train
python-visualization/folium
folium/features.py
GeoJson._validate_function
def _validate_function(self, func, name): """ Tests `self.style_function` and `self.highlight_function` to ensure they are functions returning dictionaries. """ test_feature = self.data['features'][0] if not callable(func) or not isinstance(func(test_feature), dict): ...
python
def _validate_function(self, func, name): """ Tests `self.style_function` and `self.highlight_function` to ensure they are functions returning dictionaries. """ test_feature = self.data['features'][0] if not callable(func) or not isinstance(func(test_feature), dict): ...
[ "def", "_validate_function", "(", "self", ",", "func", ",", "name", ")", ":", "test_feature", "=", "self", ".", "data", "[", "'features'", "]", "[", "0", "]", "if", "not", "callable", "(", "func", ")", "or", "not", "isinstance", "(", "func", "(", "te...
Tests `self.style_function` and `self.highlight_function` to ensure they are functions returning dictionaries.
[ "Tests", "self", ".", "style_function", "and", "self", ".", "highlight_function", "to", "ensure", "they", "are", "functions", "returning", "dictionaries", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L512-L521
train
python-visualization/folium
folium/features.py
GeoJson.find_identifier
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 feat in features)) == n: return 'feature.id' ...
python
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 feat in features)) == n: return 'feature.id' ...
[ "def", "find_identifier", "(", "self", ")", ":", "features", "=", "self", ".", "data", "[", "'features'", "]", "n", "=", "len", "(", "features", ")", "feature", "=", "features", "[", "0", "]", "if", "'id'", "in", "feature", "and", "len", "(", "set", ...
Find a unique identifier for each feature, create it if needed.
[ "Find", "a", "unique", "identifier", "for", "each", "feature", "create", "it", "if", "needed", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L523-L541
train
python-visualization/folium
folium/features.py
GeoJsonStyleMapper._create_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.items(): if isinstance(va...
python
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.items(): if isinstance(va...
[ "def", "_create_mapping", "(", "self", ",", "func", ",", "switch", ")", ":", "mapping", "=", "{", "}", "for", "feature", "in", "self", ".", "data", "[", "'features'", "]", ":", "content", "=", "func", "(", "feature", ")", "if", "switch", "==", "'styl...
Internal function to create the mapping.
[ "Internal", "function", "to", "create", "the", "mapping", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L583-L600
train
python-visualization/folium
folium/features.py
GeoJsonStyleMapper.get_feature_id
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)
python
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)
[ "def", "get_feature_id", "(", "self", ",", "feature", ")", ":", "fields", "=", "self", ".", "feature_identifier", ".", "split", "(", "'.'", ")", "[", "1", ":", "]", "return", "functools", ".", "reduce", "(", "operator", ".", "getitem", ",", "fields", "...
Return a value identifying the feature.
[ "Return", "a", "value", "identifying", "the", "feature", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L602-L605
train
python-visualization/folium
folium/features.py
GeoJsonStyleMapper._to_key
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('}}"', '}}')
python
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('}}"', '}}')
[ "def", "_to_key", "(", "d", ")", ":", "as_str", "=", "json", ".", "dumps", "(", "d", ",", "sort_keys", "=", "True", ")", "return", "as_str", ".", "replace", "(", "'\"{{'", ",", "'{{'", ")", ".", "replace", "(", "'}}\"'", ",", "'}}'", ")" ]
Convert dict to str and enable Jinja2 template syntax.
[ "Convert", "dict", "to", "str", "and", "enable", "Jinja2", "template", "syntax", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L608-L611
train
python-visualization/folium
folium/features.py
GeoJsonStyleMapper._set_default_key
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['default'] = key_longest del (mapping[key_longest])
python
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['default'] = key_longest del (mapping[key_longest])
[ "def", "_set_default_key", "(", "mapping", ")", ":", "key_longest", "=", "sorted", "(", "[", "(", "len", "(", "v", ")", ",", "k", ")", "for", "k", ",", "v", "in", "mapping", ".", "items", "(", ")", "]", ",", "reverse", "=", "True", ")", "[", "0...
Replace the field with the most features with a 'default' field.
[ "Replace", "the", "field", "with", "the", "most", "features", "with", "a", "default", "field", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L614-L619
train
python-visualization/folium
folium/features.py
TopoJson.style_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: return data geometries = recursive_get(self.data, s...
python
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: return data geometries = recursive_get(self.data, s...
[ "def", "style_data", "(", "self", ")", ":", "def", "recursive_get", "(", "data", ",", "keys", ")", ":", "if", "len", "(", "keys", ")", ":", "return", "recursive_get", "(", "data", ".", "get", "(", "keys", "[", "0", "]", ")", ",", "keys", "[", "1"...
Applies self.style_function to each feature of self.data.
[ "Applies", "self", ".", "style_function", "to", "each", "feature", "of", "self", ".", "data", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L725-L736
train
python-visualization/folium
folium/features.py
TopoJson.get_bounds
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]] """ if not self.embed: raise ValueError('Cannot compute bounds of non-embedded TopoJSON.') xmin, xmax, ymin,...
python
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]] """ if not self.embed: raise ValueError('Cannot compute bounds of non-embedded TopoJSON.') xmin, xmax, ymin,...
[ "def", "get_bounds", "(", "self", ")", ":", "if", "not", "self", ".", "embed", ":", "raise", "ValueError", "(", "'Cannot compute bounds of non-embedded TopoJSON.'", ")", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "None", ",", "None", ",", "None", ...
Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]]
[ "Computes", "the", "bounds", "of", "the", "object", "itself", "(", "not", "including", "it", "s", "children", ")", "in", "the", "form", "[[", "lat_min", "lon_min", "]", "[", "lat_max", "lon_max", "]]" ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L751-L780
train
python-visualization/folium
folium/features.py
GeoJsonTooltip.warn_for_geometry_collections
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 not None else key for key, feature in enumerate(self._parent.data['feat...
python
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 not None else key for key, feature in enumerate(self._parent.data['feat...
[ "def", "warn_for_geometry_collections", "(", "self", ")", ":", "geom_collections", "=", "[", "feature", ".", "get", "(", "'properties'", ")", "if", "feature", ".", "get", "(", "'properties'", ")", "is", "not", "None", "else", "key", "for", "key", ",", "fea...
Checks for GeoJson GeometryCollection features to warn user about incompatibility.
[ "Checks", "for", "GeoJson", "GeometryCollection", "features", "to", "warn", "user", "about", "incompatibility", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L883-L894
train
python-visualization/folium
folium/features.py
GeoJsonTooltip.render
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() elif isinstance(self._parent, TopoJson): ...
python
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() elif isinstance(self._parent, TopoJson): ...
[ "def", "render", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "self", ".", "_parent", ",", "GeoJson", ")", ":", "keys", "=", "tuple", "(", "self", ".", "_parent", ".", "data", "[", "'features'", "]", "[", "0", "]", "["...
Renders the HTML representation of the element.
[ "Renders", "the", "HTML", "representation", "of", "the", "element", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L896-L912
train
python-visualization/folium
folium/features.py
Choropleth.render
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' ' to a Map object.')...
python
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' ' to a Map object.')...
[ "def", "render", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "color_scale", ":", "# ColorMap needs Map as its parent", "assert", "isinstance", "(", "self", ".", "_parent", ",", "Map", ")", ",", "(", "'Choropleth must be added'", "' to a ...
Render the GeoJson/TopoJson and color scale objects.
[ "Render", "the", "GeoJson", "/", "TopoJson", "and", "color", "scale", "objects", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L1146-L1154
train
python-visualization/folium
folium/utilities.py
validate_location
def validate_location(location): # noqa: C901 """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 a...
python
def validate_location(location): # noqa: C901 """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 a...
[ "def", "validate_location", "(", "location", ")", ":", "# noqa: C901", "if", "isinstance", "(", "location", ",", "np", ".", "ndarray", ")", "or", "(", "pd", "is", "not", "None", "and", "isinstance", "(", "location", ",", "pd", ".", "DataFrame", ")", ")",...
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", "a", "single", "lat", "/", "lon", "coordinate", "pair", "and", "convert", "to", "a", "list" ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L26-L66
train
python-visualization/folium
folium/utilities.py
validate_locations
def validate_locations(locations): """Validate an iterable with multiple lat/lon coordinate pairs. Returns ------- list[list[float, float]] or list[list[list[float, float]]] """ locations = if_pandas_df_convert_to_numpy(locations) try: iter(locations) except TypeError: ...
python
def validate_locations(locations): """Validate an iterable with multiple lat/lon coordinate pairs. Returns ------- list[list[float, float]] or list[list[list[float, float]]] """ locations = if_pandas_df_convert_to_numpy(locations) try: iter(locations) except TypeError: ...
[ "def", "validate_locations", "(", "locations", ")", ":", "locations", "=", "if_pandas_df_convert_to_numpy", "(", "locations", ")", "try", ":", "iter", "(", "locations", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "'Locations should be an iterable with ...
Validate an iterable with multiple lat/lon coordinate pairs. Returns ------- list[list[float, float]] or list[list[list[float, float]]]
[ "Validate", "an", "iterable", "with", "multiple", "lat", "/", "lon", "coordinate", "pairs", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L69-L94
train
python-visualization/folium
folium/utilities.py
if_pandas_df_convert_to_numpy
def if_pandas_df_convert_to_numpy(obj): """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. """ if pd is not None and isinstance(obj, pd.DataFrame): return obj.val...
python
def if_pandas_df_convert_to_numpy(obj): """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. """ if pd is not None and isinstance(obj, pd.DataFrame): return obj.val...
[ "def", "if_pandas_df_convert_to_numpy", "(", "obj", ")", ":", "if", "pd", "is", "not", "None", "and", "isinstance", "(", "obj", ",", "pd", ".", "DataFrame", ")", ":", "return", "obj", ".", "values", "else", ":", "return", "obj" ]
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.
[ "Return", "a", "Numpy", "array", "from", "a", "Pandas", "dataframe", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L97-L106
train
python-visualization/folium
folium/utilities.py
image_to_url
def image_to_url(image, colormap=None, origin='upper'): """ 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 ...
python
def image_to_url(image, colormap=None, origin='upper'): """ 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 ...
[ "def", "image_to_url", "(", "image", ",", "colormap", "=", "None", ",", "origin", "=", "'upper'", ")", ":", "if", "isinstance", "(", "image", ",", "str", ")", "and", "not", "_is_url", "(", "image", ")", ":", "fileformat", "=", "os", ".", "path", ".",...
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...
[ "Infers", "the", "type", "of", "an", "image", "argument", "and", "transforms", "it", "into", "a", "URL", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L109-L144
train
python-visualization/folium
folium/utilities.py
write_png
def write_png(data, origin='upper', colormap=None): """ 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') Insp...
python
def write_png(data, origin='upper', colormap=None): """ 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') Insp...
[ "def", "write_png", "(", "data", ",", "origin", "=", "'upper'", ",", "colormap", "=", "None", ")", ":", "if", "colormap", "is", "None", ":", "def", "colormap", "(", "x", ")", ":", "return", "(", "x", ",", "x", ",", "x", ",", "1", ")", "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-...
[ "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", ":" ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L155-L239
train
python-visualization/folium
folium/utilities.py
mercator_transform
def mercator_transform(data, lat_bounds, origin='upper', height_out=None): """ 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) ...
python
def mercator_transform(data, lat_bounds, origin='upper', height_out=None): """ 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) ...
[ "def", "mercator_transform", "(", "data", ",", "lat_bounds", ",", "origin", "=", "'upper'", ",", "height_out", "=", "None", ")", ":", "import", "numpy", "as", "np", "def", "mercator", "(", "x", ")", ":", "return", "np", ".", "arcsinh", "(", "np", ".", ...
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...
[ "Transforms", "an", "image", "computed", "in", "(", "longitude", "latitude", ")", "coordinates", "into", "the", "a", "Mercator", "projection", "image", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L242-L300
train
python-visualization/folium
folium/utilities.py
iter_coords
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...
python
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...
[ "def", "iter_coords", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "tuple", ",", "list", ")", ")", ":", "coords", "=", "obj", "elif", "'features'", "in", "obj", ":", "coords", "=", "[", "geom", "[", "'geometry'", "]", "[", "'coor...
Returns all the coordinate tuples from a geometry or feature.
[ "Returns", "all", "the", "coordinate", "tuples", "from", "a", "geometry", "or", "feature", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L321-L340
train
python-visualization/folium
folium/utilities.py
_locations_mirror
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...
python
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...
[ "def", "_locations_mirror", "(", "x", ")", ":", "if", "hasattr", "(", "x", ",", "'__iter__'", ")", ":", "if", "hasattr", "(", "x", "[", "0", "]", ",", "'__iter__'", ")", ":", "return", "list", "(", "map", "(", "_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]]
[ "Mirrors", "the", "points", "in", "a", "list", "-", "of", "-", "list", "-", "of", "-", "...", "-", "of", "-", "list", "-", "of", "-", "points", ".", "For", "example", ":", ">>>", "_locations_mirror", "(", "[[[", "1", "2", "]", "[", "3", "4", "]...
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L343-L357
train
python-visualization/folium
folium/utilities.py
get_bounds
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]), ...
python
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]), ...
[ "def", "get_bounds", "(", "locations", ",", "lonlat", "=", "False", ")", ":", "bounds", "=", "[", "[", "None", ",", "None", "]", ",", "[", "None", ",", "None", "]", "]", "for", "point", "in", "iter_coords", "(", "locations", ")", ":", "bounds", "="...
Computes the bounds of the object in the form [[lat_min, lon_min], [lat_max, lon_max]]
[ "Computes", "the", "bounds", "of", "the", "object", "in", "the", "form", "[[", "lat_min", "lon_min", "]", "[", "lat_max", "lon_max", "]]" ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L360-L380
train
python-visualization/folium
folium/utilities.py
camelize
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...
python
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...
[ "def", "camelize", "(", "key", ")", ":", "return", "''", ".", "join", "(", "x", ".", "capitalize", "(", ")", "if", "i", ">", "0", "else", "x", "for", "i", ",", "x", "in", "enumerate", "(", "key", ".", "split", "(", "'_'", ")", ")", ")" ]
Convert a python_style_variable_name to lowerCamelCase. Examples -------- >>> camelize('variable_name') 'variableName' >>> camelize('variableName') 'variableName'
[ "Convert", "a", "python_style_variable_name", "to", "lowerCamelCase", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L383-L394
train
python-visualization/folium
folium/utilities.py
normalize
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
python
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
[ "def", "normalize", "(", "rendered", ")", ":", "out", "=", "''", ".", "join", "(", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "rendered", ".", "splitlines", "(", ")", "if", "line", ".", "strip", "(", ")", "]", ")", "out", "=", "o...
Return the input string without non-functional spaces or newlines.
[ "Return", "the", "input", "string", "without", "non", "-", "functional", "spaces", "or", "newlines", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L440-L446
train
python-visualization/folium
folium/utilities.py
_tmp_html
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...
python
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...
[ "def", "_tmp_html", "(", "data", ")", ":", "filepath", "=", "''", "try", ":", "fid", ",", "filepath", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.html'", ",", "prefix", "=", "'folium_'", ")", "os", ".", "write", "(", "fid", ",", "data", ...
Yields the path of a temporary HTML file containing data.
[ "Yields", "the", "path", "of", "a", "temporary", "HTML", "file", "containing", "data", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L450-L460
train
python-visualization/folium
folium/utilities.py
deep_copy
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...
python
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...
[ "def", "deep_copy", "(", "item_original", ")", ":", "item", "=", "copy", ".", "copy", "(", "item_original", ")", "item", ".", "_id", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", "if", "hasattr", "(", "item", ",", "'_children'", ")", "and", "len",...
Return a recursive deep-copy of item where each copy has a new ID.
[ "Return", "a", "recursive", "deep", "-", "copy", "of", "item", "where", "each", "copy", "has", "a", "new", "ID", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L463-L474
train
python-visualization/folium
folium/utilities.py
get_obj_in_upper_tree
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(...
python
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(...
[ "def", "get_obj_in_upper_tree", "(", "element", ",", "cls", ")", ":", "if", "not", "hasattr", "(", "element", ",", "'_parent'", ")", ":", "raise", "ValueError", "(", "'The top of the tree was reached without finding a {}'", ".", "format", "(", "cls", ")", ")", "...
Return the first object in the parent tree of class `cls`.
[ "Return", "the", "first", "object", "in", "the", "parent", "tree", "of", "class", "cls", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L477-L485
train
python-visualization/folium
folium/utilities.py
parse_options
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}
python
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}
[ "def", "parse_options", "(", "*", "*", "kwargs", ")", ":", "return", "{", "camelize", "(", "key", ")", ":", "value", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", "if", "value", "is", "not", "None", "}" ]
Return a dict with lower-camelcase keys and non-None values..
[ "Return", "a", "dict", "with", "lower", "-", "camelcase", "keys", "and", "non", "-", "None", "values", ".." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L488-L492
train
python-visualization/folium
folium/map.py
LayerControl.render
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....
python
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....
[ "def", "render", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "item", "in", "self", ".", "_parent", ".", "_children", ".", "values", "(", ")", ":", "if", "not", "isinstance", "(", "item", ",", "Layer", ")", "or", "not", "item", ".", "co...
Renders the HTML representation of the element.
[ "Renders", "the", "HTML", "representation", "of", "the", "element", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/map.py#L148-L162
train
python-visualization/folium
folium/map.py
Popup.render
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 ' ...
python
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 ' ...
[ "def", "render", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "child", "in", "self", ".", "_children", ".", "items", "(", ")", ":", "child", ".", "render", "(", "*", "*", "kwargs", ")", "figure", "=", "self", ".", "get_root...
Renders the HTML representation of the element.
[ "Renders", "the", "HTML", "representation", "of", "the", "element", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/map.py#L354-L365
train
python-visualization/folium
folium/map.py
Tooltip.parse_options
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...
python
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...
[ "def", "parse_options", "(", "self", ",", "kwargs", ")", ":", "kwargs", "=", "{", "camelize", "(", "key", ")", ":", "value", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", "}", "for", "key", "in", "kwargs", ".", "keys", "(", ...
Validate the provided kwargs and return options as json string.
[ "Validate", "the", "provided", "kwargs", "and", "return", "options", "as", "json", "string", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/map.py#L424-L436
train
python-visualization/folium
folium/folium.py
Map._repr_html_
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...
python
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...
[ "def", "_repr_html_", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_parent", "is", "None", ":", "self", ".", "add_to", "(", "Figure", "(", ")", ")", "out", "=", "self", ".", "_parent", ".", "_repr_html_", "(", "*", "*", "kw...
Displays the HTML Map in a Jupyter notebook.
[ "Displays", "the", "HTML", "Map", "in", "a", "Jupyter", "notebook", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/folium.py#L288-L296
train
python-visualization/folium
folium/folium.py
Map._to_png
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() ...
python
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() ...
[ "def", "_to_png", "(", "self", ",", "delay", "=", "3", ")", ":", "if", "self", ".", "_png_image", "is", "None", ":", "from", "selenium", "import", "webdriver", "options", "=", "webdriver", ".", "firefox", ".", "options", ".", "Options", "(", ")", "opti...
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...
[ "Export", "the", "HTML", "to", "byte", "representation", "of", "a", "PNG", "image", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/folium.py#L298-L326
train
python-visualization/folium
folium/folium.py
Map.render
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....
python
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....
[ "def", "render", "(", "self", ",", "*", "*", "kwargs", ")", ":", "figure", "=", "self", ".", "get_root", "(", ")", "assert", "isinstance", "(", "figure", ",", "Figure", ")", ",", "(", "'You cannot render this Element '", "'if it is not in a Figure.'", ")", "...
Renders the HTML representation of the element.
[ "Renders", "the", "HTML", "representation", "of", "the", "element", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/folium.py#L336-L372
train
python-visualization/folium
folium/folium.py
Map.fit_bounds
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 ...
python
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 ...
[ "def", "fit_bounds", "(", "self", ",", "bounds", ",", "padding_top_left", "=", "None", ",", "padding_bottom_right", "=", "None", ",", "padding", "=", "None", ",", "max_zoom", "=", "None", ")", ":", "self", ".", "add_child", "(", "FitBounds", "(", "bounds",...
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...
[ "Fit", "the", "map", "to", "contain", "a", "bounding", "box", "with", "the", "maximum", "zoom", "level", "possible", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/folium.py#L374-L406
train
python-visualization/folium
folium/folium.py
Map.choropleth
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...
python
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...
[ "def", "choropleth", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "'The choropleth method has been deprecated. Instead use the new '", "'Choropleth class, which has the same arguments. See the example '", "'notebook \\'GeoJSON...
Call the Choropleth class with the same arguments. This method may be deleted after a year from now (Nov 2018).
[ "Call", "the", "Choropleth", "class", "with", "the", "same", "arguments", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/folium.py#L408-L420
train
python-visualization/folium
folium/plugins/timestamped_geo_json.py
TimestampedGeoJson._get_self_bounds
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...
python
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...
[ "def", "_get_self_bounds", "(", "self", ")", ":", "if", "not", "self", ".", "embed", ":", "raise", "ValueError", "(", "'Cannot compute bounds of non-embedded GeoJSON.'", ")", "data", "=", "json", ".", "loads", "(", "self", ".", "data", ")", "if", "'features'",...
Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]].
[ "Computes", "the", "bounds", "of", "the", "object", "itself", "(", "not", "including", "it", "s", "children", ")", "in", "the", "form", "[[", "lat_min", "lon_min", "]", "[", "lat_max", "lon_max", "]]", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/plugins/timestamped_geo_json.py#L213-L243
train
python-visualization/folium
folium/plugins/dual_map.py
DualMap.add_child
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))
python
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))
[ "def", "add_child", "(", "self", ",", "child", ",", "name", "=", "None", ",", "index", "=", "None", ")", ":", "self", ".", "m1", ".", "add_child", "(", "child", ",", "name", ",", "index", ")", "if", "index", "is", "None", ":", "index", "=", "len"...
Add object `child` to the first map and store it for the second.
[ "Add", "object", "child", "to", "the", "first", "map", "and", "store", "it", "for", "the", "second", "." ]
8595240517135d1637ca4cf7cc624045f1d911b3
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/plugins/dual_map.py#L83-L88
train
yahoo/TensorFlowOnSpark
tensorflowonspark/TFManager.py
start
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: ...
python
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: ...
[ "def", "start", "(", "authkey", ",", "queues", ",", "mode", "=", "'local'", ")", ":", "global", "mgr", ",", "qdict", ",", "kdict", "qdict", ".", "clear", "(", ")", "kdict", ".", "clear", "(", ")", "for", "q", "in", "queues", ":", "qdict", "[", "q...
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...
[ "Create", "a", "new", "multiprocess", ".", "Manager", "(", "or", "return", "existing", "one", ")", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/TFManager.py#L40-L65
train
yahoo/TensorFlowOnSpark
tensorflowonspark/TFManager.py
connect
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...
python
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...
[ "def", "connect", "(", "address", ",", "authkey", ")", ":", "TFManager", ".", "register", "(", "'get_queue'", ")", "TFManager", ".", "register", "(", "'get'", ")", "TFManager", ".", "register", "(", "'set'", ")", "m", "=", "TFManager", "(", "address", ",...
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.
[ "Connect", "to", "a", "multiprocess", ".", "Manager", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/TFManager.py#L68-L83
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/process_bounding_boxes.py
ProcessXMLAnnotation
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() ...
python
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() ...
[ "def", "ProcessXMLAnnotation", "(", "xml_file", ")", ":", "# pylint: disable=broad-except", "try", ":", "tree", "=", "ET", ".", "parse", "(", "xml_file", ")", "except", "Exception", ":", "print", "(", "'Failed to parse: '", "+", "xml_file", ",", "file", "=", "...
Process a single XML file containing a bounding box.
[ "Process", "a", "single", "XML", "file", "containing", "a", "bounding", "box", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/process_bounding_boxes.py#L119-L168
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/dataset.py
Dataset.data_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...
python
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...
[ "def", "data_files", "(", "self", ")", ":", "tf_record_pattern", "=", "os", ".", "path", ".", "join", "(", "FLAGS", ".", "data_dir", ",", "'%s-*'", "%", "self", ".", "subset", ")", "data_files", "=", "tf", ".", "gfile", ".", "Glob", "(", "tf_record_pat...
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.
[ "Returns", "a", "python", "list", "of", "all", "(", "sharded", ")", "data", "subset", "files", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/dataset.py#L76-L93
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10.py
_activation_summary
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...
python
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...
[ "def", "_activation_summary", "(", "x", ")", ":", "# Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training", "# session. This helps the clarity of presentation on tensorboard.", "tensor_name", "=", "re", ".", "sub", "(", "'%s_[0-9]*/'", "%", "TOWER_NAME", ",", ...
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
[ "Helper", "to", "create", "summaries", "for", "activations", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10.py#L79-L95
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10.py
_variable_on_cpu
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...
python
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...
[ "def", "_variable_on_cpu", "(", "name", ",", "shape", ",", "initializer", ")", ":", "with", "tf", ".", "device", "(", "'/cpu:0'", ")", ":", "dtype", "=", "tf", ".", "float16", "if", "FLAGS", ".", "use_fp16", "else", "tf", ".", "float32", "var", "=", ...
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
[ "Helper", "to", "create", "a", "Variable", "stored", "on", "CPU", "memory", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10.py#L98-L112
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10.py
_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 ...
python
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 ...
[ "def", "_variable_with_weight_decay", "(", "name", ",", "shape", ",", "stddev", ",", "wd", ")", ":", "dtype", "=", "tf", ".", "float16", "if", "FLAGS", ".", "use_fp16", "else", "tf", ".", "float32", "var", "=", "_variable_on_cpu", "(", "name", ",", "shap...
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...
[ "Helper", "to", "create", "an", "initialized", "Variable", "with", "weight", "decay", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10.py#L115-L139
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10.py
distorted_inputs
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...
python
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...
[ "def", "distorted_inputs", "(", ")", ":", "if", "not", "FLAGS", ".", "data_dir", ":", "raise", "ValueError", "(", "'Please supply a data_dir'", ")", "data_dir", "=", "os", ".", "path", ".", "join", "(", "FLAGS", ".", "data_dir", ",", "'cifar-10-batches-bin'", ...
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
[ "Construct", "distorted", "input", "for", "CIFAR", "training", "using", "the", "Reader", "ops", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10.py#L142-L160
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10.py
inference
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...
python
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...
[ "def", "inference", "(", "images", ")", ":", "# We instantiate all variables using tf.get_variable() instead of", "# tf.Variable() in order to share variables across multiple GPU training runs.", "# If we only ran this model on a single GPU, we could simplify this function", "# by replacing all in...
Build the CIFAR-10 model. Args: images: Images returned from distorted_inputs() or inputs(). Returns: Logits.
[ "Build", "the", "CIFAR", "-", "10", "model", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10.py#L188-L271
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10.py
loss
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...
python
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...
[ "def", "loss", "(", "logits", ",", "labels", ")", ":", "# Calculate the average cross entropy loss across the batch.", "labels", "=", "tf", ".", "cast", "(", "labels", ",", "tf", ".", "int64", ")", "cross_entropy", "=", "tf", ".", "nn", ".", "sparse_softmax_cros...
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.
[ "Add", "L2Loss", "to", "all", "the", "trainable", "variables", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10.py#L274-L295
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10.py
_add_loss_summaries
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 ...
python
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 ...
[ "def", "_add_loss_summaries", "(", "total_loss", ")", ":", "# Compute the moving average of all individual losses and the total loss.", "loss_averages", "=", "tf", ".", "train", ".", "ExponentialMovingAverage", "(", "0.9", ",", "name", "=", "'avg'", ")", "losses", "=", ...
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.
[ "Add", "summaries", "for", "losses", "in", "CIFAR", "-", "10", "model", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10.py#L298-L322
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10.py
train
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...
python
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...
[ "def", "train", "(", "total_loss", ",", "global_step", ")", ":", "# Variables that affect learning rate.", "num_batches_per_epoch", "=", "NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN", "/", "FLAGS", ".", "batch_size", "decay_steps", "=", "int", "(", "num_batches_per_epoch", "*", "NUM...
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.
[ "Train", "CIFAR", "-", "10", "model", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10.py#L325-L378
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/slim/variables.py
add_variable
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...
python
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...
[ "def", "add_variable", "(", "var", ",", "restore", "=", "True", ")", ":", "collections", "=", "[", "MODEL_VARIABLES", "]", "if", "restore", ":", "collections", ".", "append", "(", "VARIABLES_TO_RESTORE", ")", "for", "collection", "in", "collections", ":", "i...
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.
[ "Adds", "a", "variable", "to", "the", "MODEL_VARIABLES", "collection", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/slim/variables.py#L96-L111
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/slim/variables.py
get_variables
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...
python
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...
[ "def", "get_variables", "(", "scope", "=", "None", ",", "suffix", "=", "None", ")", ":", "candidates", "=", "tf", ".", "get_collection", "(", "MODEL_VARIABLES", ",", "scope", ")", "[", ":", "]", "if", "suffix", "is", "not", "None", ":", "candidates", "...
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.
[ "Gets", "the", "list", "of", "variables", "filtered", "by", "scope", "and", "/", "or", "suffix", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/slim/variables.py#L114-L127
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/slim/variables.py
get_unique_variable
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...
python
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...
[ "def", "get_unique_variable", "(", "name", ")", ":", "candidates", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ",", "name", ")", "if", "not", "candidates", ":", "raise", "ValueError", "(", "'Couldnt find variable %s'",...
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.
[ "Gets", "the", "variable", "uniquely", "identified", "by", "that", "name", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/slim/variables.py#L152-L171
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/slim/variables.py
variable_device
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
python
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
[ "def", "variable_device", "(", "device", ",", "name", ")", ":", "if", "callable", "(", "device", ")", ":", "var_name", "=", "tf", ".", "get_variable_scope", "(", ")", ".", "name", "+", "'/'", "+", "name", "var_def", "=", "tf", ".", "NodeDef", "(", "n...
Fix the variable device to colocate its ops.
[ "Fix", "the", "variable", "device", "to", "colocate", "its", "ops", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/slim/variables.py#L209-L217
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/slim/variables.py
global_step
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...
python
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...
[ "def", "global_step", "(", "device", "=", "''", ")", ":", "global_step_ref", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "GLOBAL_STEP", ")", "if", "global_step_ref", ":", "return", "global_step_ref", "[", "0", "]", "else", ":", "col...
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.
[ "Returns", "the", "global", "step", "variable", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/slim/variables.py#L221-L244
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/slim/variables.py
variable
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...
python
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...
[ "def", "variable", "(", "name", ",", "shape", "=", "None", ",", "dtype", "=", "tf", ".", "float32", ",", "initializer", "=", "None", ",", "regularizer", "=", "None", ",", "trainable", "=", "True", ",", "collections", "=", "None", ",", "device", "=", ...
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...
[ "Gets", "an", "existing", "variable", "with", "these", "parameters", "or", "creates", "a", "new", "one", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/slim/variables.py#L248-L289
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/inception_eval.py
_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...
python
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...
[ "def", "_eval_once", "(", "saver", ",", "summary_writer", ",", "top_1_op", ",", "top_5_op", ",", "summary_op", ")", ":", "with", "tf", ".", "Session", "(", ")", "as", "sess", ":", "ckpt", "=", "tf", ".", "train", ".", "get_checkpoint_state", "(", "FLAGS"...
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.
[ "Runs", "Eval", "once", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/inception_eval.py#L55-L128
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/inception_eval.py
evaluate
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...
python
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...
[ "def", "evaluate", "(", "dataset", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "# Get images and labels from the dataset.", "images", ",", "labels", "=", "image_processing", ".", "inputs", "(", "dataset", ")", "# Number of...
Evaluate model on Dataset for a number of steps.
[ "Evaluate", "model", "on", "Dataset", "for", "a", "number", "of", "steps", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/inception_eval.py#L131-L166
train
yahoo/TensorFlowOnSpark
tensorflowonspark/pipeline.py
_run_model
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...
python
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...
[ "def", "_run_model", "(", "iterator", ",", "args", ",", "tf_args", ")", ":", "single_node_env", "(", "tf_args", ")", "logging", ".", "info", "(", "\"===== input_mapping: {}\"", ".", "format", "(", "args", ".", "input_mapping", ")", ")", "logging", ".", "info...
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. ...
[ "mapPartitions", "function", "to", "run", "single", "-", "node", "inferencing", "from", "a", "checkpoint", "/", "saved_model", "using", "the", "model", "s", "input", "/", "output", "mappings", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/pipeline.py#L483-L564
train
yahoo/TensorFlowOnSpark
tensorflowonspark/pipeline.py
single_node_env
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...
python
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...
[ "def", "single_node_env", "(", "args", ")", ":", "# setup ARGV for the TF process", "if", "isinstance", "(", "args", ",", "list", ")", ":", "sys", ".", "argv", "=", "args", "elif", "args", ".", "argv", ":", "sys", ".", "argv", "=", "args", ".", "argv", ...
Sets up environment for a single-node TF session. Args: :args: command line arguments as either argparse args or argv list
[ "Sets", "up", "environment", "for", "a", "single", "-", "node", "TF", "session", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/pipeline.py#L567-L581
train
yahoo/TensorFlowOnSpark
tensorflowonspark/pipeline.py
get_meta_graph_def
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_...
python
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_...
[ "def", "get_meta_graph_def", "(", "saved_model_dir", ",", "tag_set", ")", ":", "saved_model", "=", "reader", ".", "read_saved_model", "(", "saved_model_dir", ")", "set_of_tags", "=", "set", "(", "tag_set", ".", "split", "(", "','", ")", ")", "for", "meta_graph...
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...
[ "Utility", "function", "to", "read", "a", "meta_graph_def", "from", "disk", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/pipeline.py#L584-L601
train
yahoo/TensorFlowOnSpark
tensorflowonspark/pipeline.py
yield_batch
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...
python
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...
[ "def", "yield_batch", "(", "iterable", ",", "batch_size", ",", "num_tensors", "=", "1", ")", ":", "tensors", "=", "[", "[", "]", "for", "i", "in", "range", "(", "num_tensors", ")", "]", "for", "item", "in", "iterable", ":", "if", "item", "is", "None"...
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`
[ "Generator", "that", "yields", "batches", "of", "a", "DataFrame", "iterator", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/pipeline.py#L604-L626
train
yahoo/TensorFlowOnSpark
tensorflowonspark/pipeline.py
TFEstimator._fit
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 ...
python
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 ...
[ "def", "_fit", "(", "self", ",", "dataset", ")", ":", "sc", "=", "SparkContext", ".", "getOrCreate", "(", ")", "logging", ".", "info", "(", "\"===== 1. train args: {0}\"", ".", "format", "(", "self", ".", "args", ")", ")", "logging", ".", "info", "(", ...
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...
[ "Trains", "a", "TensorFlow", "model", "and", "returns", "a", "TFModel", "instance", "with", "the", "same", "args", "/", "params", "pointing", "to", "a", "checkpoint", "or", "saved_model", "on", "disk", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/pipeline.py#L368-L420
train
yahoo/TensorFlowOnSpark
tensorflowonspark/pipeline.py
TFModel._transform
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...
python
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...
[ "def", "_transform", "(", "self", ",", "dataset", ")", ":", "spark", "=", "SparkSession", ".", "builder", ".", "getOrCreate", "(", ")", "# set a deterministic order for input/output columns (lexicographic by key)", "input_cols", "=", "[", "col", "for", "col", ",", "...
Transforms the input DataFrame by applying the _run_model() mapPartitions function. Args: :dataset: A Spark DataFrame for TensorFlow inferencing.
[ "Transforms", "the", "input", "DataFrame", "by", "applying", "the", "_run_model", "()", "mapPartitions", "function", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/pipeline.py#L448-L475
train
yahoo/TensorFlowOnSpark
tensorflowonspark/TFCluster.py
run
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...
python
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...
[ "def", "run", "(", "sc", ",", "map_fun", ",", "tf_args", ",", "num_executors", ",", "num_ps", ",", "tensorboard", "=", "False", ",", "input_mode", "=", "InputMode", ".", "TENSORFLOW", ",", "log_dir", "=", "None", ",", "driver_ps_nodes", "=", "False", ",", ...
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...
[ "Starts", "the", "TensorFlowOnSpark", "cluster", "and", "Runs", "the", "TensorFlow", "main", "function", "on", "the", "Spark", "executors" ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/TFCluster.py#L211-L379
train
yahoo/TensorFlowOnSpark
tensorflowonspark/TFCluster.py
TFCluster.train
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()``...
python
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()``...
[ "def", "train", "(", "self", ",", "dataRDD", ",", "num_epochs", "=", "0", ",", "feed_timeout", "=", "600", ",", "qname", "=", "'input'", ")", ":", "logging", ".", "info", "(", "\"Feeding training data\"", ")", "assert", "self", ".", "input_mode", "==", "...
*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" ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/TFCluster.py#L61-L92
train
yahoo/TensorFlowOnSpark
tensorflowonspark/TFCluster.py
TFCluster.inference
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...
python
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...
[ "def", "inference", "(", "self", ",", "dataRDD", ",", "feed_timeout", "=", "600", ",", "qname", "=", "'input'", ")", ":", "logging", ".", "info", "(", "\"Feeding inference data\"", ")", "assert", "self", ".", "input_mode", "==", "InputMode", ".", "SPARK", ...
*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...
[ "*", "For", "InputMode", ".", "SPARK", "only", "*", ":", "Feeds", "Spark", "RDD", "partitions", "into", "the", "TensorFlow", "worker", "nodes", "and", "returns", "an", "RDD", "of", "results" ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/TFCluster.py#L94-L113
train
yahoo/TensorFlowOnSpark
tensorflowonspark/TFCluster.py
TFCluster.shutdown
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()` ...
python
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()` ...
[ "def", "shutdown", "(", "self", ",", "ssc", "=", "None", ",", "grace_secs", "=", "0", ",", "timeout", "=", "259200", ")", ":", "logging", ".", "info", "(", "\"Stopping TensorFlow nodes\"", ")", "# identify ps/workers", "ps_list", ",", "worker_list", ",", "ev...
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: ...
[ "Stops", "the", "distributed", "TensorFlow", "cluster", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/TFCluster.py#L115-L201
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/build_imagenet_data.py
_int64_feature
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))
python
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))
[ "def", "_int64_feature", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "value", "]", "return", "tf", ".", "train", ".", "Feature", "(", "int64_list", "=", "tf", ".", "train", ".", "Int64Lis...
Wrapper for inserting int64 features into Example proto.
[ "Wrapper", "for", "inserting", "int64", "features", "into", "Example", "proto", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/build_imagenet_data.py#L158-L162
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/build_imagenet_data.py
_float_feature
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))
python
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))
[ "def", "_float_feature", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "value", "]", "return", "tf", ".", "train", ".", "Feature", "(", "float_list", "=", "tf", ".", "train", ".", "FloatLis...
Wrapper for inserting float features into Example proto.
[ "Wrapper", "for", "inserting", "float", "features", "into", "Example", "proto", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/build_imagenet_data.py#L165-L169
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/build_imagenet_data.py
_convert_to_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...
python
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...
[ "def", "_convert_to_example", "(", "filename", ",", "image_buffer", ",", "label", ",", "synset", ",", "human", ",", "bbox", ",", "height", ",", "width", ")", ":", "xmin", "=", "[", "]", "ymin", "=", "[", "]", "xmax", "=", "[", "]", "ymax", "=", "["...
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'...
[ "Build", "an", "Example", "proto", "for", "an", "example", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/build_imagenet_data.py#L177-L225
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/build_imagenet_data.py
_process_image
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...
python
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...
[ "def", "_process_image", "(", "filename", ",", "coder", ")", ":", "# Read the image file.", "with", "tf", ".", "gfile", ".", "FastGFile", "(", "filename", ",", "'r'", ")", "as", "f", ":", "image_data", "=", "f", ".", "read", "(", ")", "# Clean the dirty da...
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...
[ "Process", "a", "single", "image", "file", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/build_imagenet_data.py#L304-L338
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/build_imagenet_data.py
_find_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...
python
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...
[ "def", "_find_human_readable_labels", "(", "synsets", ",", "synset_to_human", ")", ":", "humans", "=", "[", "]", "for", "s", "in", "synsets", ":", "assert", "s", "in", "synset_to_human", ",", "(", "'Failed to find: %s'", "%", "s", ")", "humans", ".", "append...
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.
[ "Build", "a", "list", "of", "human", "-", "readable", "labels", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/build_imagenet_data.py#L540-L555
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/build_imagenet_data.py
_find_image_bounding_boxes
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...
python
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...
[ "def", "_find_image_bounding_boxes", "(", "filenames", ",", "image_to_bboxes", ")", ":", "num_image_bbox", "=", "0", "bboxes", "=", "[", "]", "for", "f", "in", "filenames", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "f", ")", "if", "b...
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...
[ "Find", "the", "bounding", "boxes", "for", "a", "given", "image", "file", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/build_imagenet_data.py#L558-L581
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/build_imagenet_data.py
_process_dataset
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 ...
python
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 ...
[ "def", "_process_dataset", "(", "name", ",", "directory", ",", "num_shards", ",", "synset_to_human", ",", "image_to_bboxes", ")", ":", "filenames", ",", "synsets", ",", "labels", "=", "_find_image_files", "(", "directory", ",", "FLAGS", ".", "labels_file", ")", ...
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...
[ "Process", "a", "complete", "data", "set", "and", "save", "it", "as", "a", "TFRecord", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/build_imagenet_data.py#L584-L601
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/build_imagenet_data.py
_build_synset_lookup
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...
python
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...
[ "def", "_build_synset_lookup", "(", "imagenet_metadata_file", ")", ":", "lines", "=", "tf", ".", "gfile", ".", "FastGFile", "(", "imagenet_metadata_file", ",", "'r'", ")", ".", "readlines", "(", ")", "synset_to_human", "=", "{", "}", "for", "l", "in", "lines...
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", "lookup", "for", "synset", "to", "human", "-", "readable", "label", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/build_imagenet_data.py#L604-L633
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/data/build_imagenet_data.py
_build_bounding_box_lookup
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...
python
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...
[ "def", "_build_bounding_box_lookup", "(", "bounding_box_file", ")", ":", "lines", "=", "tf", ".", "gfile", ".", "FastGFile", "(", "bounding_box_file", ",", "'r'", ")", ".", "readlines", "(", ")", "images_to_bboxes", "=", "{", "}", "num_bbox", "=", "0", "num_...
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 ...
[ "Build", "a", "lookup", "from", "image", "file", "to", "bounding", "boxes", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/data/build_imagenet_data.py#L636-L681
train
yahoo/TensorFlowOnSpark
examples/mnist/estimator/mnist_estimator.py
cnn_model_fn
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...
python
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...
[ "def", "cnn_model_fn", "(", "features", ",", "labels", ",", "mode", ")", ":", "# 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", "(", "feat...
Model function for CNN.
[ "Model", "function", "for", "CNN", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/mnist/estimator/mnist_estimator.py#L26-L115
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10_input.py
read_cifar10
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. ...
python
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. ...
[ "def", "read_cifar10", "(", "filename_queue", ")", ":", "class", "CIFAR10Record", "(", "object", ")", ":", "pass", "result", "=", "CIFAR10Record", "(", ")", "# Dimensions of the images in the CIFAR-10 dataset.", "# See http://www.cs.toronto.edu/~kriz/cifar.html for a descriptio...
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...
[ "Reads", "and", "parses", "examples", "from", "CIFAR10", "data", "files", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10_input.py#L38-L98
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10_input.py
_generate_image_and_label_batch
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...
python
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...
[ "def", "_generate_image_and_label_batch", "(", "image", ",", "label", ",", "min_queue_examples", ",", "batch_size", ",", "shuffle", ")", ":", "# Create a queue that shuffles the examples, and then", "# read 'batch_size' images + labels from the example queue.", "num_preprocess_thread...
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", "a", "queued", "batch", "of", "images", "and", "labels", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10_input.py#L101-L137
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10_input.py
distorted_inputs
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...
python
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...
[ "def", "distorted_inputs", "(", "data_dir", ",", "batch_size", ")", ":", "filenames", "=", "[", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'data_batch_%d.bin'", "%", "i", ")", "for", "i", "in", "xrange", "(", "1", ",", "6", ")", "]", "for...
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.
[ "Construct", "distorted", "input", "for", "CIFAR", "training", "using", "the", "Reader", "ops", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10_input.py#L140-L200
train
yahoo/TensorFlowOnSpark
examples/cifar10/cifar10_input.py
inputs
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...
python
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...
[ "def", "inputs", "(", "eval_data", ",", "data_dir", ",", "batch_size", ")", ":", "if", "not", "eval_data", ":", "filenames", "=", "[", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'data_batch_%d.bin'", "%", "i", ")", "for", "i", "in", "xrange...
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...
[ "Construct", "input", "for", "CIFAR", "evaluation", "using", "the", "Reader", "ops", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10_input.py#L203-L257
train
yahoo/TensorFlowOnSpark
tensorflowonspark/dfutil.py
saveAsTFRecords
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...
python
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...
[ "def", "saveAsTFRecords", "(", "df", ",", "output_dir", ")", ":", "tf_rdd", "=", "df", ".", "rdd", ".", "mapPartitions", "(", "toTFExample", "(", "df", ".", "dtypes", ")", ")", "tf_rdd", ".", "saveAsNewAPIHadoopFile", "(", "output_dir", ",", "\"org.tensorflo...
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
[ "Save", "a", "Spark", "DataFrame", "as", "TFRecords", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/dfutil.py#L29-L41
train
yahoo/TensorFlowOnSpark
tensorflowonspark/dfutil.py
loadTFRecords
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...
python
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...
[ "def", "loadTFRecords", "(", "sc", ",", "input_dir", ",", "binary_features", "=", "[", "]", ")", ":", "import", "tensorflow", "as", "tf", "tfr_rdd", "=", "sc", ".", "newAPIHadoopFile", "(", "input_dir", ",", "\"org.tensorflow.hadoop.io.TFRecordFileInputFormat\"", ...
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...
[ "Load", "TFRecords", "from", "disk", "into", "a", "Spark", "DataFrame", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/dfutil.py#L44-L81
train
yahoo/TensorFlowOnSpark
tensorflowonspark/dfutil.py
toTFExample
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...
python
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...
[ "def", "toTFExample", "(", "dtypes", ")", ":", "def", "_toTFExample", "(", "iter", ")", ":", "# supported type mappings between DataFrame.dtypes and tf.train.Feature types", "float_dtypes", "=", "[", "'float'", ",", "'double'", "]", "int64_dtypes", "=", "[", "'boolean'"...
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...
[ "mapPartition", "function", "to", "convert", "a", "Spark", "RDD", "of", "Row", "into", "an", "RDD", "of", "serialized", "tf", ".", "train", ".", "Example", "bytestring", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/dfutil.py#L84-L131
train
yahoo/TensorFlowOnSpark
tensorflowonspark/dfutil.py
infer_schema
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...
python
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...
[ "def", "infer_schema", "(", "example", ",", "binary_features", "=", "[", "]", ")", ":", "def", "_infer_sql_type", "(", "k", ",", "v", ")", ":", "# special handling for binary features", "if", "k", "in", "binary_features", ":", "return", "BinaryType", "(", ")",...
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...
[ "Given", "a", "tf", ".", "train", ".", "Example", "infer", "the", "Spark", "DataFrame", "schema", "(", "StructFields", ")", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/dfutil.py#L134-L168
train
yahoo/TensorFlowOnSpark
tensorflowonspark/dfutil.py
fromTFExample
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...
python
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...
[ "def", "fromTFExample", "(", "iter", ",", "binary_features", "=", "[", "]", ")", ":", "# convert from protobuf-like dict to DataFrame-friendly dict", "def", "_get_value", "(", "k", ",", "v", ")", ":", "if", "v", ".", "int64_list", ".", "value", ":", "result", ...
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...
[ "mapPartition", "function", "to", "convert", "an", "RDD", "of", "serialized", "tf", ".", "train", ".", "Example", "bytestring", "into", "an", "RDD", "of", "Row", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/dfutil.py#L171-L212
train
yahoo/TensorFlowOnSpark
examples/wide_deep/census_main.py
build_estimator
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...
python
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...
[ "def", "build_estimator", "(", "model_dir", ",", "model_type", ",", "model_column_fn", ",", "inter_op", ",", "intra_op", ",", "ctx", ")", ":", "wide_columns", ",", "deep_columns", "=", "model_column_fn", "(", ")", "hidden_units", "=", "[", "100", ",", "75", ...
Build an estimator appropriate for the given model type.
[ "Build", "an", "estimator", "appropriate", "for", "the", "given", "model", "type", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/wide_deep/census_main.py#L46-L77
train
yahoo/TensorFlowOnSpark
examples/wide_deep/census_main.py
run_census
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...
python
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...
[ "def", "run_census", "(", "flags_obj", ",", "ctx", ")", ":", "train_file", "=", "os", ".", "path", ".", "join", "(", "flags_obj", ".", "data_dir", ",", "census_dataset", ".", "TRAINING_FILE", ")", "test_file", "=", "os", ".", "path", ".", "join", "(", ...
Construct all necessary functions and call run_loop. Args: flags_obj: Object containing user specified flags.
[ "Construct", "all", "necessary", "functions", "and", "call", "run_loop", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/wide_deep/census_main.py#L80-L122
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/slim/inception_model.py
inception_v3
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...
python
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...
[ "def", "inception_v3", "(", "inputs", ",", "dropout_keep_prob", "=", "0.8", ",", "num_classes", "=", "1000", ",", "is_training", "=", "True", ",", "restore_logits", "=", "True", ",", "scope", "=", "''", ")", ":", "# end_points will collect relevant activations for...
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...
[ "Latest", "Inception", "from", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "00567", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/slim/inception_model.py#L52-L330
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/slim/inception_model.py
inception_v3_parameters
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...
python
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...
[ "def", "inception_v3_parameters", "(", "weight_decay", "=", "0.00004", ",", "stddev", "=", "0.1", ",", "batch_norm_decay", "=", "0.9997", ",", "batch_norm_epsilon", "=", "0.001", ")", ":", "# Set weight_decay for weights in Conv and FC layers.", "with", "scopes", ".", ...
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 ...
[ "Yields", "the", "scope", "with", "the", "default", "parameters", "for", "inception_v3", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/slim/inception_model.py#L333-L356
train
yahoo/TensorFlowOnSpark
tensorflowonspark/util.py
single_node_env
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 =...
python
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 =...
[ "def", "single_node_env", "(", "num_gpus", "=", "1", ")", ":", "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"...
Setup environment variables for Hadoop compatibility and GPU allocation
[ "Setup", "environment", "variables", "for", "Hadoop", "compatibility", "and", "GPU", "allocation" ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/util.py#L19-L38
train
yahoo/TensorFlowOnSpark
tensorflowonspark/util.py
get_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...
python
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...
[ "def", "get_ip_address", "(", ")", ":", "try", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "s", ".", "connect", "(", "(", "\"8.8.8.8\"", ",", "80", ")", ")", "ip_address", "=", "s", ...
Simple utility to get host IP address.
[ "Simple", "utility", "to", "get", "host", "IP", "address", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/util.py#L41-L54
train
yahoo/TensorFlowOnSpark
tensorflowonspark/util.py
find_in_path
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
python
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
[ "def", "find_in_path", "(", "path", ",", "file", ")", ":", "for", "p", "in", "path", ".", "split", "(", "os", ".", "pathsep", ")", ":", "candidate", "=", "os", ".", "path", ".", "join", "(", "p", ",", "file", ")", "if", "os", ".", "path", ".", ...
Find a file in a given path string.
[ "Find", "a", "file", "in", "a", "given", "path", "string", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/util.py#L57-L63
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/slim/losses.py
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....
python
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....
[ "def", "l1_regularizer", "(", "weight", "=", "1.0", ",", "scope", "=", "None", ")", ":", "def", "regularizer", "(", "tensor", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'L1Regularizer'", ",", "[", "tensor", "]", ")", ":", "l1_weight...
Define a L1 regularizer. Args: weight: scale the loss by this factor. scope: Optional scope for name_scope. Returns: a regularizer function.
[ "Define", "a", "L1", "regularizer", "." ]
5e4b6c185ab722fd0104ede0377e1149ea8d6f7c
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/slim/losses.py#L37-L53
train