text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def abbreviate_dashed(s): """Abbreviates each part of string that is delimited by a '-'."""
r = [] for part in s.split('-'): r.append(abbreviate(part)) return '-'.join(r)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def abbreviate(s): """Apply a set of standard transformations to string to produce an abbreviation no more than 4 characters long. """
if not s: return '' # check the cache if s in abbreviate.abbreviations: return abbreviate.abbreviations[s] # anything less than 4 characters doesn't need # an abbreviation if len(s) < 4: # update cache abbreviate.abbreviations[s] = s return s # save t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_decision(self, child, is_missing = False): """ Get the decision from this node to a child node. Parameters child: Node A child node of this node. Returns...
# Child does exist and there is a path to the child. value = self.value feature = self.split_feature_column index = self.split_feature_index if not is_missing: if self.left_id == child.node_id: if self.node_type in ["float", "integer"]: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ Return the node as a dictionary. Returns ------- dict: All the attributes of this node as a dictionary (minus the left and right). """
out = {} for key in self.__dict__.keys(): if key not in ['left', 'right', 'missing', 'parent']: out[key] = self.__dict__[key] return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self, root_id = 0, output = {}): """ Recursive function to dump this tree as a json blob. Parameters root_id: Root id of the sub-tree output: Carry o...
_raise_error_if_not_of_type(root_id, [int,long], "root_id") _numeric_param_check_range("root_id", root_id, 0, self.num_nodes - 1) node = self.nodes[root_id] output = node.to_dict() if node.left_id is not None: j = node.left_id output['left'] = self.to_js...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_prediction_path(self, node_id, missing_id = []): """ Return the prediction path from this node to the parent node. Parameters node_id : id of the node to...
_raise_error_if_not_of_type(node_id, [int,long], "node_id") _numeric_param_check_range("node_id", node_id, 0, self.num_nodes - 1) def _deduplicate_path(path): s_nodes = {} # super_nodes s_path = [] # paths of super nodes. for node in path: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(graph, label_field, threshold=1e-3, weight_field='', self_weight=1.0, undirected=False, max_iterations=None, _single_precision=False, _distributed='aut...
from turicreate._cython.cy_server import QuietProgress _raise_error_if_not_of_type(label_field, str) _raise_error_if_not_of_type(weight_field, str) if not isinstance(graph, _SGraph): raise TypeError('graph input must be a SGraph object.') if graph.vertices[label_field].dtype != int: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_not_pickle_safe_gl_model_class(obj_class): """ Check if a Turi create model is pickle safe. The function does it by checking that _CustomModel is the bas...
if issubclass(obj_class, _toolkits._model.CustomModel): return not obj_class._is_gl_pickle_safe() return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_not_pickle_safe_gl_class(obj_class): """ Check if class is a Turi create model. The function does it by checking the method resolution order (MRO) of the...
gl_ds = [_SFrame, _SArray, _SGraph] # Object is GLC-DS or GLC-Model return (obj_class in gl_ds) or _is_not_pickle_safe_gl_model_class(obj_class)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_gl_class_type(obj_class): """ Internal util to get the type of the GLC class. The pickle file stores this name so that it knows how to construct the obj...
if obj_class == _SFrame: return "SFrame" elif obj_class == _SGraph: return "SGraph" elif obj_class == _SArray: return "SArray" elif _is_not_pickle_safe_gl_model_class(obj_class): return "Model" else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_gl_object_from_persistent_id(type_tag, gl_archive_abs_path): """ Internal util to get a GLC object from a persistent ID in the pickle file. Parameters t...
if type_tag == "SFrame": obj = _SFrame(gl_archive_abs_path) elif type_tag == "SGraph": obj = _load_graph(gl_archive_abs_path) elif type_tag == "SArray": obj = _SArray(gl_archive_abs_path) elif type_tag == "Model": from . import load_model as _load_model obj = _lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def persistent_id(self, obj): """ Provide a persistent ID for "saving" GLC objects by reference. Return None for all non GLC objects. Parameters obj: Name of the...
# Get the class of the object (if it can be done) obj_class = None if not hasattr(obj, '__class__') else obj.__class__ if obj_class is None: return None # If the object is a GLC class. if _is_not_pickle_safe_gl_class(obj_class): if (id(obj) in self.gl_o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Close the pickle file, and the zip archive file. The single zip archive file can now be shipped around to be loaded by the unpickler. """
if self.file is None: return # Close the pickle file. self.file.close() self.file = None for f in self.mark_for_delete: error = [False] def register_error(*args): error[0] = True _shutil.rmtree(f, onerror = regi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def persistent_load(self, pid): """ Reconstruct a GLC object using the persistent ID. This method should not be used externally. It is required by the unpickler ...
if len(pid) == 2: # Pre GLC-1.3 release behavior, without memorization type_tag, filename = pid abs_path = _os.path.join(self.gl_temp_storage_path, filename) return _get_gl_object_from_persistent_id(type_tag, abs_path) else: # Post GLC-1.3 re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Clean up files that were created. """
if self.file: self.file.close() self.file = None # If temp_file is a folder, we do not remove it because we may # still need it after the unpickler is disposed if self.tmp_file and _os.path.isfile(self.tmp_file): _os.remove(self.tmp_file) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(sk_obj, input_features = None, output_feature_names = None): """ Convert scikit-learn pipeline, classifier, or regressor to Core ML format. Parameter...
# This function is just a thin wrapper around the internal converter so # that sklearn isn't actually imported unless this function is called from ...models import MLModel # NOTE: Providing user-defined class labels will be enabled when # several issues with the ordering of the classes are worked...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ParseMessage(descriptor, byte_str): """Generate a new Message instance from this Descriptor and a byte string. Args: descriptor: Protobuf Descriptor object b...
result_class = MakeClass(descriptor) new_msg = result_class() new_msg.ParseFromString(byte_str) return new_msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def MakeClass(descriptor): """Construct a class object for a protobuf described by descriptor. Composite descriptors are handled by defining the new class as a m...
if descriptor in MESSAGE_CLASS_CACHE: return MESSAGE_CLASS_CACHE[descriptor] attributes = {} for name, nested_type in descriptor.nested_types_by_name.items(): attributes[name] = MakeClass(nested_type) attributes[GeneratedProtocolMessageType._DESCRIPTOR_KEY] = descriptor result = GeneratedProtocolM...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_images(url, format='auto', with_path=True, recursive=True, ignore_failure=True, random_order=False): """ Loads images from a directory. JPEG and PNG ima...
from ... import extensions as _extensions from ...util import _make_internal_url return _extensions.load_images(url, format, with_path, recursive, ignore_failure, random_order)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode(image_data): """ Internal helper function for decoding a single Image or an SArray of Images """
from ...data_structures.sarray import SArray as _SArray from ... import extensions as _extensions if type(image_data) is _SArray: return _extensions.decode_image_sarray(image_data) elif type(image_data) is _Image: return _extensions.decode_image(image_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resize(image, width, height, channels=None, decode=False, resample='nearest'): """ Resizes the image or SArray of Images to a specific width, height, and num...
if height < 0 or width < 0: raise ValueError("Cannot resize to negative sizes") if resample == 'nearest': resample_method = 0 elif resample == 'bilinear': resample_method = 1 else: raise ValueError("Unknown resample option: '%s'" % resample) from ...data_structure...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_1bit_array_to_byte_array(arr): """ Convert bit array to byte array. :param arr: list Bits as a list where each element is an integer of 0 or 1 Retur...
# Padding if necessary while len(arr) < 8 or len(arr) % 8: arr.append(0) arr = _np.array(arr, dtype='uint8') bit_arr = [] idx = 0 # Iterate and combine 8-bits into a uint8 for arr_idx in range(int(len(arr) / 8)): bit_arr.append(((arr[idx] << 7) & (1 << 7)) | ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decompose_bytes_to_bit_arr(arr): """ Unpack bytes to bits :param arr: list Byte Stream, as a list of uint8 values Returns ------- bit_arr: list Decomposed b...
bit_arr = [] for idx in range(len(arr)): for i in reversed(range(8)): bit_arr.append((arr[idx] >> i) & (1 << 0)) return bit_arr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_linear_lookup_table_and_weight(nbits, wp): """ Generate a linear lookup table. :param nbits: int Number of bits to represent a quantized weight value :p...
w = wp.reshape(1, -1) qw, scales, biases = _quantize_channelwise_linear(w, nbits, axis=0) indices = _np.array(range(0, 2**nbits)) lookup_table = indices * scales[0] + biases[0] return lookup_table, qw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_kmeans_lookup_table_and_weight(nbits, w, init='k-means++', tol=1e-2, n_init=1, rand_seed=0): """ Generate K-Means lookup table given a weight parameter ...
if _HAS_SKLEARN: from sklearn.cluster import KMeans else: raise Exception('sklearn package required for k-means quantization') units = _np.prod(w.shape) lut_len = 1 << nbits n_clusters = units if (units < lut_len) else lut_len wf = w.reshape(-1, 1) kmeans = KMeans(n_clusters...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _quantize_channelwise_linear(weight, nbits, axis=0): """ Linearly quantize weight blob. :param weight: numpy.array Weight to be quantized. :param nbits: int ...
if len(weight.shape) == 1: # vector situation, treat as 1 channel weight = weight.reshape((1, weight.shape[0])) rank = len(weight.shape) if axis == 1: transposed_axis_order = (1,0) + tuple(range(2,rank)) weight = _np.transpose(weight, transposed_axis_order) num_channels = weig...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _quantize_wp(wp, nbits, qm, axis=0, **kwargs): """ Quantize the weight blob :param wp: numpy.array Weight parameters :param nbits: int Number of bits :param ...
scale = bias = lut = None # Linear Quantization if qm == _QUANTIZATION_MODE_LINEAR_QUANTIZATION: qw, scale, bias = _quantize_channelwise_linear(wp, nbits, axis) # Lookup tables elif qm == _QUANTIZATION_MODE_LOOKUP_TABLE_KMEANS: lut, qw = _get_kmeans_lookup_table_and_weight(nbits, w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _quantize_wp_field(wp, nbits, qm, shape, axis=0, **kwargs): """ Quantize WeightParam field in Neural Network Protobuf :param wp: MLModel.NeuralNetwork.Weight...
# De-quantization if qm == _QUANTIZATION_MODE_DEQUANTIZE: return _dequantize_wp(wp, shape, axis) # If the float32 field is empty do nothing and return if len(wp.floatValue) == 0: return # Half precision (16-bit) quantization if nbits == 16: return _wp_to_fp16wp(wp) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_models(full_precision_model, quantized_model, sample_data): """ Utility function to compare the performance of a full precision vs quantized model :p...
emessage = (""" Invalid sample data provided. Only a list of dictionaries containing sample data or path to a folder containing images is supported""") spec = full_precision_model.get_spec() num_inputs = len(spec.description.input) if isinstance(sample_data, str): input_type = spec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(observation_data, user_id='user_id', item_id='item_id', target=None, user_data=None, item_data=None, nearest_items=None, similarity_type='jaccard', thr...
from turicreate._cython.cy_server import QuietProgress opts = {} model_proxy = _turicreate.extensions.item_similarity() model_proxy.init_options(opts) if user_data is None: user_data = _turicreate.SFrame() if item_data is None: item_data = _turicreate.SFrame() if neare...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_advanced_relu(builder, layer, input_names, output_names, keras_layer): """ Convert an ReLU layer with maximum value from keras to coreml. Parameters ...
# Get input and output names input_name, output_name = (input_names[0], output_names[0]) if keras_layer.max_value is None: builder.add_activation(layer, 'RELU', input_name, output_name) return # No direct support of RELU with max-activation value - use negate and # clip layers ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_separable_convolution(builder, layer, input_names, output_names, keras_layer): """ Convert separable convolution layer from keras to coreml. Paramete...
_check_data_format(keras_layer) # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.use_bias # Get the weights from _keras. weight_list = keras_layer.get_weights() output_blob_shape = list(filter(None, keras_layer.output_shape))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_batchnorm(builder, layer, input_names, output_names, keras_layer): """ Convert a Batch Normalization layer. Parameters keras_layer: layer A keras lay...
# Get input and output names input_name, output_name = (input_names[0], output_names[0]) axis = keras_layer.axis nb_channels = keras_layer.input_shape[axis] # Set parameters # Parameter arrangement in Keras: gamma, beta, mean, variance idx = 0 gamma, beta = None, None if keras_la...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_merge(builder, layer, input_names, output_names, keras_layer): """ Convert concat layer from keras to coreml. Parameters keras_layer: layer A keras l...
# Get input and output names output_name = output_names[0] mode = _get_elementwise_name_from_keras_layer(keras_layer) builder.add_elementwise(name = layer, input_names = input_names, output_name = output_name, mode = mode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_pooling(builder, layer, input_names, output_names, keras_layer): """ Convert pooling layer from keras to coreml. Parameters keras_layer: layer A kera...
_check_data_format(keras_layer) # Get input and output names input_name, output_name = (input_names[0], output_names[0]) # Pooling layer type if isinstance(keras_layer, _keras.layers.convolutional.MaxPooling2D) or \ isinstance(keras_layer, _keras.layers.convolutional.MaxPooling1D) or \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _loadlib(lib='standard'): """Load rabit library."""
global _LIB if _LIB is not None: warnings.warn('rabit.int call was ignored because it has'\ ' already been initialized', level=2) return if lib == 'standard': _LIB = ctypes.cdll.LoadLibrary(WRAPPER_PATH % '') elif lib == 'mock': _LIB = ctypes.cd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(args=None, lib='standard'): """Intialize the rabit module, call this once before using anything. Parameters args: list of str, optional The list of argu...
if args is None: args = sys.argv _loadlib(lib) arr = (ctypes.c_char_p * len(args))() arr[:] = args _LIB.RabitInit(len(args), arr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allreduce(data, op, prepare_fun=None): """Perform allreduce, return the result. Parameters data: numpy array Input data. op: int Reduction operators, can be ...
if not isinstance(data, np.ndarray): raise Exception('allreduce only takes in numpy.ndarray') buf = data.ravel() if buf.base is data.base: buf = buf.copy() if buf.dtype not in DTYPE_ENUM__: raise Exception('data type %s not supported' % str(buf.dtype)) if prepare_fun is None...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_checkpoint(with_local=False): """Load latest check point. Parameters with_local: bool, optional whether the checkpoint contains local model Returns ----...
gptr = ctypes.POINTER(ctypes.c_char)() global_len = ctypes.c_ulong() if with_local: lptr = ctypes.POINTER(ctypes.c_char)() local_len = ctypes.c_ulong() version = _LIB.RabitLoadCheckPoint( ctypes.byref(gptr), ctypes.byref(global_len), ctypes.byref(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkpoint(global_model, local_model=None): """Checkpoint the model. This means we finished a stage of execution. Every time we call check point, there is a ...
sglobal = pickle.dumps(global_model) if local_model is None: _LIB.RabitCheckPoint(sglobal, len(sglobal), None, 0) del sglobal else: slocal = pickle.dumps(local_model) _LIB.RabitCheckPoint(sglobal, len(sglobal), slocal, len(slocal)) del slocal del sglobal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(observation_data, user_id='user_id', item_id='item_id', target=None, user_data=None, item_data=None, num_factors=32, regularization=1e-9, linear_regula...
from turicreate._cython.cy_server import QuietProgress opts = {} model_proxy = _turicreate.extensions.ranking_factorization_recommender() model_proxy.init_options(opts) if user_data is None: user_data = _turicreate.SFrame() if item_data is None: item_data = _turicreate.SFrame(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_converter_module(sk_obj): """ Returns the module holding the conversion functions for a particular model). """
try: cv_idx = _converter_lookup[sk_obj.__class__] except KeyError: raise ValueError( "Transformer '%s' not supported; supported transformers are %s." % (repr(sk_obj), ",".join(k.__name__ for k in _converter_module_list))) return _converte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_post_evaluation_transform(self, value): r""" Set the post processing transform applied after the prediction value from the tree ensemble. Parameters valu...
self.tree_spec.postEvaluationTransform = \ _TreeEnsemble_pb2.TreeEnsemblePostEvaluationTransform.Value(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_branch_node(self, tree_id, node_id, feature_index, feature_value, branch_mode, true_child_id, false_child_id, relative_hit_rate = None, missing_value_trac...
spec_node = self.tree_parameters.nodes.add() spec_node.treeId = tree_id spec_node.nodeId = node_id spec_node.branchFeatureIndex = feature_index spec_node.branchFeatureValue = feature_value spec_node.trueChildNodeId = true_child_id spec_node.falseChildNodeId = fal...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_leaf_node(self, tree_id, node_id, values, relative_hit_rate = None): """ Add a leaf node to the tree ensemble. Parameters tree_id: int ID of the tree to ...
spec_node = self.tree_parameters.nodes.add() spec_node.treeId = tree_id spec_node.nodeId = node_id spec_node.nodeBehavior = \ _TreeEnsemble_pb2.TreeEnsembleParameters.TreeNode.TreeNodeBehavior.Value('LeafNode') if not isinstance(values, _collections.Iterable): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create (raw_properties = []): """ Creates a new 'PropertySet' instance for the given raw properties, or returns an already existing one. """
assert (is_iterable_typed(raw_properties, property.Property) or is_iterable_typed(raw_properties, basestring)) # FIXME: propagate to callers. if len(raw_properties) > 0 and isinstance(raw_properties[0], property.Property): x = raw_properties else: x = [property.create_from_s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_with_validation (raw_properties): """ Creates new 'PropertySet' instances after checking that all properties are valid and converting implicit propert...
assert is_iterable_typed(raw_properties, basestring) properties = [property.create_from_string(s) for s in raw_properties] property.validate(properties) return create(properties)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_user_input(raw_properties, jamfile_module, location): """Creates a property-set from the input given by the user, in the context of 'jamfile-modu...
assert is_iterable_typed(raw_properties, basestring) assert isinstance(jamfile_module, basestring) assert isinstance(location, basestring) properties = property.create_from_strings(raw_properties, True) properties = property.translate_paths(properties, location) properties = property.translate_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base (self): """ Returns properties that are neither incidental nor free. """
result = [p for p in self.lazy_properties if not(p.feature.incidental or p.feature.free)] result.extend(self.base_) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def free (self): """ Returns free properties which are not dependency properties. """
result = [p for p in self.lazy_properties if not p.feature.incidental and p.feature.free] result.extend(self.free_) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dependency (self): """ Returns dependency properties. """
result = [p for p in self.lazy_properties if p.feature.dependency] result.extend(self.dependency_) return self.dependency_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def non_dependency (self): """ Returns properties that are not dependencies. """
result = [p for p in self.lazy_properties if not p.feature.dependency] result.extend(self.non_dependency_) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def incidental (self): """ Returns incidental properties. """
result = [p for p in self.lazy_properties if p.feature.incidental] result.extend(self.incidental_) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refine (self, requirements): """ Refines this set's properties using the requirements passed as an argument. """
assert isinstance(requirements, PropertySet) if requirements not in self.refined_: r = property.refine(self.all_, requirements.all_) self.refined_[requirements] = create(r) return self.refined_[requirements]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def target_path (self): """ Computes the target path that should be used for target with these properties. Returns a tuple of - the computed path - if the path i...
if not self.target_path_: # The <location> feature can be used to explicitly # change the location of generated targets l = self.get ('<location>') if l: computed = l[0] is_relative = False else: p = se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add (self, ps): """ Creates a new property set containing the properties in this one, plus the ones of the property set passed as argument. """
assert isinstance(ps, PropertySet) if ps not in self.added_: self.added_[ps] = create(self.all_ + ps.all()) return self.added_[ps]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get (self, feature): """ Returns all values of 'feature'. """
if type(feature) == type([]): feature = feature[0] if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.Feature) if self.feature_map_ is None: self.feature_map_ = {}...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_properties(self, feature): """Returns all contained properties associated with 'feature'"""
if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.Feature) result = [] for p in self.all_: if p.feature == feature: result.append(p) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create(observation_data, user_id='user_id', item_id='item_id', target=None, user_data=None, item_data=None, ranking=True, verbose=True): """ A unified inter...
if not (isinstance(observation_data, _SFrame)): raise TypeError('observation_data input must be a SFrame') side_data = (user_data is not None) or (item_data is not None) if user_data is not None: if not isinstance(user_data, _SFrame): raise TypeError('Provided user_data must b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_models(dataset, models, model_names=None, user_sample=1.0, metric='auto', target=None, exclude_known_for_precision_recall=True, make_plot=False, verbo...
num_models = len(models) if model_names is None: model_names = ['M' + str(i) for i in range(len(models))] if num_models < 1: raise ValueError("Must pass in at least one recommender model to \ evaluate") if model_names is not None and len(model_names) != nu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def precision_recall_by_user(observed_user_items, recommendations, cutoffs=[10]): """ Compute precision and recall at a given cutoff for each user. In informatio...
assert type(observed_user_items) == _SFrame assert type(recommendations) == _SFrame assert type(cutoffs) == list assert min(cutoffs) > 0, "All cutoffs must be positive integers." assert recommendations.num_columns() >= 2 user_id = recommendations.column_names()[0] item_id = recommendations...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_split_by_user(dataset, user_id='user_id', item_id='item_id', max_num_users=1000, item_test_proportion=.2, random_seed=0): """Create a recommender-frie...
assert user_id in dataset.column_names(), \ 'Provided user column "{0}" not found in data set.'.format(user_id) assert item_id in dataset.column_names(), \ 'Provided item column "{0}" not found in data set.'.format(item_id) if max_num_users == 'all': max_num_users = None if r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _list_fields(self): """ Get the current settings of the model. The keys depend on the type of model. Returns ------- out : list A list of fields that can be ...
response = self.__proxy__.list_fields() return [s for s in response['value'] if not s.startswith("_")]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_current_options(self, options): """ Set current options for a model. Parameters options : dict A dictionary of the desired option settings. The key shou...
opts = self._get_current_options() opts.update(options) response = self.__proxy__.set_current_options(opts) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __prepare_dataset_parameter(self, dataset): """ Processes the dataset parameter for type correctness. Returns it as an SFrame. """
# Translate the dataset argument into the proper type if not isinstance(dataset, _SFrame): def raise_dataset_type_exception(): raise TypeError("The dataset parameter must be either an SFrame, " "or a dictionary of (str : list) or (str : value...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, dataset, new_observation_data=None, new_user_data=None, new_item_data=None): """ Return a score prediction for the user ids and item ids in the...
if new_observation_data is None: new_observation_data = _SFrame() if new_user_data is None: new_user_data = _SFrame() if new_item_data is None: new_item_data = _SFrame() dataset = self.__prepare_dataset_parameter(dataset) def check_type(ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_similar_items(self, items=None, k=10, verbose=False): """ Get the k most similar items for each item in items. Each type of recommender has its own model...
if items is None: get_all_items = True items = _SArray() else: get_all_items = False if isinstance(items, list): items = _SArray(items) def check_type(arg, arg_name, required_type, allowed_types): if not isinstance(arg, requ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_similar_users(self, users=None, k=10): """Get the k most similar users for each entry in `users`. Each type of recommender has its own model for the simi...
if users is None: get_all_users = True users = _SArray() else: get_all_users = False if isinstance(users, list): users = _SArray(users) def check_type(arg, arg_name, required_type, allowed_types): if not isinstance(arg, requ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recommend_from_interactions( self, observed_items, k=10, exclude=None, items=None, new_user_data=None, new_item_data=None, exclude_known=True, diversity=0, ra...
column_types = self._get_data_schema() user_id = self.user_id item_id = self.item_id user_type = column_types[user_id] item_type = column_types[item_id] if not hasattr(self, "_implicit_user_name"): import hashlib import time self._im...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_precision_recall(self, dataset, cutoffs=list(range(1,11,1))+list(range(11,50,5)), skip_set=None, exclude_known=True, verbose=True, **kwargs): """ Co...
user_column = self.user_id item_column = self.item_id assert user_column in dataset.column_names() and \ item_column in dataset.column_names(), \ 'Provided data set must have a column pertaining to user ids and \ item ids, similar to what we had during t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_rmse(self, dataset, target): """ Evaluate the prediction error for each user-item pair in the given data set. Parameters dataset : SFrame An SFrame ...
assert target in dataset.column_names(), \ 'Provided dataset must contain a target column with the same \ name as the target used during training.' y = dataset[target] yhat = self.predict(dataset) user_column = self.user_id item_column = self.item...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(self, dataset, metric='auto', exclude_known_for_precision_recall=True, target=None, verbose=True, **kwargs): r""" Evaluate the model's ability to ma...
ret = {} dataset = self.__prepare_dataset_parameter(dataset) # If the model does not have a target column, compute prec-recall. if metric in ['precision_recall', 'auto']: results = self.evaluate_precision_recall(dataset, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_popularity_baseline(self): """ Returns a new popularity model matching the data set this model was trained with. Can be used for comparison purposes. ""...
response = self.__proxy__.get_popularity_baseline() from .popularity_recommender import PopularityRecommender return PopularityRecommender(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_item_intersection_info(self, item_pairs): """ For a collection of item -> item pairs, returns information about the users in that intersection. Paramete...
if type(item_pairs) is list: if not all(type(t) in [list, tuple] and len(t) == 2 for t in item_pairs): raise TypeError("item_pairs must be 2-column SFrame of two item " "columns, or a list of (item_1, item_2) tuples. ") item_name = self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def query_boost_version(boost_root): ''' Read in the Boost version from a given boost_root. ''' boost_version = None if os.path.exists(os.path.join(boost_root,'Jamroot')): with codecs.open(os.path.join(boost_root,'Jamroot'), 'r', 'utf-8') as f: for lin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def git_clone(sub_repo, branch, commit = None, cwd = None, no_submodules = False): ''' This clone mimicks the way Travis-CI clones a project's repo. So far Travis-CI is the most limiting in the sense of only fetching partial history of the repo. ''' if not cwd: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def install_toolset(self, toolset): ''' Installs specific toolset on CI system. ''' info = toolset_info[toolset] if sys.platform.startswith('linux'): os.chdir(self.work_dir) if 'ppa' in info: for ppa in info['ppa']: util...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_keras_model(model_network_path, model_weight_path, custom_objects=None): """Load a keras model from disk Parameters model_network_path: str Path where ...
from keras.models import model_from_json import json # Load the model network json_file = open(model_network_path, 'r') loaded_model_json = json_file.read() json_file.close() if not custom_objects: custom_objects = {} # Load the model weights loaded_model = model_from_jso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(self): """ A method for displaying the Plot object Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, de...
global _target display = False try: if _target == 'auto' and \ get_ipython().__class__.__name__ == "ZMQInteractiveShell": self._repr_javascript_() display = True except NameError: pass finally: if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, filepath): """ A method for saving the Plot object in a vega representation Parameters filepath: string The destination filepath where the plot ob...
if type(filepath) != str: raise ValueError("filepath provided is not a string") if filepath.endswith(".json"): # save as vega json spec = self.get_vega(include_data = True) with open(filepath, 'w') as fp: _json.dump(spec, fp) elif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_value(scikit_value, mode = 'regressor', scaling = 1.0, n_classes = 2, tree_index = 0): """ Get the right value from the scikit-tree """
# Regression if mode == 'regressor': return scikit_value[0] * scaling # Binary classification if n_classes == 2: # Decision tree if len(scikit_value[0]) != 1: value = scikit_value[0][1] * scaling / scikit_value[0].sum() # boosted tree else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_tree_ensemble(model, input_features, output_features = ('predicted_class', float), mode = 'regressor', base_prediction = None, class_labels = None, po...
num_dimensions = get_input_dimension(model) features = process_or_validate_features(input_features, num_dimensions) n_classes = None if mode == 'classifier': n_classes = model.n_classes_ if class_labels is None: class_labels = range(n_classes) else: if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_styles(self, style=None): """ Returns SFrame of style images used for training the model Parameters style: int or list, optional The selected style or li...
style, _ = self._style_input_check(style) return self.styles.filter_by(style, self._index_column)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_model(model_path): """Load a libsvm model from a path on disk. This currently supports: * C-SVC * NU-SVC * Epsilon-SVR * NU-SVR Parameters model_path: s...
if not(HAS_LIBSVM): raise RuntimeError('libsvm not found. libsvm conversion API is disabled.') from svmutil import svm_load_model # From libsvm import os if (not os.path.exists(model_path)): raise IOError("Expected a valid file path. %s does not exist" % model_path) return svm_load...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_enumerated_multiarray_shapes(spec, feature_name, shapes): """ Annotate an input or output multiArray feature in a Neural Network spec to to accommodate a...
if not isinstance(shapes, list): shapes = [shapes] for shape in shapes: if not isinstance(shape, NeuralNetworkMultiArrayShape): raise Exception( 'Shape ranges should be of type NeuralNetworkMultiArrayShape') shape._validate_multiarray_shape() feature =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_enumerated_image_sizes(spec, feature_name, sizes): """ Annotate an input or output image feature in a Neural Network spec to to accommodate a list of enu...
if not isinstance(sizes, list): sizes = [sizes] for size in sizes: if not isinstance(size, NeuralNetworkImageSize): raise Exception( 'Shape ranges should be of type NeuralNetworkImageSize') feature = _get_feature(spec, feature_name) if feature.type.WhichOne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_image_size_range(spec, feature_name, size_range): """ Annotate an input or output Image feature in a Neural Network spec to to accommodate a range of ...
if not isinstance(size_range, NeuralNetworkImageSizeRange): raise Exception( 'Shape ranges should be of type NeuralNetworkImageSizeRange') feature = _get_feature(spec, feature_name) if feature.type.WhichOneof('Type') != 'imageType': raise Exception('Trying to add size ranges fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_multiarray_shape_range(spec, feature_name, shape_range): """ Annotate an input or output MLMultiArray feature in a Neural Network spec to accommodate ...
if not isinstance(shape_range, NeuralNetworkMultiArrayShapeRange): raise Exception('Shape range should be of type MultiArrayShapeRange') shape_range.validate_array_shape_range() feature = _get_feature(spec, feature_name) if feature.type.WhichOneof('Type') != 'multiArrayType': raise Ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_allowed_shape_ranges(spec): """ For a given model specification, returns a dictionary with a shape range object for each input feature name. """
shaper = NeuralNetworkShaper(spec, False) inputs = _get_input_names(spec) output = {} for input in inputs: output[input] = shaper.shape(input) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_allow_multiple_input_shapes(spec): """ Examines a model specification and determines if it can compute results for more than one output shape. :param spe...
# First, check that the model actually has a neural network in it try: layers = _get_nn_layers(spec) except: raise Exception('Unable to verify that this model contains a neural network.') try: shaper = NeuralNetworkShaper(spec, False) except: raise Exception('Unabl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isFlexible(self): """ Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value. """
for key, value in self.arrayShapeRange.items(): if key in _CONSTRAINED_KEYS: if value.isFlexible: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define_macro(out_f, (name, args, body), undefine=False, check=True): """Generate a macro definition or undefinition"""
if undefine: out_f.write( '#undef {0}\n' .format(macro_name(name)) ) else: if args: arg_list = '({0})'.format(', '.join(args)) else: arg_list = '' if check: out_f.write( '#ifdef {0}\n' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filename(out_dir, name, undefine=False): """Generate the filename"""
if undefine: prefix = 'undef_' else: prefix = '' return os.path.join(out_dir, '{0}{1}.hpp'.format(prefix, name.lower()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def length_limits(max_length_limit, length_limit_step): """Generates the length limits"""
string_len = len(str(max_length_limit)) return [ str(i).zfill(string_len) for i in xrange( length_limit_step, max_length_limit + length_limit_step - 1, length_limit_step ) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_take(out_f, steps, line_prefix): """Generate the take function"""
out_f.write( '{0}constexpr inline int take(int n_)\n' '{0}{{\n' '{0} return {1} 0 {2};\n' '{0}}}\n' '\n'.format( line_prefix, ''.join('n_ >= {0} ? {0} : ('.format(s) for s in steps), ')' * len(steps) ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_make_string(out_f, max_step): """Generate the make_string template"""
steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)] with Namespace( out_f, ['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl'] ) as nsp: generate_take(out_f, steps, nsp.prefix()) out_f.write( '{0}template <int LenNow, int LenRemaining, char....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_string(out_dir, limits): """Generate string.hpp"""
max_limit = max((int(v) for v in limits)) with open(filename(out_dir, 'string'), 'wb') as out_f: with IncludeGuard(out_f): out_f.write( '\n' '#include <boost/metaparse/v{0}/cpp11/impl/concat.hpp>\n' '#include <boost/preprocessor/cat.hpp>\n' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def existing_path(value): """Throws when the path does not exist"""
if os.path.exists(value): return value else: raise argparse.ArgumentTypeError("Path {0} not found".format(value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def end(self): """Generate the closing part"""
for depth in xrange(len(self.names) - 1, -1, -1): self.out_f.write('{0}}}\n'.format(self.prefix(depth)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_deep_features(audio_data, verbose=True): ''' Calculates the deep features used by the Sound Classifier. Internally the Sound Classifier calculates deep features for both model creation and predictions. If the same data will be used multiple times, calculating the deep features just once wil...