text
stringlengths
81
112k
Predict with data. NOTE: This function is not thread safe. For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call bst.copy() to make copies of model object and then call predict Parameters...
Save the model to a in memory buffer represetation Returns ------- a in memory buffer represetation of the model def save_raw(self): """ Save the model to a in memory buffer represetation Returns ------- a in memory buffer represetation of the model ...
Load the model from a file. Parameters ---------- fname : string or a memory buffer Input file name or memory buffer(see also save_raw) def load_model(self, fname): """ Load the model from a file. Parameters ---------- fname : string or a me...
Dump model into a text file. Parameters ---------- foout : string Output file name. fmap : string, optional Name of the file containing feature map names. with_stats : bool (optional) Controls whether the split statistics are output. def dump...
Returns the dump the model as a list of strings. def get_dump(self, fmap='', with_stats=False): """ Returns the dump the model as a list of strings. """ length = ctypes.c_ulong() sarr = ctypes.POINTER(ctypes.c_char_p)() if self.feature_names is not None and fmap == '': ...
Get feature importance of each feature. Parameters ---------- fmap: str (optional) The name of feature map file def get_fscore(self, fmap=''): """Get feature importance of each feature. Parameters ---------- fmap: str (optional) The name o...
Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature...
Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions. def disassembler(co, lasti= -1): """Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions. """ code = co.co_code labels = di...
Matches all elements of 'list' agains the 'pattern' and returns a list of the elements indicated by indices of all successfull matches. If 'indices' is omitted returns a list of first paranthethised groups of all successfull matches. def transform (list, pattern, indices = [1]): """...
Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex expression. Args: s (str): the string to modify pattern (str): the search expression replacement (str): the string to replace each match with def repla...
Replaces occurrences of a match string in a given list of strings and returns a list of new strings. The match string can be a regex expression. Args: items (list): the list of strings to modify. match (str): the search expression. replacement (str): the string to replace ...
Create a topic model from the given data set. A topic model assumes each document is a mixture of a set of topics, where for each topic some words are more likely than others. One statistical approach to do this is called a "topic model". This method learns a topic model for the given document collectio...
Compute the perplexity of a set of test documents given a set of predicted topics. Let theta be the matrix of document-topic probabilities, where theta_ik = p(topic k | document i). Let Phi be the matrix of term-topic probabilities, where phi_jk = p(word j | topic k). Then for each word in each do...
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 list of tuples) A list of summary sections...
Return the value of a given field. The list of all queryable fields is detailed below, and can be obtained with the :py:func:`~TopicModel._list_fields` method. +-----------------------+----------------------------------------------+ | Field | Description ...
Return a dictionary of statistics collected during creation of the model. These statistics are also available with the ``get`` method and are described in more detail in that method's documentation. Returns ------- out : dict Dictionary of statistics compiled during ...
Get the words associated with a given topic. The score column is the probability of choosing that word given that you have chosen a particular topic. Parameters ---------- topic_ids : list of int, optional The topics to retrieve words. Topic ids are zero-based. ...
Use the model to predict topics for each document. The provided `dataset` should be an SArray object where each element is a dict representing a single document in bag-of-words format, where keys are words and values are their corresponding counts. If `dataset` is an SFrame, then it must...
Estimate the model's ability to predict new data. Imagine you have a corpus of books. One common approach to evaluating topic models is to train on the first half of all of the books and see how well the model predicts the second half of each book. This method returns a metric called pe...
Convert from corner bounding box to center/shape def bbox_to_ybox(bbox): """Convert from corner bounding box to center/shape""" return [ (bbox[1] + bbox[3]) / 2, (bbox[0] + bbox[2]) / 2, (bbox[3] - bbox[1]), (bbox[2] - bbox[0]), ]
Performs some sanity checks on the SFrame provided as input to `turicreate.drawing_classifier.create` and raises a ToolkitError if something in the dataset is missing or wrong. def _raise_error_if_not_drawing_classifier_input_sframe( dataset, feature, target): """ Performs some sanity checks on th...
Create a :class:`DrawingClassifier` model. Parameters ---------- dataset : SFrame Input data. The columns named by the ``feature`` and ``target`` parameters will be extracted for training the drawing classifier. target : string Name of the column containing the target variable....
Save the model in Core ML format. The Core ML model takes a grayscale drawing of fixed size as input and produces two outputs: `classLabel` and `labelProbabilities`. The first one, `classLabel` is an integer or string (depending on the classes the model was trained on) to store the la...
Predict with probabilities. The core prediction part that both `evaluate` and `predict` share. Returns an SFrame with two columns, self.target, and "probabilities". The column with column name, self.target, contains the predictions made by the model for the provided dataset. ...
Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same names as the feature and target columns used for model t...
Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability` or `rank`, depending on the ``output_type`` parameter. Parameters ---------- dataset : SFrame | SArray | turi...
Predict on an SFrame or SArray of drawings, or on a single drawing. Parameters ---------- data : SFrame | SArray | tc.Image | list The drawing(s) on which to perform drawing classification. If dataset is an SFrame, it must have a column with the same name as ...
Parameters ---------- dataset: SFrame SFrame of images def extract_features(self, dataset, feature, batch_size=64, verbose=False): """ Parameters ---------- dataset: SFrame SFrame of images """ from ._mxnet._mx_sframe_iter import S...
Parameters ---------- mode: str ('classifier', 'regressor' or None) Mode of the converted coreml model. When mode = 'classifier', a NeuralNetworkClassifier spec will be constructed. When mode = 'regressor', a NeuralNetworkRegressor spec will be constructed. R...
Takes an mxnet parameter collect (from Block.collect_params()) and subsets it with the parameters available in this base network. def available_parameters_subset(self, mx_params): """ Takes an mxnet parameter collect (from Block.collect_params()) and subsets it with the parameters avail...
Return an SFrame containing a bag of words representation of each column. def _BOW_FEATURE_EXTRACTOR(sf, target=None): """ Return an SFrame containing a bag of words representation of each column. """ if isinstance(sf, dict): out = _tc.SArray([sf]).unpack('') elif isinstance(sf, _tc.SFrame)...
Create a model that trains a classifier to classify text from a collection of documents. The model is a :class:`~turicreate.logistic_classifier.LogisticClassifier` model trained using a bag-of-words representation of the text dataset. Parameters ---------- dataset : SFrame Contains one or...
Returns a list of names of columns that are string type. def _get_str_columns(sf): """ Returns a list of names of columns that are string type. """ return [name for name in sf.column_names() if sf[name].dtype == str]
Return predictions for ``dataset``, using the trained model. Parameters ---------- dataset : SFrame dataset of new observations. Must include columns with the same names as the features used for model training, but does not require a target column. Additional...
Return a classification, for each example in the ``dataset``, using the trained model. The output SFrame contains predictions as both class labels as well as probabilities that the predicted value is the associated label. Parameters ---------- dataset : SFrame ...
Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame An SFrame having the same feature columns as provided when creating the model. metric : str, optional Name ...
Takes an SVM regression model produces a starting spec using the parts. that are shared between all SVMs. def _generate_base_svm_regression_spec(model): """ Takes an SVM regression model produces a starting spec using the parts. that are shared between all SVMs. """ if not(_HAS_SKLEARN): ...
Convert a Support Vector Regressor (SVR) model to the protobuf spec. Parameters ---------- model: SVR A trained SVR encoder model. feature_names: [str] Name of the input columns. target: str Name of the output column. Returns ------- model_spec: An object of ty...
Verify that the given extension handle is valid. def _VerifyExtensionHandle(message, extension_handle): """Verify that the given extension handle is valid.""" if not isinstance(extension_handle, _FieldDescriptor): raise KeyError('HasExtension() expects an extension handle, got: %s' % extens...
Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type. def _AddEnumValues(descriptor, cls): """Sets class-leve...
Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field. The returned function has one argument: message: Message instance containing this field, or a weakref proxy of same. That function in turn returns a default value for this field. The...
Re-raise the currently-handled TypeError with the field name added. def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added.""" exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field n...
Adds an __init__ method to cls. def _AddInitMethod(message_descriptor, cls): """Adds an __init__ method to cls.""" def _GetIntegerEnumValue(enum_type, value): """Convert a string or integer enum value to an integer. If the value is a string, it is converted to the enum value in enum_type with the sam...
Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name. def _GetFieldByName(message_descriptor, field_name): """Returns a field desc...
Adds properties for all fields in this protocol message type. def _AddPropertiesForFields(descriptor, cls): """Adds properties for all fields in this protocol message type.""" for field in descriptor.fields: _AddPropertiesForField(field, cls) if descriptor.is_extendable: # _ExtensionDict is just an adap...
Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're constructing. def _AddPropertiesForField(fie...
Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add values to these containers, we perform type-checking i...
Adds a public property for a nonrepeated, scalar protocol message field. Clients can use this property to get and directly set the value of the field. Note that when the client sets the value of a field by using this property, all necessary "has" bits are set as a side-effect, and we also perform type-checking....
Adds properties for all fields in this protocol message type. def _AddPropertiesForExtensions(descriptor, cls): """Adds properties for all fields in this protocol message type.""" extension_dict = descriptor.extensions_by_name for extension_name, extension_field in extension_dict.items(): constant_name = ext...
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields(). def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].l...
Helper for _AddMessageMethods(). def _AddListFieldsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ListFields(self): all_fields = [item for item in self._fields.items() if _IsPresent(item)] all_fields.sort(key = lambda item: item[0].number) return all_fields cls.ListFiel...
Helper for _AddMessageMethods(). def _AddHasFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" is_proto3 = (message_descriptor.syntax == "proto3") error_msg = _Proto3HasError if is_proto3 else _Proto2HasError hassable_fields = {} for field in message_descriptor.fields: if fiel...
Helper for _AddMessageMethods(). def _AddClearFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ClearField(self, field_name): try: field = message_descriptor.fields_by_name[field_name] except KeyError: try: field = message_descriptor.oneofs_by_name[field_n...
Helper for _AddMessageMethods(). def _AddClearExtensionMethod(cls): """Helper for _AddMessageMethods().""" def ClearExtension(self, extension_handle): _VerifyExtensionHandle(self, extension_handle) # Similar to ClearField(), above. if extension_handle in self._fields: del self._fields[extension_...
Helper for _AddMessageMethods(). def _AddHasExtensionMethod(cls): """Helper for _AddMessageMethods().""" def HasExtension(self, extension_handle): _VerifyExtensionHandle(self, extension_handle) if extension_handle.label == _FieldDescriptor.LABEL_REPEATED: raise KeyError('"%s" is repeated.' % extensio...
Unpacks Any message and returns the unpacked message. This internal method is different from public Any Unpack method which takes the target message as argument. _InternalUnpackAny method does not have target message type and need to find the message type in descriptor pool. Args: msg: An Any message to b...
Helper for _AddMessageMethods(). def _AddEqualsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __eq__(self, other): if (not isinstance(other, message_mod.Message) or other.DESCRIPTOR != self.DESCRIPTOR): return False if self is other: return True if sel...
Helper for _AddMessageMethods(). def _AddStrMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __str__(self): return text_format.MessageToString(self) cls.__str__ = __str__
Helper for _AddMessageMethods(). def _AddReprMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __repr__(self): return text_format.MessageToString(self) cls.__repr__ = __repr__
Helper for _AddMessageMethods(). def _AddUnicodeMethod(unused_message_descriptor, cls): """Helper for _AddMessageMethods().""" def __unicode__(self): return text_format.MessageToString(self, as_utf8=True).decode('utf-8') cls.__unicode__ = __unicode__
Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value. Args: value: Value we're serializing. field_number: Field number of this value. (Since the field number ...
Helper for _AddMessageMethods(). def _AddByteSizeMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ByteSize(self): if not self._cached_byte_size_dirty: return self._cached_byte_size size = 0 for field_descriptor, field_value in self.ListFields(): size += field_de...
Helper for _AddMessageMethods(). def _AddSerializeToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializeToString(self): # Check if the message has all of its required fields set. errors = [] if not self.IsInitialized(): raise message_mod.EncodeError( ...
Helper for _AddMessageMethods(). def _AddSerializePartialToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializePartialToString(self): out = BytesIO() self._InternalSerialize(out.write) return out.getvalue() cls.SerializePartialToString = SerializePartialToStrin...
Helper for _AddMessageMethods(). def _AddMergeFromStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def MergeFromString(self, serialized): length = len(serialized) try: if self._InternalParse(serialized, 0, length) != length: # The only reason _InternalParse would ...
Adds the IsInitialized and FindInitializationError methods to the protocol message class. def _AddIsInitializedMethod(message_descriptor, cls): """Adds the IsInitialized and FindInitializationError methods to the protocol message class.""" required_fields = [field for field in message_descriptor.fields ...
Adds implementations of all Message methods to cls. def _AddMessageMethods(message_descriptor, cls): """Adds implementations of all Message methods to cls.""" _AddListFieldsMethod(message_descriptor, cls) _AddHasFieldMethod(message_descriptor, cls) _AddClearFieldMethod(message_descriptor, cls) if message_des...
Adds implementation of private helper methods to cls. def _AddPrivateHelperMethods(message_descriptor, cls): """Adds implementation of private helper methods to cls.""" def Modified(self): """Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change. ...
Also updates the state of the containing oneof in the parent message. def Modified(self): """Also updates the state of the containing oneof in the parent message.""" try: self._parent_message_weakref._UpdateOneofState(self._field) super(_OneofListener, self).Modified() except ReferenceError: ...
Returns a string containing the name of an enum value. def Name(self, number): """Returns a string containing the name of an enum value.""" if number in self._enum_type.values_by_number: return self._enum_type.values_by_number[number].name raise ValueError('Enum %s has no name defined for value %d' %...
Returns the value coresponding to the given enum name. def Value(self, name): """Returns the value coresponding to the given enum name.""" if name in self._enum_type.values_by_name: return self._enum_type.values_by_name[name].number raise ValueError('Enum %s has no value defined for name %s' % ( ...
Return a list of the (name, value) pairs of the enum. These are returned in the order they were defined in the .proto file. def items(self): """Return a list of the (name, value) pairs of the enum. These are returned in the order they were defined in the .proto file. """ return [(value_descriptor...
Load global singleton of tcmps lib handler. This function is used not used at the top level, so that the shared library is loaded lazily only when needed. def _load_tcmps_lib(): """ Load global singleton of tcmps lib handler. This function is used not used at the top level, so that the shared...
Returns True if the environment has MPS backend support and a high-power (fast) device is available. def has_fast_mps_support(): """ Returns True if the environment has MPS backend support and a high-power (fast) device is available. """ lib = _load_tcmps_lib() if lib is None: retur...
Returns name of MPS device that will be used, else None. def mps_device_name(): """ Returns name of MPS device that will be used, else None. """ lib = _load_tcmps_lib() if lib is None: return None n = 256 c_name = (_ctypes.c_char * n)() ret = lib.TCMPSMetalDeviceName(_ctypes.by...
Returns the memory size in bytes that can be effectively allocated on the MPS device that will be used, or None if no suitable device is available. def mps_device_memory_limit(): """ Returns the memory size in bytes that can be effectively allocated on the MPS device that will be used, or None if no su...
Copy the shape from TCMPS as a new numpy ndarray. def shape(self): """Copy the shape from TCMPS as a new numpy ndarray.""" # Create C variables that will serve as out parameters for TCMPS. shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr dim = _ctypes.c_size_t() ...
Copy the data from TCMPS into a new numpy ndarray def asnumpy(self): """Copy the data from TCMPS into a new numpy ndarray""" # Create C variables that will serve as out parameters for TCMPS. data_ptr = _ctypes.POINTER(_ctypes.c_float)() # float* data_ptr shape_ptr = _ctypes.POINTER(...
Submits an input batch to the model. Returns a MpsFloatArray representing the batch loss. Calling asnumpy() on this value will wait for the batch to finish and yield the loss as a numpy array. def train(self, input, label): """ Submits an input batch to the model. Returns a MpsFloatArra...
Submits an input batch to the model. Returns a MpsFloatArray representing the model predictions. Calling asnumpy() on this value will wait for the batch to finish and yield the predictions as a numpy array. def predict(self, input): """ Submits an input batch to the model. Returns a Mps...
Performs a forward pass from the input batch, followed by a backward pass using the provided gradient (in place of a loss function). Returns a MpsFloatArray representing the output (final gradient) of the backward pass. Calling asnumpy() on this value will wait for the batch to finish an...
Gets SNS Message, deserialises the message, imports the function, calls the function with args def route_sns_task(event, context): """ Gets SNS Message, deserialises the message, imports the function, calls the function with args """ record = event['Records'][0] message = json.loads( ...
Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'command' in handler.py def run_message(message): """ Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'comm...
Instead of decorating a function with @task, you can just run it directly. If you were going to do func(*args, **kwargs), then you will call this: import zappa.asynchronous.run zappa.asynchronous.run(func, args, kwargs) If you want to use SNS, then do: zappa.asynchronous.run(func, args, kwargs, s...
Async task decorator so that running Args: func (function): the function to be wrapped Further requirements: func must be an independent top-level function. i.e. not a class method or an anonymous function service (str): either 'lambda' or 'sns' remo...
Given a modular path to a function, import that module and return the function. def import_and_get_task(task_path): """ Given a modular path to a function, import that module and return the function. """ module, function = task_path.rsplit('.', 1) app_module = importlib.import_module(module...
Format the modular task path for a function via inspection. def get_func_task_path(func): """ Format the modular task path for a function via inspection. """ module_path = inspect.getmodule(func).__name__ task_path = '{module_path}.{func_name}'.format( module...
Get the response from the async table def get_async_response(response_id): """ Get the response from the async table """ response = DYNAMODB_CLIENT.get_item( TableName=ASYNC_RESPONSE_TABLE, Key={'id': {'S': str(response_id)}} ) if 'Item' not in response: return None ...
Create the message object and pass it to the actual sender. def send(self, task_path, args, kwargs): """ Create the message object and pass it to the actual sender. """ message = { 'task_path': task_path, 'capture_response': self.capture_response, ...
Given a message, directly invoke the lamdba function for this task. def _send(self, message): """ Given a message, directly invoke the lamdba function for this task. """ message['command'] = 'zappa.asynchronous.route_lambda_task' payload = json.dumps(message).encode('utf-8') ...
Given a message, publish to this topic. def _send(self, message): """ Given a message, publish to this topic. """ message['command'] = 'zappa.asynchronous.route_sns_task' payload = json.dumps(message).encode('utf-8') if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma...
Parses S3 URL. Returns bucket (domain) and file (full path). def parse_s3_url(url): """ Parses S3 URL. Returns bucket (domain) and file (full path). """ bucket = '' path = '' if url: result = urlparse(url) bucket = result.netloc path = result.path.strip('/') ...
Accepts a str, returns an int timestamp. def string_to_timestamp(timestring): """ Accepts a str, returns an int timestamp. """ ts = None # Uses an extended version of Go's duration string. try: delta = durationpy.from_str(timestring); past = datetime.datetime.utcnow() - delta ...
Automatically try to discover Django settings files, return them as relative module paths. def detect_django_settings(): """ Automatically try to discover Django settings files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): ...
Automatically try to discover Flask apps files, return them as relative module paths. def detect_flask_apps(): """ Automatically try to discover Flask apps files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filen...
Given an event_source dictionary, create the object and add the event source. def add_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and add the event source. """ event_source_obj, ctx, funk = get_event_source(e...
Given an event_source dictionary, create the object and remove the event source. def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and remove the event source. """ event_source_obj, ctx, funk = get_event...
Given an event_source dictionary, create the object and get the event source status. def get_event_source_status(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and get the event source status. """ event_source_obj, ctx, funk...
Checks if a newer version of Zappa is available. Returns True is updateable, else False. def check_new_version_available(this_version): """ Checks if a newer version of Zappa is available. Returns True is updateable, else False. """ import requests pypi_url = 'https://pypi.python.org/py...
Validate name for AWS Lambda function. name: actual name (without `arn:aws:lambda:...:` prefix and without `:$LATEST`, alias or version suffix. maxlen: max allowed length for name without prefix and suffix. The value 80 was calculated from prefix with longest known region name and assuming that...