text
stringlengths
81
112k
Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d box and whiskers plot, and returns the resulting Plot object. The function x as SArray of dtype str and y as SArray of dtype: int, float. Parameters ---------- x : SArray The data to plot on the X axis of the b...
Plots a columnwise summary of the sframe provided as input, and returns the resulting Plot object. The function supports SFrames. Parameters ---------- sf : SFrame The data to get a columnwise summary for. Returns ------- out : Plot A :class: Plot object that is t...
Plots a histogram of the sarray provided as input, and returns the resulting Plot object. The function supports numeric SArrays with dtypes int or float. Parameters ---------- sa : SArray The data to get a histogram for. Must be numeric (int/float). xlabel : str (optional) The...
Plots an item frequency of the sarray provided as input, and returns the resulting Plot object. The function supports SArrays with dtype str. Parameters ---------- sa : SArray The data to get an item frequency for. Must have dtype str xlabel : str (optional) The text label for...
Parses the input file and returns C code and corresponding header file. def Parse(factory, file): """ Parses the input file and returns C code and corresponding header file. """ entities = [] while 1: # Just gets the whole struct nicely formatted data = GetNextStruct(file) ...
Creates the name inside an enumeration for distinguishing data types. def EntryTagName(self, entry): """Creates the name inside an enumeration for distinguishing data types.""" name = "%s_%s" % (self._name, entry.Name()) return name.upper()
Takes an array, add indentation to each entry and prints it. def PrintIndented(self, file, ident, code): """Takes an array, add indentation to each entry and prints it.""" for entry in code: print >>file, '%s%s' % (ident, entry)
Prints the tag definitions for a structure. def PrintTags(self, file): """Prints the tag definitions for a structure.""" print >>file, '/* Tag definition for %s */' % self._name print >>file, 'enum %s_ {' % self._name.lower() for entry in self._entries: print >>file, ' %s=%...
Builtin approximate quantile aggregator for groupby. Accepts as an argument, one or more of a list of quantiles to query. For instance: To extract the median >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', 0.5)}) To extract a few quantiles >>> sf.groupby(...
Compute the K-core decomposition of the graph. Return a model object with total number of cores as well as the core id for each vertex in the graph. Parameters ---------- graph : SGraph The graph on which to compute the k-core decomposition. kmin : int, optional Minimum core id. Ve...
Raise an error if an option is not supported. def raise_error_unsupported_categorical_option(option_name, option_value, layer_type, layer_name): """ Raise an error if an option is not supported. """ raise RuntimeError("Unsupported option %s=%s in layer %s(%s)" % (option_name, option_value, laye...
Given a list of class labels and a list of output_features, validate the list and return a valid version of output_features with all the correct data type information included. def process_or_validate_classifier_output_features( output_features, class_labels, supports_class_scores = True): """ ...
Puts features into a standard form from a number of different possible forms. The standard form is a list of 2-tuples of (name, datatype) pairs. The name is a string and the datatype is an object as defined in the _datatype module. The possible input forms are as follows: * A list of strings. in t...
Performs python-side bootstrapping of Boost.Build/Python. This function arranges for 'b2.whatever' package names to work, while also allowing to put python files alongside corresponding jam modules. def bootstrap(root_path): """Performs python-side bootstrapping of Boost.Build/Python. This function a...
The main function of the utility def main(): """The main function of the utility""" parser = argparse.ArgumentParser( description='Manage the build environment of Boost.Metaparse' ) parser.add_argument( '--dep_json', required=True, help='The json file describing the depe...
Outputs the last `num` elements that were appended either by `append` or `append_multiple`. Returns ------- out : list def read_history(self, num=10, segment=0): """ Outputs the last `num` elements that were appended either by `append` or `append_multiple`. ...
Specifies the flags (variables) that must be set on targets under certain conditions, described by arguments. rule_or_module: If contains dot, should be a rule name. The flags will be applied when that rule is used to set up build actions. ...
Returns the first element of 'property-sets' which is a subset of 'properties', or an empty list if no such element exists. def find_satisfied_condition(conditions, ps): """Returns the first element of 'property-sets' which is a subset of 'properties', or an empty list if no such element exists.""" ass...
Brings all flag definitions from the 'base' toolset into the 'toolset' toolset. Flag definitions whose conditions make use of properties in 'prohibited-properties' are ignored. Don't confuse property and feature, for example <debug-symbols>on and <debug-symbols>off, so blocking one of them does not bloc...
Given a rule name and a property set, returns a list of tuples of variables names and values, which must be set on targets for that rule/properties combination. def __set_target_variables_aux (manager, rule_or_module, ps): """ Given a rule name and a property set, returns a list of tuples of ...
Adds a new flag setting with the specified values. Does no checking. def __add_flag (rule_or_module, variable_name, condition, values): """ Adds a new flag setting with the specified values. Does no checking. """ assert isinstance(rule_or_module, basestring) assert isinstance(variable_n...
Convert a Logistic Regression model to the protobuf spec. Parameters ---------- model: LogisticRegression A trained LogisticRegression model. feature_names: [str], optional (default=None) Name of the input columns. target: str, optional (default=None) Name of the output col...
If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged. def root (path, root): """ If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged. """ if os.path.isabs (path): return path else: return os.path.join (root, path)
Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted. Args: path (str): the path to reverse Returns: the string of the reversed path Example: >>> p1 = 'path/to/somewhere' >>> p2 = reverse('path/to/somewhere') >>>...
Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain "." or ".." elements. Each slash separated element of pattern can contain the following special char...
Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain '.' or '..' elements. Each slash separated element of pattern can contain the following special char...
Recursive version of GLOB. Builds the glob of files while also searching in the subdirectories of the given roots. An optional set of exclusion patterns will filter out the matching entries from the result. The exclusions also apply to the subdirectory scanning, such that directories that match the ...
Recursive version of GLOB which glob sall parent directories of dir until the first match is found. Returns an empty result if no match is found def glob_in_parents(dir, patterns, upper_limit=None): """Recursive version of GLOB which glob sall parent directories of dir until the first match is found. R...
Recursively walks each thing in val, opening lists and dictionaries, converting all occurrences of UnityGraphProxy to an SGraph, UnitySFrameProxy to SFrame, and UnitySArrayProxy to SArray. def _wrap_function_return(val): """ Recursively walks each thing in val, opening lists and dictionaries, conve...
A setattr wrapper call used only by _publish(). This ensures that anything published into this module is also published into tc.extensions def _setattr_wrapper(mod, key, value): """ A setattr wrapper call used only by _publish(). This ensures that anything published into this module is also published i...
Dispatches arguments to a toolkit function. Parameters ---------- fnname : string The toolkit function to run arguments : list[string] The list of all the arguments the function takes. args : list The arguments that were passed kwargs : dictionary The keyword ...
class_name is of the form modA.modB.modC.class module_path splits on "." and the import_path is then ['modA','modB','modC'] the __import__ call is really annoying but essentially it reads like: import class from modA.modB.modC - Then the module variable points to modC - Then you get the class from...
Look for the class in .extensions in case it has already been imported (perhaps as a builtin extensions hard compiled into unity_server). def _create_class_instance(class_name, _proxy): """ Look for the class in .extensions in case it has already been imported (perhaps as a builtin extensions hard comp...
Publishes all functions and classes registered in unity_server. The functions and classes will appear in the module turicreate.extensions def _publish(): import copy """ Publishes all functions and classes registered in unity_server. The functions and classes will appear in the module turicreate.e...
Loads a turicreate toolkit module (a shared library) into the tc.extensions namespace. Toolkit module created via SDK can either be directly imported, e.g. ``import example`` or via this function, e.g. ``turicreate.ext_import("example.so")``. Use ``ext_import`` when you need more namespace control, or ...
Given a toolkit function name, return the argument list def _get_argument_list_from_toolkit_function_name(fn): """ Given a toolkit function name, return the argument list """ unity = _get_unity() fnprops = unity.describe_toolkit_function(fn) argnames = fnprops['arguments'] return argnames
Given a globals dictionary, and a name of the form "a.b.c.d", recursively walk the globals expanding caller_globals['a']['b']['c']['d'] returning the result. Raises an exception (IndexError) on failure. def _descend_namespace(caller_globals, name): """ Given a globals dictionary, and a name of the form...
If fn can be interpreted and handled as a native function: i.e. fn is one of the extensions, or fn is a simple lambda closure using one of the extensions. fn = tc.extensions.add fn = lambda x: tc.extensions.add(5) Then, this returns a closure object, which describes the function call whi...
We have to see if fullname refers to a module we can import. Some care is needed here because: import xxx # tries to load xxx.so from any of the python import paths import aaa.bbb.xxx # tries to load aaa/bbb/xxx.so from any of the python import paths def find_module(self, fullname, submodule...
Print lines of input along with output. def main(): """ Print lines of input along with output. """ source_lines = (line.rstrip() for line in sys.stdin) console = InteractiveInterpreter() console.runsource('import turicreate') source = '' try: while True: source = so...
Returns a type checker for a message field of the specified types. Args: field: FieldDescriptor object for this field. Returns: An instance of TypeChecker which can be used to verify the types of values assigned to a field of the specified type. def GetTypeChecker(field): """Returns a type checker ...
Type check the provided value and return it. The returned value might have been normalized to another type. def CheckValue(self, proposed_value): """Type check the provided value and return it. The returned value might have been normalized to another type. """ if not isinstance(proposed_value, se...
Generate executable python source code from an ast node. :param ast: ast node :param file: file to write output to. def python_source(ast, file=sys.stdout): ''' Generate executable python source code from an ast node. :param ast: ast node :param file: file to write output to. ...
Escape a bytes string for use in an ascii protocol buffer. text.encode('string_escape') does not seem to satisfy our needs as it encodes unprintable characters using two-digit hex escapes whereas our C++ unescaping function allows hex escapes to be any length. So, "\0011".encode('string_escape') ends up being...
Unescape a text string with C-style escape sequences to UTF-8 bytes. def CUnescape(text): """Unescape a text string with C-style escape sequences to UTF-8 bytes.""" def ReplaceHex(m): # Only replace the match if the number of leading back slashes is odd. i.e. # the slash itself is not escaped. if len(...
Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. def reset (): """ Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. """ global ...
Registers a target type, possibly derived from a 'base-type'. If 'suffixes' are provided, they list all the suffixes that mean a file is of 'type'. Also, the first element gives the suffix to be used when constructing and object of 'type'. type: a string suffixes: None or a seque...
Specifies that targets with suffix from 'suffixes' have the type 'type'. If a different type is already specified for any of syffixes, issues an error. def register_suffixes (suffixes, type): """ Specifies that targets with suffix from 'suffixes' have the type 'type'. If a different type is already...
Sets a scanner class that will be used for this 'type'. def set_scanner (type, scanner): """ Sets a scanner class that will be used for this 'type'. """ if __debug__: from .scanner import Scanner assert isinstance(type, basestring) assert issubclass(scanner, Scanner) validate (t...
Returns a scanner instance appropriate to 'type' and 'property_set'. def get_scanner (type, prop_set): """ Returns a scanner instance appropriate to 'type' and 'property_set'. """ if __debug__: from .property_set import PropertySet assert isinstance(type, basestring) assert isinstan...
Returns type and all of its bases, in the order of their distance from type. def all_bases (type): """ Returns type and all of its bases, in the order of their distance from type. """ assert isinstance(type, basestring) result = [] while type: result.append (type) type = __types [ty...
Returns type and all classes that derive from it, in the order of their distance from type. def all_derived (type): """ Returns type and all classes that derive from it, in the order of their distance from type. """ assert isinstance(type, basestring) result = [type] for d in __types [type]['derive...
Returns true if 'type' is 'base' or has 'base' as its direct or indirect base. def is_derived (type, base): """ Returns true if 'type' is 'base' or has 'base' as its direct or indirect base. """ assert isinstance(type, basestring) assert isinstance(base, basestring) # TODO: this isn't very efficien...
Same as is_derived. Should be removed. def is_subtype (type, base): """ Same as is_derived. Should be removed. """ assert isinstance(type, basestring) assert isinstance(base, basestring) # TODO: remove this method return is_derived (type, base)
Sets a target suffix that should be used when generating target of 'type' with the specified properties. Can be called with empty properties if no suffix for 'type' was specified yet. This does not automatically specify that files 'suffix' have 'type' --- two different types can use the ...
Change the suffix previously registered for this type/properties combination. If suffix is not yet specified, sets it. def change_generated_target_suffix (type, properties, suffix): """ Change the suffix previously registered for this type/properties combination. If suffix is not yet specified, set...
Returns suffix that should be used when generating target of 'type', with the specified properties. If not suffix were specified for 'type', returns suffix for base type, if any. def generated_target_ps(is_suffix, type, prop_set): """ Returns suffix that should be used when generating target of 'ty...
Returns file type given it's name. If there are several dots in filename, tries each suffix. E.g. for name of "file.so.1.2" suffixes "2", "1", and "so" will be tried. def type(filename): """ Returns file type given it's name. If there are several dots in filename, tries each suffix. E.g. f...
Register the given type on the specified OSes, or on remaining OSes if os is not specified. This rule is injected into each of the type modules for the sake of convenience. def register_type (type, suffixes, base_type = None, os = []): """ Register the given type on the specified OSes, or on remai...
keys of kwargs must be the names passed to __init__(...) as `column_names` def print_row(self, **kwargs): ''' keys of kwargs must be the names passed to __init__(...) as `column_names` ''' meta_string = '|' for key in self.column_names: float_specifier = '' ...
Parameters ---------- features : list[str] | str | None, optional Column names of features to be transformed. If None, all columns are selected. If string, that column is transformed. If list of strings, this list of column names is selected. exclude : list[str] | str | None, option...
Pretty print a list to be readable. def pretty_print_list(lst, name = 'features', repr_format=True): """ Pretty print a list to be readable. """ if not lst or len(lst) < 8: if repr_format: return lst.__repr__() else: return ', '.join(map(str, lst)) else: ...
Get the keras layer name from the activation name. def _get_elementwise_name_from_keras_layer(keras_layer): """ Get the keras layer name from the activation name. """ mode = keras_layer.mode if mode == 'sum': return 'ADD' elif mode == 'mul': return 'MULTIPLY' elif mode == 'c...
Test if a 3D (H,W,C) matrix x has the same element in each (H,W) matrix for each channel def _same_elements_per_channel(x): """ Test if a 3D (H,W,C) matrix x has the same element in each (H,W) matrix for each channel """ eps = 1e-5 dims = x.shape for c in range(dims[-1]): xc = x[:,:,c]....
Convert a dense layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_dense(builder, layer, input_names, output_names, keras_layer): """Convert a dense layer from keras ...
Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_activation(builder, layer, input_names, output_names, keras_layer): """Convert an activation ...
Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_padding(builder, layer, input_names, output_names, ke...
Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_cropping(builder, layer, input_names, output_names, k...
Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_upsample(builder, layer, input_names, output_names, keras_layer): """Convert convolution layer ...
Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_convolution(builder, layer, input_names, output_names, keras_layer): """Convert convolution lay...
Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_convolution1d(builder, layer, input_names, output_names, keras_layer): """Convert convolution l...
Convert an LSTM layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_lstm(builder, layer, input_names, output_names, keras_layer): """Convert an LSTM layer from keras t...
Convert an SimpleRNN layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_simple_rnn(builder, layer, input_names, output_names, keras_layer): """Convert an SimpleRNN la...
Convert a GRU layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_gru(builder, layer, input_names, output_names, keras_layer): """Convert a GRU layer from keras to cor...
Convert a bidirectional layer from keras to coreml. Currently assumes the units are LSTMs. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_bidirectional(builder, layer, input_names, outpu...
Parameters keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_batchnorm(builder, layer, input_names, output_names, keras_layer): """ Parameters keras_layer: layer A keras layer object. builder: NeuralNetw...
Convert a flatten layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_flatten(builder, layer, input_names, output_names, keras_layer): """Convert a flatten layer from ...
Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_softmax(builder, layer, input_names, output_names, keras_layer): """Convert a softmax layer from ...
Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. def convert_permute(builder, layer, input_names, output_names, keras_layer): """Convert a softmax layer from ...
customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nslave number of slave process to start up args arguments to launch each job this usually includes th...
Returns a string representing the ast. :param ast: the ast to print. :param indent: how far to indent a newline. :param newline: The newline character. def dump_ast(ast, indent=' ', newline='\n'): ''' Returns a string representing the ast. :param ast: the ast to print. :param...
Pretty print an ast node. :param ast: the ast to print. :param indent: how far to indent a newline. :param initlevel: starting indent level :param newline: The newline character. :param file: file object to print to To print a short ast you may want to use:: node = ast.par...
Convert a ctypes pointer array to a numpy array. def ctypes2numpy(cptr, length, dtype): """Convert a ctypes pointer array to a numpy array. """ if not isinstance(cptr, ctypes.POINTER(ctypes.c_float)): raise RuntimeError('expected float pointer') res = np.zeros(length, dtype=dtype) if not ct...
Extract internal data from pd.DataFrame def _maybe_from_pandas(data, feature_names, feature_types): """ Extract internal data from pd.DataFrame """ try: import pandas as pd except ImportError: return data, feature_names, feature_types if not isinstance(data, pd.DataFrame): retu...
Initialize data from a CSR matrix. def _init_from_csr(self, csr): """ Initialize data from a CSR matrix. """ if len(csr.indices) != len(csr.data): raise ValueError('length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data))) self.handle = ctypes.c_void_p() ...
Initialize data from a CSC matrix. def _init_from_csc(self, csc): """ Initialize data from a CSC matrix. """ if len(csc.indices) != len(csc.data): raise ValueError('length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data))) self.handle = ctypes.c_void_p() ...
Initialize data from a 2-D numpy matrix. def _init_from_npy2d(self, mat, missing): """ Initialize data from a 2-D numpy matrix. """ if len(mat.shape) != 2: raise ValueError('Input numpy.ndarray must be 2 dimensional') data = np.array(mat.reshape(mat.size), dtype=np.f...
Get float property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data def get_float_info(self, field): """Get float property fr...
Get unsigned integer property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data def get_uint_info(self, field): """Get unsigne...
Set float type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set def set_float_info(self, field, data): """Set float type property into the DMatrix. Parame...
Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set def set_uint_info(self, field, data): """Set uint type property into the DMatrix. Parameter...
Save DMatrix to an XGBoost buffer. Parameters ---------- fname : string Name of the output buffer file. silent : bool (optional; default: True) If set, the output is suppressed. def save_binary(self, fname, silent=True): """Save DMatrix to an XGBoost buf...
Get the number of rows in the DMatrix. Returns ------- number of rows : int def num_row(self): """Get the number of rows in the DMatrix. Returns ------- number of rows : int """ ret = ctypes.c_ulong() _check_call(_LIB.XGDMatrixNumRow(sel...
Get the number of columns (features) in the DMatrix. Returns ------- number of columns : int def num_col(self): """Get the number of columns (features) in the DMatrix. Returns ------- number of columns : int """ ret = ctypes.c_uint() _ch...
Slice the DMatrix and return a new DMatrix that only contains `rindex`. Parameters ---------- rindex : list List of indices to be selected. Returns ------- res : DMatrix A new DMatrix containing only selected indices. def slice(self, rindex): ...
Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names def feature_names(self, feature_names): """Set feature names (column labels). Parameters ---------- fea...
Set feature types (column types). This is for displaying the results and unrelated to the learning process. Parameters ---------- feature_types : list or None Labels for features. None will reset existing feature names def feature_types(self, feature_types): ...
Update for one iteration, with objective function calculated internally. Parameters ---------- dtrain : DMatrix Training data. iteration : int Current iteration number. fobj : function Customized objective function. def update(self, dtrain, i...
Boost the booster for one iteration, with customized gradient statistics. Parameters ---------- dtrain : DMatrix The training DMatrix. grad : list The first order of gradient. hess : list The second order of gradient. def boost(self, dtrain, ...
Evaluate a set of data. Parameters ---------- evals : list of tuples (DMatrix, string) List of items to be evaluated. iteration : int Current iteration. feval : function Custom evaluation function. Returns ------- res...