Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def is_subtype (type, base): assert isinstance(type, basestring) assert isinstance(base, basestring) # TODO: remove this method return is_derived (type, base)
[ " Same as is_derived. Should be removed.\n " ]
Please provide a description of the function:def set_generated_target_suffix (type, properties, suffix): assert isinstance(type, basestring) assert is_iterable_typed(properties, basestring) assert isinstance(suffix, basestring) set_generated_target_ps(1, type, properties, suffix)
[ " Sets a target suffix that should be used when generating target\n of 'type' with the specified properties. Can be called with\n empty properties if no suffix for 'type' was specified yet.\n This does not automatically specify that files 'suffix' have\n 'type' --- two different types ca...
Please provide a description of the function:def change_generated_target_suffix (type, properties, suffix): assert isinstance(type, basestring) assert is_iterable_typed(properties, basestring) assert isinstance(suffix, basestring) change_generated_target_ps(1, type, properties, suffix)
[ " Change the suffix previously registered for this type/properties\n combination. If suffix is not yet specified, sets it.\n " ]
Please provide a description of the function:def generated_target_ps(is_suffix, type, prop_set): if __debug__: from .property_set import PropertySet assert isinstance(is_suffix, (int, bool)) assert isinstance(type, basestring) assert isinstance(prop_set, PropertySet) key = (...
[ " Returns suffix that should be used when generating target of 'type',\n with the specified properties. If not suffix were specified for\n 'type', returns suffix for base type, if any.\n " ]
Please provide a description of the function:def type(filename): assert isinstance(filename, basestring) while 1: filename, suffix = os.path.splitext (filename) if not suffix: return None suffix = suffix[1:] if suffix in __suffixes_to_types: return __suffixes_to...
[ " Returns file type given it's name. If there are several dots in filename,\n tries each suffix. E.g. for name of \"file.so.1.2\" suffixes \"2\", \"1\", and\n \"so\" will be tried.\n " ]
Please provide a description of the function:def register_type (type, suffixes, base_type = None, os = []): assert isinstance(type, basestring) assert is_iterable_typed(suffixes, basestring) assert isinstance(base_type, basestring) or base_type is None assert is_iterable_typed(os, basestring) i...
[ " Register the given type on the specified OSes, or on remaining OSes\n if os is not specified. This rule is injected into each of the type\n modules for the sake of convenience.\n " ]
Please provide a description of the function: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 = '' if isinstance(kwargs[key], f...
[]
Please provide a description of the function:def process_features(features, exclude): # Check types _raise_error_if_not_of_type(features, [NoneType, str, list], 'features') _raise_error_if_not_of_type(exclude, [NoneType, str, list], 'exclude') # Make a copy of the parameters. _features = _cop...
[ "\n Parameters\n ----------\n features : list[str] | str | None, optional\n Column names of features to be transformed. If None, all columns\n are selected. If string, that column is transformed. If list of strings,\n this list of column names is selected.\n\n exclude : list[str] | ...
Please provide a description of the function:def pretty_print_list(lst, name = 'features', repr_format=True): if not lst or len(lst) < 8: if repr_format: return lst.__repr__() else: return ', '.join(map(str, lst)) else: topk = ', '.join(map(str, lst[:3])) ...
[ " Pretty print a list to be readable.\n " ]
Please provide a description of the function:def _get_elementwise_name_from_keras_layer(keras_layer): mode = keras_layer.mode if mode == 'sum': return 'ADD' elif mode == 'mul': return 'MULTIPLY' elif mode == 'concat': if len(keras_layer.input_shape[0]) == 3 and (keras_layer....
[ "\n Get the keras layer name from the activation name.\n " ]
Please provide a description of the function:def _same_elements_per_channel(x): eps = 1e-5 dims = x.shape for c in range(dims[-1]): xc = x[:,:,c].flatten() if not np.all(np.absolute(xc - xc[0]) < eps): return False return True
[ "\n Test if a 3D (H,W,C) matrix x has the same element in each (H,W) matrix for each channel\n " ]
Please provide a description of the function:def convert_dense(builder, layer, input_names, output_names, keras_layer): # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.bias # Get the weights from keras W = keras_layer.get_weights ...
[ "Convert a dense layer from keras to coreml.\n\n Parameters\n keras_layer: layer\n ----------\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_activation(builder, layer, input_names, output_names, keras_layer): # Get input and output names input_name, output_name = (input_names[0], output_names[0]) non_linearity = _get_activation_name_from_keras_layer(keras_layer) # Add a non-linea...
[ "Convert an activation layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_padding(builder, layer, input_names, output_names, keras_layer): # Get input and output names input_name, output_name = (input_names[0], output_names[0]) if isinstance(keras_layer, keras.layers.convolutional.ZeroPadding1D): left, right =...
[ "Convert padding layer from keras to coreml.\n Keras only supports zero padding at this time.\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_cropping(builder, layer, input_names, output_names, keras_layer): # Get input and output names input_name, output_name = (input_names[0], output_names[0]) if isinstance(keras_layer, keras.layers.convolutional.Cropping1D): left, right = k...
[ "Convert padding layer from keras to coreml.\n Keras only supports zero padding at this time.\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_upsample(builder, layer, input_names, output_names, keras_layer): # Get input and output names input_name, output_name = (input_names[0], output_names[0]) if isinstance(keras_layer, keras.layers.convolutional.UpSampling1D): fh, fw = 1, k...
[ "Convert convolution layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_convolution(builder, layer, input_names, output_names, keras_layer): # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.bias is_deconv = isinstance(keras_layer, keras.layers.convol...
[ "Convert convolution layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_convolution1d(builder, layer, input_names, output_names, keras_layer): # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.bias # Get the weights from keras. # Keras stores con...
[ "Convert convolution layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_lstm(builder, layer, input_names, output_names, keras_layer): hidden_size = keras_layer.output_dim input_size = keras_layer.input_shape[-1] if keras_layer.consume_less not in ['cpu', 'gpu']: raise ValueError('Cannot convert Keras layer w...
[ "Convert an LSTM layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_simple_rnn(builder, layer, input_names, output_names, keras_layer): # Get input and output names hidden_size = keras_layer.output_dim input_size = keras_layer.input_shape[-1] output_all = keras_layer.return_sequences reverse_input = kera...
[ "Convert an SimpleRNN layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_gru(builder, layer, input_names, output_names, keras_layer): hidden_size = keras_layer.output_dim input_size = keras_layer.input_shape[-1] output_all = keras_layer.return_sequences reverse_input = keras_layer.go_backwards if keras_laye...
[ "Convert a GRU layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_bidirectional(builder, layer, input_names, output_names, keras_layer): input_size = keras_layer.input_shape[-1] lstm_layer = keras_layer.forward_layer if (type(lstm_layer) != keras.layers.recurrent.LSTM): raise TypeError('Bidirectional ...
[ "Convert a bidirectional layer from keras to coreml.\n Currently assumes the units are LSTMs.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_batchnorm(builder, layer, input_names, output_names, keras_layer): # Get input and output names input_name, output_name = (input_names[0], output_names[0]) # Currently CoreML supports only per-channel batch-norm if keras_layer.mode != 0: ...
[ "\n Parameters\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_flatten(builder, layer, input_names, output_names, keras_layer): input_name, output_name = (input_names[0], output_names[0]) # blob_order == 0 if the input blob needs not be rearranged # blob_order == 1 if the input blob needs to be rearranged ...
[ "Convert a flatten layer from keras to coreml.\n\n Parameters\n keras_layer: layer\n ----------\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_softmax(builder, layer, input_names, output_names, keras_layer): input_name, output_name = (input_names[0], output_names[0]) builder.add_softmax(name = layer, input_name = input_name, output_name = output_name)
[ "Convert a softmax layer from keras to coreml.\n\n Parameters\n keras_layer: layer\n ----------\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_permute(builder, layer, input_names, output_names, keras_layer): input_name, output_name = (input_names[0], output_names[0]) keras_dims = keras_layer.dims # Keras permute layer index begins at 1 if len(keras_dims) == 3: # Keras input...
[ "Convert a softmax layer from keras to coreml.\n\n Parameters\n keras_layer: layer\n ----------\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def sge_submit(nslave, worker_args, worker_envs): env_arg = ','.join(['%s=\"%s\"' % (k, str(v)) for k, v in worker_envs.items()]) cmd = 'qsub -cwd -t 1-%d -S /bin/bash' % nslave if args.queue != 'default': cmd += '-q %s' % args.queue cmd += ' -N ...
[ "\n customized submit script, that submit nslave jobs, each must contain args as parameter\n note this can be a lambda function containing additional parameters in input\n Parameters\n nslave number of slave process to start up\n args arguments to launch each job\n this u...
Please provide a description of the function:def dump_ast(ast, indent=' ', newline='\n'): ''' 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. ''' visitor = ASTPrinter(i...
[]
Please provide a description of the function:def print_ast(ast, indent=' ', initlevel=0, newline='\n', file=sys.stdout): ''' 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 newlin...
[]
Please provide a description of the function:def ctypes2numpy(cptr, length, dtype): if not isinstance(cptr, ctypes.POINTER(ctypes.c_float)): raise RuntimeError('expected float pointer') res = np.zeros(length, dtype=dtype) if not ctypes.memmove(res.ctypes.data, cptr, length * res.strides[0]): ...
[ "Convert a ctypes pointer array to a numpy array.\n " ]
Please provide a description of the function:def _maybe_from_pandas(data, feature_names, feature_types): try: import pandas as pd except ImportError: return data, feature_names, feature_types if not isinstance(data, pd.DataFrame): return data, feature_names, feature_types ...
[ " Extract internal data from pd.DataFrame " ]
Please provide a description of the function:def _init_from_csr(self, csr): 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() _check_call(_LIB.XGDMatrixCreateFromCSR(c_a...
[ "\n Initialize data from a CSR matrix.\n " ]
Please provide a description of the function:def _init_from_csc(self, csc): 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() _check_call(_LIB.XGDMatrixCreateFromCSC(c_a...
[ "\n Initialize data from a CSC matrix.\n " ]
Please provide a description of the function:def _init_from_npy2d(self, mat, missing): if len(mat.shape) != 2: raise ValueError('Input numpy.ndarray must be 2 dimensional') data = np.array(mat.reshape(mat.size), dtype=np.float32) self.handle = ctypes.c_void_p() _chec...
[ "\n Initialize data from a 2-D numpy matrix.\n " ]
Please provide a description of the function:def get_float_info(self, field): length = ctypes.c_ulong() ret = ctypes.POINTER(ctypes.c_float)() _check_call(_LIB.XGDMatrixGetFloatInfo(self.handle, c_str(field), ...
[ "Get float property from the DMatrix.\n\n Parameters\n ----------\n field: str\n The field name of the information\n\n Returns\n -------\n info : array\n a numpy array of float information of the data\n " ]
Please provide a description of the function:def get_uint_info(self, field): length = ctypes.c_ulong() ret = ctypes.POINTER(ctypes.c_uint)() _check_call(_LIB.XGDMatrixGetUIntInfo(self.handle, c_str(field), ...
[ "Get unsigned integer property from the DMatrix.\n\n Parameters\n ----------\n field: str\n The field name of the information\n\n Returns\n -------\n info : array\n a numpy array of float information of the data\n " ]
Please provide a description of the function:def set_float_info(self, field, data): _check_call(_LIB.XGDMatrixSetFloatInfo(self.handle, c_str(field), c_array(ctypes.c_float, data), ...
[ "Set float type property into the DMatrix.\n\n Parameters\n ----------\n field: str\n The field name of the information\n\n data: numpy array\n The array ofdata to be set\n " ]
Please provide a description of the function:def set_uint_info(self, field, data): _check_call(_LIB.XGDMatrixSetUIntInfo(self.handle, c_str(field), c_array(ctypes.c_uint, data), ...
[ "Set uint type property into the DMatrix.\n\n Parameters\n ----------\n field: str\n The field name of the information\n\n data: numpy array\n The array ofdata to be set\n " ]
Please provide a description of the function:def save_binary(self, fname, silent=True): _check_call(_LIB.XGDMatrixSaveBinary(self.handle, c_str(fname), int(silent)))
[ "Save DMatrix to an XGBoost buffer.\n\n Parameters\n ----------\n fname : string\n Name of the output buffer file.\n silent : bool (optional; default: True)\n If set, the output is suppressed.\n " ]
Please provide a description of the function:def num_row(self): ret = ctypes.c_ulong() _check_call(_LIB.XGDMatrixNumRow(self.handle, ctypes.byref(ret))) return ret.value
[ "Get the number of rows in the DMatrix.\n\n Returns\n -------\n number of rows : int\n " ]
Please provide a description of the function:def num_col(self): ret = ctypes.c_uint() _check_call(_LIB.XGDMatrixNumCol(self.handle, ctypes.byref(ret))) return ret.value
[ "Get the number of columns (features) in the DMatrix.\n\n Returns\n -------\n number of columns : int\n " ]
Please provide a description of the function:def slice(self, rindex): res = DMatrix(None, feature_names=self.feature_names) res.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixSliceDMatrix(self.handle, c_array(ctypes.c_int, rindex), ...
[ "Slice the DMatrix and return a new DMatrix that only contains `rindex`.\n\n Parameters\n ----------\n rindex : list\n List of indices to be selected.\n\n Returns\n -------\n res : DMatrix\n A new DMatrix containing only selected indices.\n " ]
Please provide a description of the function:def feature_names(self, feature_names): if not feature_names is None: # validate feature name if not isinstance(feature_names, list): feature_names = list(feature_names) if len(feature_names) != len(set(fea...
[ "Set feature names (column labels).\n\n Parameters\n ----------\n feature_names : list or None\n Labels for features. None will reset existing feature names\n " ]
Please provide a description of the function:def feature_types(self, feature_types): if not feature_types is None: if self.feature_names is None: msg = 'Unable to set feature types before setting names' raise ValueError(msg) if isinstance(featur...
[ "Set feature types (column types).\n\n This is for displaying the results and unrelated\n to the learning process.\n\n Parameters\n ----------\n feature_types : list or None\n Labels for features. None will reset existing feature names\n " ]
Please provide a description of the function:def update(self, dtrain, iteration, fobj=None): if not isinstance(dtrain, DMatrix): raise TypeError('invalid training matrix: {}'.format(type(dtrain).__name__)) self._validate_features(dtrain) if fobj is None: _check_...
[ "\n Update for one iteration, with objective function calculated internally.\n\n Parameters\n ----------\n dtrain : DMatrix\n Training data.\n iteration : int\n Current iteration number.\n fobj : function\n Customized objective function.\n ...
Please provide a description of the function:def boost(self, dtrain, grad, hess): if len(grad) != len(hess): raise ValueError('grad / hess length mismatch: {} / {}'.format(len(grad), len(hess))) if not isinstance(dtrain, DMatrix): raise TypeError('invalid training matrix...
[ "\n Boost the booster for one iteration, with customized gradient statistics.\n\n Parameters\n ----------\n dtrain : DMatrix\n The training DMatrix.\n grad : list\n The first order of gradient.\n hess : list\n The second order of gradient.\n...
Please provide a description of the function:def eval_set(self, evals, iteration=0, feval=None): # pylint: disable=invalid-name if feval is None: for d in evals: if not isinstance(d[0], DMatrix): raise TypeError('expected DMatrix, got {}'.format(t...
[ "Evaluate a set of data.\n\n Parameters\n ----------\n evals : list of tuples (DMatrix, string)\n List of items to be evaluated.\n iteration : int\n Current iteration.\n feval : function\n Custom evaluation function.\n\n Returns\n --...
Please provide a description of the function:def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False): option_mask = 0x00 if output_margin: option_mask |= 0x01 if pred_leaf: option_mask |= 0x02 self._validate_features(data) l...
[ "\n Predict with data.\n\n NOTE: This function is not thread safe.\n For each booster object, predict can only be called from one thread.\n If you want to run prediction using multiple thread, call bst.copy() to make copies\n of model object and then call predict...
Please provide a description of the function:def save_raw(self): length = ctypes.c_ulong() cptr = ctypes.POINTER(ctypes.c_char)() _check_call(_LIB.XGBoosterGetModelRaw(self.handle, ctypes.byref(length), ...
[ "\n Save the model to a in memory buffer represetation\n\n Returns\n -------\n a in memory buffer represetation of the model\n " ]
Please provide a description of the function:def load_model(self, fname): if isinstance(fname, STRING_TYPES): # assume file name if os.path.exists(fname): _LIB.XGBoosterLoadModel(self.handle, c_str(fname)) else: raise ValueError("No such file: {0...
[ "\n Load the model from a file.\n\n Parameters\n ----------\n fname : string or a memory buffer\n Input file name or memory buffer(see also save_raw)\n " ]
Please provide a description of the function:def dump_model(self, fout, fmap='', with_stats=False): if isinstance(fout, STRING_TYPES): fout = open(fout, 'w') need_close = True else: need_close = False ret = self.get_dump(fmap, with_stats) for ...
[ "\n Dump model into a text file.\n\n Parameters\n ----------\n foout : string\n Output file name.\n fmap : string, optional\n Name of the file containing feature map names.\n with_stats : bool (optional)\n Controls whether the split statisti...
Please provide a description of the function:def get_dump(self, fmap='', with_stats=False): length = ctypes.c_ulong() sarr = ctypes.POINTER(ctypes.c_char_p)() if self.feature_names is not None and fmap == '': flen = int(len(self.feature_names)) fname = from_pys...
[ "\n Returns the dump the model as a list of strings.\n " ]
Please provide a description of the function:def get_fscore(self, fmap=''): trees = self.get_dump(fmap) fmap = {} for tree in trees: for line in tree.split('\n'): arr = line.split('[') if len(arr) == 1: continue ...
[ "Get feature importance of each feature.\n\n Parameters\n ----------\n fmap: str (optional)\n The name of feature map file\n " ]
Please provide a description of the function:def _validate_features(self, data): if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_types else: # Booster can't accept data with different feature names ...
[ "\n Validate Booster and data's feature_names are identical.\n Set feature_names and feature_types from DMatrix\n " ]
Please provide a description of the function:def disassembler(co, lasti= -1): code = co.co_code labels = dis.findlabels(code) linestarts = dict(dis.findlinestarts(co)) i = 0 extended_arg = 0 lineno = 0 free = None for i, op, oparg in _walk_ops(co): if i in linestarts: ...
[ "Disassemble a code object. \n \n :param co: code object\n :param lasti: internal\n :yields: Instructions.\n \n " ]
Please provide a description of the function:def transform (list, pattern, indices = [1]): result = [] for e in list: m = re.match (pattern, e) if m: for i in indices: result.append (m.group (i)) return result
[ " Matches all elements of 'list' agains the 'pattern'\n and returns a list of the elements indicated by indices of\n all successfull matches. If 'indices' is omitted returns\n a list of first paranthethised groups of all successfull\n matches.\n " ]
Please provide a description of the function:def replace(s, pattern, replacement): # the replacement string may contain invalid backreferences (like \1 or \g) # which will cause python's regex to blow up. Since this should emulate # the jam version exactly and the jam version didn't support # backr...
[ "Replaces occurrences of a match string in a given\n string and returns the new string. The match string\n can be a regex expression.\n\n Args:\n s (str): the string to modify\n pattern (str): the search expression\n replacement (str): the string to replace each match wit...
Please provide a description of the function:def replace_list(items, match, replacement): return [replace(item, match, replacement) for item in items]
[ "Replaces occurrences of a match string in a given list of strings and returns\n a list of new strings. The match string can be a regex expression.\n\n Args:\n items (list): the list of strings to modify.\n match (str): the search expression.\n replacement (str): the string ...
Please provide a description of the function:def create(dataset, num_topics=10, initial_topics=None, alpha=None, beta=.1, num_iterations=10, num_burnin=5, associations=None, verbose=False, print_interval=10, va...
[ "\n Create a topic model from the given data set. A topic model assumes each\n document is a mixture of a set of topics, where for each topic some words\n are more likely than others. One statistical approach to do this is called a\n \"topic model\". This method learns a topic model for the given docume...
Please provide a description of the function:def perplexity(test_data, predictions, topics, vocabulary): test_data = _check_input(test_data) assert isinstance(predictions, _SArray), \ "Predictions must be an SArray of vector type." assert predictions.dtype == _array.array, \ "Prediction...
[ "\n Compute the perplexity of a set of test documents given a set\n of predicted topics.\n\n Let theta be the matrix of document-topic probabilities, where\n theta_ik = p(topic k | document i). Let Phi be the matrix of term-topic\n probabilities, where phi_jk = p(word j | topic k).\n\n Then for ea...
Please provide a description of the function:def _get_summary_struct(self): section_titles=['Schema','Settings'] vocab_length = len(self.vocabulary) verbose = self.verbose == 1 sections=[ [ ('Vocabulary Size',_precomputed_field(vocab...
[ "\n Returns a structured description of the model, including (where relevant)\n the schema of the training data, description of the training data,\n training statistics, and model hyperparameters.\n\n Returns\n -------\n sections : list (of list of tuples)\n A li...
Please provide a description of the function:def _get(self, field): opts = {'model': self.__proxy__, 'field': field} response = _turicreate.extensions._text.topicmodel_get_value(opts) return response['value']
[ "\n Return the value of a given field. The list of all queryable fields is\n detailed below, and can be obtained with the\n :py:func:`~TopicModel._list_fields` method.\n\n +-----------------------+----------------------------------------------+\n | Field | Descript...
Please provide a description of the function:def _training_stats(self): fields = self._list_fields() stat_fields = ['training_time', 'training_iterations'] if 'validation_perplexity' in fields: stat_fields.append('validation_perplexity') ret ...
[ "\n Return a dictionary of statistics collected during creation of the\n model. These statistics are also available with the ``get`` method and\n are described in more detail in that method's documentation.\n\n Returns\n -------\n out : dict\n Dictionary of stati...
Please provide a description of the function:def get_topics(self, topic_ids=None, num_words=5, cdf_cutoff=1.0, output_type='topic_probabilities'): _check_categorical_option_type('output_type', output_type, ['topic_probabilities', 'topic_words']) if topic_ids is ...
[ "\n Get the words associated with a given topic. The score column is the\n probability of choosing that word given that you have chosen a\n particular topic.\n\n Parameters\n ----------\n topic_ids : list of int, optional\n The topics to retrieve words. Topic ids...
Please provide a description of the function:def predict(self, dataset, output_type='assignment', num_burnin=None): dataset = _check_input(dataset) if num_burnin is None: num_burnin = self.num_burnin opts = {'model': self.__proxy__, 'data': dataset, ...
[ "\n Use the model to predict topics for each document. The provided\n `dataset` should be an SArray object where each element is a dict\n representing a single document in bag-of-words format, where keys\n are words and values are their corresponding counts. If `dataset` is\n an S...
Please provide a description of the function:def evaluate(self, train_data, test_data=None, metric='perplexity'): train_data = _check_input(train_data) if test_data is None: test_data = train_data else: test_data = _check_input(test_data) predictions = ...
[ "\n Estimate the model's ability to predict new data. Imagine you have a\n corpus of books. One common approach to evaluating topic models is to\n train on the first half of all of the books and see how well the model\n predicts the second half of each book.\n\n This method return...
Please provide a description of the function:def bbox_to_ybox(bbox): return [ (bbox[1] + bbox[3]) / 2, (bbox[0] + bbox[2]) / 2, (bbox[3] - bbox[1]), (bbox[2] - bbox[0]), ]
[ "Convert from corner bounding box to center/shape" ]
Please provide a description of the function:def _raise_error_if_not_drawing_classifier_input_sframe( dataset, feature, target): from turicreate.toolkits._internal_utils import _raise_error_if_not_sframe _raise_error_if_not_sframe(dataset) if feature not in dataset.column_names(): raise _To...
[ "\n Performs some sanity checks on the SFrame provided as input to \n `turicreate.drawing_classifier.create` and raises a ToolkitError\n if something in the dataset is missing or wrong.\n " ]
Please provide a description of the function:def create(input_dataset, target, feature=None, validation_set='auto', warm_start='auto', batch_size=256, max_iterations=100, verbose=True): import mxnet as _mx from mxnet import autograd as _autograd from ._model_architecture i...
[ "\n Create a :class:`DrawingClassifier` model.\n\n Parameters\n ----------\n dataset : SFrame\n Input data. The columns named by the ``feature`` and ``target``\n parameters will be extracted for training the drawing classifier.\n\n target : string\n Name of the column containing ...
Please provide a description of the function:def export_coreml(self, filename, verbose=False): import mxnet as _mx from .._mxnet._mxnet_to_coreml import _mxnet_converter import coremltools as _coremltools batch_size = 1 image_shape = (batch_size,) + (1, BITMAP_WIDTH, BI...
[ "\n Save the model in Core ML format. The Core ML model takes a grayscale \n drawing of fixed size as input and produces two outputs: \n `classLabel` and `labelProbabilities`.\n\n The first one, `classLabel` is an integer or string (depending on the\n classes the model was trained...
Please provide a description of the function:def _predict_with_probabilities(self, input_dataset, batch_size=None, verbose=True): from .._mxnet import _mxnet_utils import mxnet as _mx from ._sframe_loader import SFrameClassifierIter as _SFrameClassifierIter is_stroke_...
[ "\n Predict with probabilities. The core prediction part that both \n `evaluate` and `predict` share.\n\n Returns an SFrame with two columns, self.target, and \"probabilities\".\n\n The column with column name, self.target, contains the predictions made\n by the model for the prov...
Please provide a description of the function:def evaluate(self, dataset, metric='auto', batch_size=None, verbose=True): if self.target not in dataset.column_names(): raise _ToolkitError("Must provide ground truth column, '" + self.target + "' in the evaluation dataset.") ...
[ "\n Evaluate the model by making predictions of target values and comparing\n these to actual values.\n \n Parameters\n ----------\n dataset : SFrame\n Dataset of new observations. Must include columns with the same\n names as the feature and target co...
Please provide a description of the function:def predict_topk(self, dataset, output_type="probability", k=3, batch_size=None): _tkutl._check_categorical_option_type("output_type", output_type, ["probability", "rank"]) if not isinstance(k, int): raise T...
[ "\n Return top-k predictions for the ``dataset``, using the trained model.\n Predictions are returned as an SFrame with three columns: `id`,\n `class`, and `probability` or `rank`, depending on the ``output_type``\n parameter.\n\n Parameters\n ----------\n dataset : ...
Please provide a description of the function:def predict(self, data, output_type='class', batch_size=None, verbose=True): _tkutl._check_categorical_option_type("output_type", output_type, ["probability", "class", "probability_vector"]) if isinstance(data, _tc.SArray): p...
[ "\n Predict on an SFrame or SArray of drawings, or on a single drawing.\n\n Parameters\n ----------\n data : SFrame | SArray | tc.Image | list\n The drawing(s) on which to perform drawing classification.\n If dataset is an SFrame, it must have a column with the same...
Please provide a description of the function:def extract_features(self, dataset, feature, batch_size=64, verbose=False): from ._mxnet._mx_sframe_iter import SFrameImageIter as _SFrameImageIter from six.moves.queue import Queue as _Queue from threading import Thread as _Thread im...
[ "\n Parameters\n ----------\n dataset: SFrame\n SFrame of images\n " ]
Please provide a description of the function:def get_coreml_model(self, mode = 'classifier'): import mxnet as _mx from ._mxnet import _mxnet_utils from ._mxnet._mxnet_to_coreml import _mxnet_converter (sym, arg_params, aux_params) = self.ptModel.mxmodel fe_mxmodel = sel...
[ "\n Parameters\n ----------\n mode: str ('classifier', 'regressor' or None)\n Mode of the converted coreml model.\n When mode = 'classifier', a NeuralNetworkClassifier spec will be constructed.\n When mode = 'regressor', a NeuralNetworkRegressor spec will be con...
Please provide a description of the function:def available_parameters_subset(self, mx_params): from copy import copy from collections import OrderedDict subset_params = copy(mx_params) subset_params._params = OrderedDict([ (k, v) for k, v in mx_params.items() if k in...
[ "\n Takes an mxnet parameter collect (from Block.collect_params()) and\n subsets it with the parameters available in this base network.\n " ]
Please provide a description of the function:def _BOW_FEATURE_EXTRACTOR(sf, target=None): if isinstance(sf, dict): out = _tc.SArray([sf]).unpack('') elif isinstance(sf, _tc.SFrame): out = sf.__copy__() else: raise ValueError("Unrecognized input to feature extractor.") for f ...
[ "\n Return an SFrame containing a bag of words representation of each column.\n " ]
Please provide a description of the function:def create(dataset, target, features = None, drop_stop_words = True, word_count_threshold = 2, method = 'auto', validation_set = 'auto', max_iterations = 10): _raise_error_if_not_sframe(dataset, "dataset") # Validate method. if method ...
[ "\n Create a model that trains a classifier to classify text from a\n collection of documents. The model is a\n :class:`~turicreate.logistic_classifier.LogisticClassifier` model trained\n using a bag-of-words representation of the text dataset.\n\n Parameters\n ----------\n dataset : SFrame\n ...
Please provide a description of the function:def _get_str_columns(sf): return [name for name in sf.column_names() if sf[name].dtype == str]
[ "\n Returns a list of names of columns that are string type.\n " ]
Please provide a description of the function:def predict(self, dataset, output_type='class'): m = self.__proxy__['classifier'] target = self.__proxy__['target'] f = _BOW_FEATURE_EXTRACTOR return m.predict(f(dataset, target), output_type=output_type)
[ "\n Return predictions for ``dataset``, using the trained model.\n\n Parameters\n ----------\n dataset : SFrame\n dataset of new observations. Must include columns with the same\n names as the features used for model training, but does not require\n a tar...
Please provide a description of the function:def classify(self, dataset): m = self.__proxy__['classifier'] target = self.__proxy__['target'] f = _BOW_FEATURE_EXTRACTOR return m.classify(f(dataset, target))
[ "\n Return a classification, for each example in the ``dataset``, using the\n trained model. The output SFrame contains predictions as both class\n labels as well as probabilities that the predicted value is the\n associated label.\n\n Parameters\n ----------\n datas...
Please provide a description of the function:def evaluate(self, dataset, metric='auto', **kwargs): m = self.__proxy__['classifier'] target = self.__proxy__['target'] f = _BOW_FEATURE_EXTRACTOR test = f(dataset, target) return m.evaluate(test, metric, **kwargs)
[ "\n Evaluate the model by making predictions of target values and comparing\n these to actual values.\n\n Parameters\n ----------\n dataset : SFrame\n An SFrame having the same feature columns as provided when creating\n the model.\n\n metric : str, op...
Please provide a description of the function:def _generate_base_svm_regression_spec(model): if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') spec = _Model_pb2.Model() spec.specificationVersion = SPECIFICATION_VERSION svm = spec.su...
[ "\n Takes an SVM regression model produces a starting spec using the parts.\n that are shared between all SVMs.\n " ]
Please provide a description of the function:def convert(model, features, target): spec = _generate_base_svm_regression_spec(model) spec = set_regressor_interface_params(spec, features, target) return _MLModel(spec)
[ "Convert a Support Vector Regressor (SVR) model to the protobuf spec.\n Parameters\n ----------\n model: SVR\n A trained SVR encoder model.\n\n feature_names: [str]\n Name of the input columns.\n\n target: str\n Name of the output column.\n\n Returns\n -------\n model_sp...
Please provide a description of the function:def _VerifyExtensionHandle(message, extension_handle): if not isinstance(extension_handle, _FieldDescriptor): raise KeyError('HasExtension() expects an extension handle, got: %s' % extension_handle) if not extension_handle.is_extension: ra...
[ "Verify that the given extension handle is valid." ]
Please provide a description of the function:def _AddEnumValues(descriptor, cls): for enum_type in descriptor.enum_types: setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type)) for enum_value in enum_type.values: setattr(cls, enum_value.name, enum_value.number)
[ "Sets class-level attributes for all enum fields defined in this message.\n\n Also exporting a class-level object that can name enum values.\n\n Args:\n descriptor: Descriptor object for this message type.\n cls: Class we're constructing for this message type.\n " ]
Please provide a description of the function:def _DefaultValueConstructorForField(field): if _IsMapField(field): return _GetInitializeDefaultForMap(field) if field.label == _FieldDescriptor.LABEL_REPEATED: if field.has_default_value and field.default_value != []: raise ValueError('Repeated field ...
[ "Returns a function which returns a default value for a field.\n\n Args:\n field: FieldDescriptor object for this field.\n\n The returned function has one argument:\n message: Message instance containing this field, or a weakref proxy\n of same.\n\n That function in turn returns a default value for th...
Please provide a description of the function:def _ReraiseTypeErrorWithFieldName(message_name, field_name): exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (str(exc), message_name, fiel...
[ "Re-raise the currently-handled TypeError with the field name added." ]
Please provide a description of the function:def _AddInitMethod(message_descriptor, cls): def _GetIntegerEnumValue(enum_type, value): if isinstance(value, six.string_types): try: return enum_type.values_by_name[value].number except KeyError: raise ValueError('Enum type %s: unk...
[ "Adds an __init__ method to cls.", "Convert a string or integer enum value to an integer.\n\n If the value is a string, it is converted to the enum value in\n enum_type with the same name. If the value is not a string, it's\n returned as-is. (No conversion or bounds-checking is done.)\n " ]
Please provide a description of the function:def _GetFieldByName(message_descriptor, field_name): try: return message_descriptor.fields_by_name[field_name] except KeyError: raise ValueError('Protocol message %s has no "%s" field.' % (message_descriptor.name, field_name))
[ "Returns a field descriptor by field name.\n\n Args:\n message_descriptor: A Descriptor describing all fields in message.\n field_name: The name of the field to retrieve.\n Returns:\n The field descriptor associated with the field name.\n " ]
Please provide a description of the function:def _AddPropertiesForFields(descriptor, cls): for field in descriptor.fields: _AddPropertiesForField(field, cls) if descriptor.is_extendable: # _ExtensionDict is just an adaptor with no state so we allocate a new one # every time it is accessed. cls.E...
[ "Adds properties for all fields in this protocol message type." ]
Please provide a description of the function:def _AddPropertiesForField(field, cls): # Catch it if we add other types that we should # handle specially here. assert _FieldDescriptor.MAX_CPPTYPE == 10 constant_name = field.name.upper() + "_FIELD_NUMBER" setattr(cls, constant_name, field.number) if field...
[ "Adds a public property for a protocol message field.\n Clients can use this property to get and (in the case\n of non-repeated scalar fields) directly set the value\n of a protocol message field.\n\n Args:\n field: A FieldDescriptor for this field.\n cls: The class we're constructing.\n " ]
Please provide a description of the function:def _AddPropertiesForRepeatedField(field, cls): proto_field_name = field.name property_name = _PropertyName(proto_field_name) def getter(self): field_value = self._fields.get(field) if field_value is None: # Construct a new object to represent this fi...
[ "Adds a public property for a \"repeated\" protocol message field. Clients\n can use this property to get the value of the field, which will be either a\n _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see\n below).\n\n Note that when clients add values to these containers, we perform\n ty...
Please provide a description of the function:def _AddPropertiesForNonRepeatedScalarField(field, cls): proto_field_name = field.name property_name = _PropertyName(proto_field_name) type_checker = type_checkers.GetTypeChecker(field) default_value = field.default_value valid_values = set() is_proto3 = field...
[ "Adds a public property for a nonrepeated, scalar protocol message field.\n Clients can use this property to get and directly set the value of the field.\n Note that when the client sets the value of a field by using this property,\n all necessary \"has\" bits are set as a side-effect, and we also perform\n typ...
Please provide a description of the function:def _AddPropertiesForExtensions(descriptor, cls): extension_dict = descriptor.extensions_by_name for extension_name, extension_field in extension_dict.items(): constant_name = extension_name.upper() + "_FIELD_NUMBER" setattr(cls, constant_name, extension_field...
[ "Adds properties for all fields in this protocol message type." ]
Please provide a description of the function:def _IsPresent(item): if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return item[1]._is_present_in_parent else: return True
[ "Given a (FieldDescriptor, value) tuple from _fields, return true if the\n value should be included in the list returned by ListFields()." ]
Please provide a description of the function:def _AddListFieldsMethod(message_descriptor, cls): 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.ListFields = ListFields
[ "Helper for _AddMessageMethods()." ]
Please provide a description of the function:def _AddHasFieldMethod(message_descriptor, cls): is_proto3 = (message_descriptor.syntax == "proto3") error_msg = _Proto3HasError if is_proto3 else _Proto2HasError hassable_fields = {} for field in message_descriptor.fields: if field.label == _FieldDescriptor...
[ "Helper for _AddMessageMethods()." ]
Please provide a description of the function:def _AddClearFieldMethod(message_descriptor, cls): def ClearField(self, field_name): try: field = message_descriptor.fields_by_name[field_name] except KeyError: try: field = message_descriptor.oneofs_by_name[field_name] if field in se...
[ "Helper for _AddMessageMethods()." ]