Search is not available for this dataset
text
stringlengths
75
104k
def implied_feature (implicit_value): """ Returns the implicit feature associated with the given implicit value. """ assert isinstance(implicit_value, basestring) components = implicit_value.split('-') if components[0] not in __implicit_features: raise InvalidValue ("'%s' is not a value of ...
def validate_feature (name): """ Checks if all name is a valid feature. Otherwise, raises an exception. """ assert isinstance(name, basestring) if name not in __all_features: raise InvalidFeature ("'%s' is not a valid feature name" % name) else: return __all_features[name]
def __expand_subfeatures_aux (property_, dont_validate = False): """ Helper for expand_subfeatures. Given a feature and value, or just a value corresponding to an implicit feature, returns a property set consisting of all component subfeatures and their values. For example: expand...
def expand_subfeatures(properties, dont_validate = False): """ Make all elements of properties corresponding to implicit features explicit, and express all subfeature values as separate properties in their own right. For example, the property gcc-2.95.2-linux-x86 might expand to <too...
def extend (name, values): """ Adds the given values to the given feature. """ assert isinstance(name, basestring) assert is_iterable_typed(values, basestring) name = add_grist (name) __validate_feature (name) feature = __all_features [name] if feature.implicit: for v in values:...
def validate_value_string (f, value_string): """ Checks that value-string is a valid value-string for the given feature. """ assert isinstance(f, Feature) assert isinstance(value_string, basestring) if f.free or value_string in f.values: return values = [value_string] if f.subfeatu...
def subfeature (feature_name, value_string, subfeature, subvalues, attributes = []): """ Declares a subfeature. feature_name: Root feature that is not a subfeature. value_string: An optional value-string specifying which feature or subfeature values this subfeature is spe...
def compose (composite_property_s, component_properties_s): """ Sets the components of the given composite property. All parameters are <feature>value strings """ from . import property component_properties_s = to_seq (component_properties_s) composite_property = property.create_from_string(co...
def get_values (feature, properties): """ Returns all values of the given feature specified by the given property set. """ if feature[0] != '<': feature = '<' + feature + '>' result = [] for p in properties: if get_grist (p) == feature: result.append (replace_grist (p, '')) ...
def expand_composites (properties): """ Expand all composite properties in the set so that all components are explicitly expressed. """ if __debug__: from .property import Property assert is_iterable_typed(properties, Property) explicit_features = set(p.feature for p in propertie...
def is_subfeature_of (parent_property, f): """ Return true iff f is an ordinary subfeature of the parent_property's feature, or if f is a subfeature of the parent_property's feature specific to the parent_property's value. """ if __debug__: from .property import Property asse...
def __is_subproperty_of (parent_property, p): """ As is_subfeature_of, for subproperties. """ if __debug__: from .property import Property assert isinstance(parent_property, Property) assert isinstance(p, Property) return is_subfeature_of (parent_property, p.feature)
def expand (properties): """ Given a property set which may consist of composite and implicit properties and combined subfeature values, returns an expanded, normalized property set with all implicit features expressed explicitly, all subfeature values individually expressed, and all ...
def add_defaults (properties): """ Given a set of properties, add default values for features not represented in the set. Note: if there's there's ordinary feature F1 and composite feature F2, which includes some value for F1, and both feature have default values, then the default va...
def minimize (properties): """ Given an expanded property set, eliminate all redundancy: properties which are elements of other (composite) properties in the set will be eliminated. Non-symmetric properties equal to default values will be eliminated, unless the override a value from some com...
def split (properties): """ Given a property-set of the form v1/v2/...vN-1/<fN>vN/<fN+1>vN+1/...<fM>vM Returns v1 v2 ... vN-1 <fN>vN <fN+1>vN+1 ... <fM>vM Note that vN...vM may contain slashes. This is resilient to the substitution of backslashes for slashes, since Jam, unbidden, s...
def compress_subproperties (properties): """ Combine all subproperties into their parent properties Requires: for every subproperty, there is a parent property. All features are explicitly expressed. This rule probably shouldn't be needed, but build-request.expand-no-defaults is b...
def __select_subfeatures (parent_property, features): """ Given a property, return the subset of features consisting of all ordinary subfeatures of the property's feature, and all specific subfeatures of the property's feature which are conditional on the property's value. """ if __d...
def _get_interpretation_function(interpretation, dtype): """ Retrieves the interpretation function used. """ type_string = dtype.__name__ name = "%s__%s" % (interpretation, type_string) global _interpretations if not hasattr(_interpretations, name): raise ValueError("No transform ...
def _get_interpretation_description_and_output_type(interpretation, dtype): """ Returns the description and output type for a given interpretation. """ type_string = dtype.__name__ name = "%s__%s" % (interpretation, type_string) if not hasattr(_interpretations_class, name): raise Value...
def _get_embeddable_interpretation_doc(indent = 0): """ Returns a list of the available interpretations and what they do. If indent is specified, then the entire doc string is indented by that amount. """ output_rows = [] # Pull out the doc string and put it in a table. for name in sorted...
def _load_version(cls, unpickler, version): """ A function to load a previously saved SentenceSplitter instance. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writer...
def fit(self, data): """ Fits the transformer using the given data. """ _raise_error_if_not_sframe(data, "data") fitted_state = {} feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features) if not feature_columns: raise ...
def transform(self, data): """ Transforms the data. """ if not self._get("fitted"): raise RuntimeError("`transform` called before `fit` or `fit_transform`.") data = data.copy() output_column_prefix = self._get("output_column_prefix") if output_colum...
def short_text__str(self, column_name, output_column_prefix): """ Transforms short text into a dictionary of TFIDF-weighted 3-gram character counts. """ from ._ngram_counter import NGramCounter from ._tfidf import TFIDF return [NGramCounter(features=[column_name...
def categorical__int(self, column_name, output_column_prefix): """ Interprets an integer column as a categorical variable. """ return [_ColumnFunctionTransformation( features = [column_name], output_column_prefix = output_column_prefix, transform_func...
def _setup_from_data(self, data): """ Sets up the content transforms. """ fitted_state = {} _raise_error_if_not_of_type(data, [_SFrame]) feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features) if not feature_columns: ...
def fit(self, data): """ Fits a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted object) See Also -------- transform, fit_tr...
def fit_transform(self, data): """ Fits and transforms the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out...
def transform(self, data): """ Transform the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out: SFrame ...
def _get_summary_struct(self): """ Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of lis...
def _save_impl(self, pickler): """ Save the model as a directory, which can be loaded with the :py:func:`~turicreate.load_model` method. Parameters ---------- pickler : GLPickler An opened GLPickle archive (Do not close the archive). See Also ...
def CreateMock(self, class_to_mock): """Create a new mock object. Args: # class_to_mock: the class to be mocked class_to_mock: class Returns: MockObject that can be used as the class_to_mock would be. """ new_mock = MockObject(class_to_mock) self._mock_objects.append(new_moc...
def StubOutWithMock(self, obj, attr_name, use_mock_anything=False): """Replace a method, attribute, etc. with a Mock. This will replace a class or module with a MockObject, and everything else (method, function, etc) with a MockAnything. This can be overridden to always use a MockAnything by setting u...
def _Verify(self): """Verify that all of the expected calls have been made. Raises: ExpectedMethodCallsError: if there are still more method calls in the expected queue. """ # If the list of expected calls is not empty, raise an exception if self._expected_calls_queue: # The la...
def _VerifyMethodCall(self): """Verify the called method is expected. This can be an ordered method, or part of an unordered set. Returns: The expected mock method. Raises: UnexpectedMethodCall if the method called was not expected. """ expected = self._PopNextMethod() # Loo...
def GetPossibleGroup(self): """Returns a possible group from the end of the call queue or None if no other methods are on the stack. """ # Remove this method from the tail of the queue so we can add it to a group. this_method = self._call_queue.pop() assert this_method == self # Determine ...
def _CheckAndCreateNewGroup(self, group_name, group_class): """Checks if the last method (a possible group) is an instance of our group_class. Adds the current method to this group or creates a new one. Args: group_name: the name of the group. group_class: the class used to create instance of ...
def equals(self, rhs): """Check to see if the RHS is an instance of class_name. Args: # rhs: the right hand side of the test rhs: object Returns: bool """ try: return isinstance(rhs, self._class_name) except TypeError: # Check raw types if there was a type error....
def equals(self, rhs): """Check to see if RHS is almost equal to float_value Args: rhs: the value to compare to float_value Returns: bool """ try: return round(rhs-self._float_value, self._places) == 0 except TypeError: # This is probably because either float_value or ...
def equals(self, rhs): """Check whether the given key/value pair is in the rhs dict. Returns: bool """ try: return rhs[self._key] == self._value except Exception: return False
def equals(self, actual_seq): """Check to see whether actual_seq has same elements as expected_seq. Args: actual_seq: sequence Returns: bool """ try: expected = dict([(element, None) for element in self._expected_seq]) actual = dict([(element, None) for element in actual_s...
def equals(self, rhs): """Checks whether any Comparator is equal to rhs. Args: # rhs: can be anything Returns: bool """ for comparator in self._comparators: if comparator.equals(rhs): return True return False
def MethodCalled(self, mock_method): """Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raise...
def MethodCalled(self, mock_method): """Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raise...
def IsSatisfied(self): """Return True if all methods in this group are called at least once.""" # NOTE(psycho): We can't use the simple set difference here because we want # to match different parameters which are considered the same e.g. IsA(str) # and some string. This solution is O(n^2) but n should ...
def convert(model, input_features, output_features): """Convert a _imputer model to the protobuf spec. Parameters ---------- model: Imputer A trained Imputer model. input_features: str Name of the input column. output_features: str Name of the output column. Retur...
def set_classifier_interface_params(spec, features, class_labels, model_accessor_for_class_labels, output_features = None): """ Common utilities to set the regression interface params. """ # Normalize the features list. features = _fm.process_or_validate_features(features) if class_labe...
def set_regressor_interface_params(spec, features, output_features): """ Common utilities to set the regressor interface params. """ if output_features is None: output_features = [("predicted_class", datatypes.Double())] else: output_features = _fm.process_or_validate_features(output_fea...
def set_transform_interface_params(spec, input_features, output_features, are_optional = False): """ Common utilities to set transform interface params. """ input_features = _fm.process_or_validate_features(input_features) output_features = _fm.process_or_validate_features(output_features) # Add in...
def prep_data(data, features, session_id, prediction_window, predictions_in_chunk, target=None, verbose=True): """ Convert SFrame to batch form, where each row contains a sequence of length predictions_in_chunk * prediction_window, and there is a single label per prediction window. """ if target...
def _load_into_numpy(sf, np_array, start, end, strides=None, shape=None): """Loads into numpy array from SFrame, assuming SFrame stores data flattened""" np_array[:] = 0.0 np_array_2d = np_array.reshape((np_array.shape[0], np_array.shape[1] * np_array.shape[2])) _extensions.sframe_load_to_numpy(sf, np_a...
def set_input(self, input_names, input_dims): """ Set the inputs of the network spec. Parameters ---------- input_names: [str] List of input names of the network. input_dims: [tuple] List of input dimensions of the network. The ordering of input_...
def set_output(self, output_names, output_dims): """ Set the outputs of the network spec. Parameters ---------- output_names: [str] List of output names of the network. output_dims: [tuple] List of output dimensions of the network. The ordering o...
def set_class_labels(self, class_labels, predicted_feature_name = 'classLabel', prediction_blob = ''): """ Set class labels to the model spec to make it a neural network classifier. Parameters ---------- class_labels: list[int or str] A list of integers or strings th...
def add_optionals(self, optionals_in, optionals_out): """ Add optional inputs and outputs to the model spec. Parameters ---------- optionals_in: [str] List of inputs that are optionals. optionals_out: [str] List of outputs that are optionals. ...
def add_embedding(self, name, W, b, input_dim, output_channels, has_bias, input_name, output_name): """ Add an embedding layer to the model. Parameters ---------- name: str The name of this layer W: numpy.array Weight matrix ...
def add_softmax(self, name, input_name, output_name): """ Add a softmax layer to the model. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str The output ...
def add_activation(self, name, non_linearity, input_name, output_name, params=None): """ Add an activation layer to the model. Parameters ---------- name: str The name of this layer non_linearity: str The non_linearity (activation) functio...
def add_elementwise(self, name, input_names, output_name, mode, alpha = None): """ Add an element-wise operation layer to the model. Parameters ---------- The name of this layer name: str input_names: [str] A list of input blob names of this layer...
def add_upsample(self, name, scaling_factor_h, scaling_factor_w, input_name, output_name, mode = 'NN'): """ Add upsample layer to the model. Parameters ---------- name: str The name of this layer. scaling_factor_h: int Scaling factor on the vertic...
def add_scale(self, name, W, b, has_bias, input_name, output_name, shape_scale = [1], shape_bias = [1]): """ Add scale layer to the model. Parameters ---------- name: str The name of this layer. W: int | numpy.array Scale of the input. b: ...
def add_bias(self, name, b, input_name, output_name, shape_bias = [1]): """ Add bias layer to the model. Parameters ---------- name: str The name of this layer. b: int | numpy.array Bias to add to the input. input_name: str The...
def add_sequence_repeat(self, name, nrep, input_name, output_name): """ Add sequence repeat layer to the model. Parameters ---------- name: str The name of this layer. nrep: int Number of repetitions of the input blob along the sequence axis. ...
def add_convolution(self, name, kernel_channels, output_channels, height, width, stride_height, stride_width, border_mode, groups, W, b, has_bias, is_deconv = False, output_shape = None, input_name = 'data', output_name = 'out', dilation_factors = [1,1], paddi...
def add_padding(self, name, left = 0, right = 0, top = 0, bottom = 0, value = 0, input_name = 'data', output_name = 'out', padding_type = 'constant'): """ Add a padding layer to the model. Kindly refer to NeuralNetwork.proto for details. Parameter...
def add_crop(self, name, left, right, top, bottom, offset, input_names, output_name): """ Add a cropping layer to the model. The cropping layer have two functional modes: - When it has 1 input blob, it crops the input blob based on the 4 parameters [left, r...
def add_simple_rnn(self,name, W_h, W_x, b, hidden_size, input_size, activation, input_names, output_names, output_all = False, reverse_input = False): """ Add a simple recurrent layer to the model. Parameters ---------- name: str The name of this layer. W_h: ...
def add_gru(self, name, W_h, W_x, b, hidden_size, input_size, input_names, output_names, activation = 'TANH', inner_activation = 'SIGMOID_HARD', output_all = False, reverse_input = False): """ Add a Gated-Recurrent Unit (GRU) layer to the model. Parameters ------...
def add_unilstm(self, name, W_h, W_x, b, hidden_size, input_size, input_names, output_names, inner_activation = 'SIGMOID', cell_state_update_activation = 'TANH', output_activation = 'TANH', peep = None, output_all = Fals...
def add_bidirlstm(self, name, W_h, W_x, b, W_h_back, W_x_back, b_back, hidden_size, input_size, input_names, output_names, inner_activation = 'SIGMOID', cell_state_update_activation = 'TANH', output_activation = 'TANH', peep = None, peep_back = None, ...
def add_flatten(self, name, mode, input_name, output_name): """ Add a flatten layer. Only flattens the channel, height and width axis. Leaves the sequence axis as is. Parameters ---------- name: str The name of this layer. mode: int - If mode == ...
def add_slice(self, name, input_name, output_name, axis, start_index = 0, end_index = -1, stride = 1): """ Add a slice layer. Equivalent to to numpy slice [start_index:end_index:stride], start_index is included, while end_index is exclusive. Parameters ---------- name: s...
def add_reorganize_data(self, name, input_name, output_name, mode = 'SPACE_TO_DEPTH', block_size = 2): """ Add a data reorganization layer of type "SPACE_TO_DEPTH" or "DEPTH_TO_SPACE". Parameters ---------- name: str The name of this layer. input_name: str ...
def add_batchnorm(self, name, channels, gamma, beta, mean = None, variance = None, input_name = 'data', output_name = 'out', compute_mean_var = False, instance_normalization = False, epsilon = 1e-5): """ Add a Batch ...
def add_permute(self, name, dim, input_name, output_name): """ Add a permute layer. Assumes that the input has dimensions in the order [Seq, C, H, W] Parameters ---------- name: str The name of this layer. dim: tuple The order in which to permute ...
def add_reshape(self, name, input_name, output_name, target_shape, mode): """ Add a reshape layer. Kindly refer to NeuralNetwork.proto for details. Parameters ---------- name: str The name of this layer. target_shape: tuple Shape of the output blo...
def add_reduce(self, name, input_name, output_name, axis, mode, epsilon = 1e-6): """ Add a reduce layer. Applies the function specified by the parameter mode, along dimension(s) specified by the parameter axis. Parameters ---------- name: str The name of this...
def add_lrn(self, name, input_name, output_name, alpha, beta, local_size, k = 1.0): """ Add a LRN (local response normalization) layer. Please see the LRNLayerParams message in Core ML neural network protobuf for more information about the operation of this layer. Supports "across" channels norm...
def add_mvn(self, name, input_name, output_name, across_channels = True, normalize_variance = True, epsilon = 1e-5): """ Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input. Parameters ---------- name: str The name of this...
def add_l2_normalize(self, name, input_name, output_name, epsilon = 1e-5): """ Add L2 normalize layer. Normalizes the input by the L2 norm, i.e. divides by the the square root of the sum of squares of all elements of the input along C, H and W dimensions. Parameters ---------- ...
def add_unary(self, name, input_name, output_name, mode, alpha = 1.0, shift = 0, scale = 1.0, epsilon = 1e-6): """ Add a Unary layer. Applies the specified function (mode) to all the elements of the input. Please see the UnaryFunctionLayerParams message in Core ML neural netw...
def add_split(self, name, input_name, output_names): """ Add a Split layer that uniformly splits the input along the channel dimension to produce multiple outputs. Parameters ---------- name: str The name of this layer. input_name: str Th...
def add_load_constant(self, name, output_name, constant_value, shape): """ Add a load constant layer. Parameters ---------- name: str The name of this layer. output_name: str The output blob name of this layer. constant_value: numpy.arra...
def add_custom(self, name, input_names, output_names, custom_proto_spec = None): """ Add a custom layer. Parameters ---------- name: str The name of this layer. input_names: [str] The input blob names to this layer. output_names: [str] ...
def set_pre_processing_parameters(self, image_input_names = [], is_bgr = False, red_bias = 0.0, green_bias = 0.0, blue_bias = 0.0, gray_bias = 0.0, image_scale = 1.0): """Add pre-processing parameters to the neural network object Parameters ---------- image_input_names: [str...
def register(scanner_class, relevant_properties): """ Registers a new generator class, specifying a set of properties relevant to this scanner. Ctor for that class should have one parameter: list of properties. """ assert issubclass(scanner_class, Scanner) assert isinstance(relevant_pro...
def get(scanner_class, properties): """ Returns an instance of previously registered scanner with the specified properties. """ assert issubclass(scanner_class, Scanner) assert is_iterable_typed(properties, basestring) scanner_name = str(scanner_class) if not registered(scanner_name): ...
def install (self, scanner, target, vtarget): """ Installs the specified scanner on actual target 'target'. vtarget: virtual target from which 'target' was actualized. """ assert isinstance(scanner, Scanner) assert isinstance(target, basestring) assert isinstance(vtar...
def _fill_function(func, globals, defaults, dict, module, closure_values): """ Fills in the rest of function data into the skeleton function object that were created via _make_skel_func(). """ func.__globals__.update(globals) func.__defaults__ = defaults func.__dict__ = dict func.__modul...
def _make_skel_func(code, cell_count, base_globals=None): """ Creates a skeleton function object that contains just the provided code and the correct number of cells in func_closure. All other func attributes (e.g. func_globals) are empty. """ if base_globals is None: base_globals =...
def _rehydrate_skeleton_class(skeleton_class, class_dict): """Put attributes from `class_dict` back on `skeleton_class`. See CloudPickler.save_dynamic_class for more info. """ for attrname, attr in class_dict.items(): setattr(skeleton_class, attrname, attr) return skeleton_class
def _find_module(mod_name): """ Iterate over each part instead of calling imp.find_module directly. This function is able to find submodules (e.g. sickit.tree) """ path = None for part in mod_name.split('.'): if path is not None: path = [path] file, path, description ...
def save_module(self, obj): """ Save a module as an import """ mod_name = obj.__name__ # If module is successfully found then it is not a dynamically created module if hasattr(obj, '__file__'): is_dynamic = False else: try: ...
def _save_subimports(self, code, top_level_dependencies): """ Ensure de-pickler imports any package child-modules that are needed by the function """ # check if any known dependency is an imported package for x in top_level_dependencies: if isinstance(x, types...
def save_dynamic_class(self, obj): """ Save a class that can't be stored as module global. This method is used to serialize classes that are defined inside functions, or that otherwise can't be serialized as attribute lookups from global modules. """ clsdict = di...
def save_function_tuple(self, func): """ Pickles an actual func object. A func comprises: code, globals, defaults, closure, and dict. We extract and save these, injecting reducing functions at certain points to recreate the func object. Keep in mind that some of these pieces ...
def extract_code_globals(cls, co): """ Find all globals names read or written to by codeblock co """ out_names = cls._extract_code_globals_cache.get(co) if out_names is None: try: names = co.co_names except AttributeError: #...
def save_global(self, obj, name=None, pack=struct.pack): """ Save a "global". The name of this method is somewhat misleading: all types get dispatched here. """ if obj.__module__ == "__builtin__" or obj.__module__ == "builtins": if obj in _BUILTIN_TYPE_NAMES:...
def save_reduce(self, func, args, state=None, listitems=None, dictitems=None, obj=None): """Modified to support __transient__ on new objects Change only affects protocol level 2 (which is always used by PiCloud""" # Assert that args is a tuple or None if not isinstanc...