Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def translate_poco_step(self, step):
ret = {}
prev_step = self._steps[-1]
if prev_step:
ret.update(prev_step)
ret['type'] = step[1].get("name", "")
if step.get('trace'):
ret['trace'] = step['trace']
... | [
"\n 处理poco的相关操作,参数与airtest的不同,由一个截图和一个操作构成,需要合成一个步骤\n Parameters\n ----------\n step 一个完整的操作,如click\n prev_step 前一个步骤,应该是截图\n\n Returns\n -------\n\n "
] |
Please provide a description of the function:def func_desc_poco(self, step):
desc = {
"touch": u"点击UI组件 {name}".format(name=step.get("text", "")),
}
if step['type'] in desc:
return desc.get(step['type'])
else:
return self._translate_desc(step) | [
" 把对应的poco操作显示成中文"
] |
Please provide a description of the function:def profile_different_methods(search_file, screen_file, method_list, dir_path, file_name):
profiler = ProfileRecorder(0.05)
# 加载图片
profiler.load_images(search_file, screen_file)
# 传入待测试的方法列表
profiler.profile_methods(method_list)
# 将性能数据写入文件
p... | [
"对指定的图片进行性能测试."
] |
Please provide a description of the function:def plot_profiled_all_images_table(method_list):
high_dpi_dir_path, high_dpi_file_name = "result", "high_dpi.json"
rich_texture_dir_path, rich_texture_file_name = "result", "rich_texture.json"
text_dir_path, text_file_name = "result", "text.json"
image_... | [
"绘制多个图片的结果."
] |
Please provide a description of the function:def get_color_list(method_list):
color_list = []
for method in method_list:
color = tuple([random() for _ in range(3)]) # 随机颜色画线
color_list.append(color)
return color_list | [
"获取method对应的color列表."
] |
Please provide a description of the function:def plot_compare_table(image_list, method_list, color_list, compare_dict, fig_name="", fig_num=111):
row_labels = image_list
# 写入值:
table_vals = []
for i in range(len(row_labels)):
row_vals = []
for method in method_list:
row_... | [
"绘制了对比表格."
] |
Please provide a description of the function:def plot_compare_curves(image_list, method_list, color_list, compare_dict, fig_name="", fig_num=111):
plt.subplot(fig_num)
plt.title(fig_name, loc="center") # 设置绘图的标题
mix_ins = []
for index, method in enumerate(method_list):
mem_ins = plt.plot(i... | [
"绘制对比曲线."
] |
Please provide a description of the function:def ReadTag(buffer, pos):
start = pos
while six.indexbytes(buffer, pos) & 0x80:
pos += 1
pos += 1
return (buffer[start:pos], pos) | [
"Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.\n\n We return the raw bytes of the tag rather than decoding them. The raw\n bytes can then be used to look up the proper decoder. This effectively allows\n us to trade some work that would be done in pure-python (decoding a varint)\n for wo... |
Please provide a description of the function:def _SimpleDecoder(wire_type, decode_value):
def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default):
if is_packed:
local_DecodeVarint = _DecodeVarint
def DecodePackedField(buffer, pos, end, message, field_dict):
value = fiel... | [
"Return a constructor for a decoder for fields of a particular type.\n\n Args:\n wire_type: The field's wire type.\n decode_value: A function which decodes an individual value, e.g.\n _DecodeVarint()\n "
] |
Please provide a description of the function:def _ModifiedDecoder(wire_type, decode_value, modify_value):
# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
# not enough to make a significant difference.
def InnerDecode(buffer, pos):
(result, new_pos) = decode_value(buffer, pos... | [
"Like SimpleDecoder but additionally invokes modify_value on every value\n before storing it. Usually modify_value is ZigZagDecode.\n "
] |
Please provide a description of the function:def _StructPackDecoder(wire_type, format):
value_size = struct.calcsize(format)
local_unpack = struct.unpack
# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
# not enough to make a significant difference.
# Note that we expect som... | [
"Return a constructor for a decoder for a fixed-width field.\n\n Args:\n wire_type: The field's wire type.\n format: The format string to pass to struct.unpack().\n "
] |
Please provide a description of the function:def _FloatDecoder():
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
# We expect a 32-bit value in little-endian byte order. Bit 1 is the sign
# bit, bits 2-9 represent the exponent, and bits 10-32 are the significand.
new_pos = pos + 4
f... | [
"Returns a decoder for a float field.\n\n This code works around a bug in struct.unpack for non-finite 32-bit\n floating-point values.\n "
] |
Please provide a description of the function:def _DoubleDecoder():
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
# We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
# bit, bits 2-12 represent the exponent, and bits 13-64 are the significand.
new_pos = pos + 8
... | [
"Returns a decoder for a double field.\n\n This code works around a bug in struct.unpack for not-a-number.\n "
] |
Please provide a description of the function:def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
local_DecodeVarint = _DecodeVarint
local_unicode = six.text_type
def _ConvertToUnicode(byte_str):
try:
return local_unicode(byte_str, 'utf-8')
except UnicodeDecodeError as e:
... | [
"Returns a decoder for a string field."
] |
Please provide a description of the function:def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):
local_DecodeVarint = _DecodeVarint
assert not is_packed
if is_repeated:
tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_LENGTH_DELIMITED)... | [
"Returns a decoder for a bytes field."
] |
Please provide a description of the function:def GroupDecoder(field_number, is_repeated, is_packed, key, new_default):
end_tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_END_GROUP)
end_tag_len = len(end_tag_bytes)
assert not is_packed
if is_repeated:
... | [
"Returns a decoder for a group field."
] |
Please provide a description of the function:def MapDecoder(field_descriptor, new_default, is_message_map):
key = field_descriptor
tag_bytes = encoder.TagBytes(field_descriptor.number,
wire_format.WIRETYPE_LENGTH_DELIMITED)
tag_len = len(tag_bytes)
local_DecodeVarint = _Decode... | [
"Returns a decoder for a map field."
] |
Please provide a description of the function:def _SkipVarint(buffer, pos, end):
# Previously ord(buffer[pos]) raised IndexError when pos is out of range.
# With this code, ord(b'') raises TypeError. Both are handled in
# python_message.py to generate a 'Truncated message' error.
while ord(buffer[pos:pos+1])... | [
"Skip a varint value. Returns the new position."
] |
Please provide a description of the function:def _SkipLengthDelimited(buffer, pos, end):
(size, pos) = _DecodeVarint(buffer, pos)
pos += size
if pos > end:
raise _DecodeError('Truncated message.')
return pos | [
"Skip a length-delimited value. Returns the new position."
] |
Please provide a description of the function:def _SkipGroup(buffer, pos, end):
while 1:
(tag_bytes, pos) = ReadTag(buffer, pos)
new_pos = SkipField(buffer, pos, end, tag_bytes)
if new_pos == -1:
return pos
pos = new_pos | [
"Skip sub-group. Returns the new position."
] |
Please provide a description of the function:def _FieldSkipper():
WIRETYPE_TO_SKIPPER = [
_SkipVarint,
_SkipFixed64,
_SkipLengthDelimited,
_SkipGroup,
_EndGroup,
_SkipFixed32,
_RaiseInvalidWireType,
_RaiseInvalidWireType,
]
wiretype_mask = wire_format.TAG_T... | [
"Constructs the SkipField function.",
"Skips a field with the specified tag.\n\n |pos| should point to the byte immediately after the tag.\n\n Returns:\n The new position (after the tag value), or -1 if the tag is an end-group\n tag (in which case the calling loop should break).\n "
] |
Please provide a description of the function:def _parse_node(graph, text):
match = _NODEPAT.match(text)
if match is not None:
node = match.group(1)
graph.node(node, label=match.group(2), shape='circle')
return node
match = _LEAFPAT.match(text)
if match is not None:
n... | [
"parse dumped node"
] |
Please provide a description of the function:def plot_tree(booster, num_trees=0, rankdir='UT', ax=None, **kwargs):
try:
import matplotlib.pyplot as plt
import matplotlib.image as image
except ImportError:
raise ImportError('You must install matplotlib to plot tree')
if ax is N... | [
"Plot specified tree.\n\n Parameters\n ----------\n booster : Booster, XGBModel\n Booster or XGBModel instance\n num_trees : int, default 0\n Specify the ordinal number of target tree\n rankdir : str, default \"UT\"\n Passed to graphiz via graph_attr\n ax : matplotlib Axes, de... |
Please provide a description of the function:def construct (self, properties = [], targets = []):
if not targets:
for name, project in self.projects ().projects ():
targets.append (project.target ())
property_groups = build_request.expand_no_defaults (properties)
... | [
" Constructs the dependency graph.\n properties: the build properties.\n targets: the targets to consider. If none is specified, uses all.\n "
] |
Please provide a description of the function:def evaluate(self, dataset, metric='auto', missing_value_action='auto'):
_raise_error_evaluation_metric_is_valid(metric,
['auto', 'accuracy', 'confusion_matrix', 'roc_curve', 'auc',
'log_loss', 'precision', 'recall', 'f1_scor... | [
"\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 target and features used for ... |
Please provide a description of the function:def predict(self, dataset, output_type='class', missing_value_action='auto'):
_check_categorical_option_type('output_type', output_type,
['class', 'margin', 'probability', 'probability_vector'])
return super(_Classifier, self).predict... | [
"\n A flexible and advanced prediction API.\n\n The target column is provided during\n :func:`~turicreate.decision_tree.create`. If the target column is in the\n `dataset` it will be ignored.\n\n Parameters\n ----------\n dataset : SFrame\n A dataset that ha... |
Please provide a description of the function:def predict_topk(self, dataset, output_type="probability", k=3, missing_value_action='auto'):
_check_categorical_option_type('output_type', output_type, ['rank', 'margin', 'probability'])
if missing_value_action == 'auto':
missing_value_a... | [
"\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`, `margin`, or `rank`, depending on the ``output_type``\n parameter. Input dataset size must be the same as for traini... |
Please provide a description of the function:def classify(self, dataset, missing_value_action='auto'):
return super(DecisionTreeClassifier, self).classify(dataset,
missing_value_action=missing_value_action) | [
"\n Return a classification, for each example in the ``dataset``, using the\n trained model. The output SFrame contains predictions as class labels\n (0 or 1) and probabilities associated with the the example.\n\n Parameters\n ----------\n dataset : SFrame\n Data... |
Please provide a description of the function:def slave_envs(self):
if self.hostIP == 'dns':
host = socket.gethostname()
elif self.hostIP == 'ip':
host = socket.gethostbyname(socket.getfqdn())
else:
host = self.hostIP
return {'rabit_tracker_uri... | [
"\n get enviroment variables for slaves\n can be passed in as args or envs\n "
] |
Please provide a description of the function:def find_share_ring(self, tree_map, parent_map, r):
nset = set(tree_map[r])
cset = nset - set([parent_map[r]])
if len(cset) == 0:
return [r]
rlst = [r]
cnt = 0
for v in cset:
vlst = self.find_sh... | [
"\n get a ring structure that tends to share nodes with the tree\n return a list starting from r\n "
] |
Please provide a description of the function:def get_ring(self, tree_map, parent_map):
assert parent_map[0] == -1
rlst = self.find_share_ring(tree_map, parent_map, 0)
assert len(rlst) == len(tree_map)
ring_map = {}
nslave = len(tree_map)
for r in range(nslave):
... | [
"\n get a ring connection used to recover local data\n "
] |
Please provide a description of the function:def get_link_map(self, nslave):
tree_map, parent_map = self.get_tree(nslave)
ring_map = self.get_ring(tree_map, parent_map)
rmap = {0 : 0}
k = 0
for i in range(nslave - 1):
k = ring_map[k][1]
rmap[k] = ... | [
"\n get the link map, this is a bit hacky, call for better algorithm\n to place similar nodes together\n "
] |
Please provide a description of the function:def maybe_rewrite_setup(toolset, setup_script, setup_options, version, rewrite_setup='off'):
result = '"{}" {}'.format(setup_script, setup_options)
# At the moment we only know how to rewrite scripts with cmd shell.
if os.name == 'nt' and rewrite_setup != '... | [
"\n Helper rule to generate a faster alternative to MSVC setup scripts.\n\n We used to call MSVC setup scripts directly in every action, however in\n newer MSVC versions (10.0+) they make long-lasting registry queries\n which have a significant impact on build time.\n "
] |
Please provide a description of the function:def create(dataset, target, features=None, validation_set = 'auto',
verbose=True):
return _sl.create_classification_with_model_selector(
dataset,
target,
model_selector = _turicreate.extensions._supervised_learning._classifier_availab... | [
"\n Automatically create a suitable classifier model based on the provided\n training data.\n\n To use specific options of a desired model, use the ``create`` function\n of the corresponding model.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset for training the model.\n\n ta... |
Please provide a description of the function:def add_column(self, data, column_name="", inplace=False):
# Check type for pandas dataframe or SArray?
if not isinstance(data, SArray):
raise TypeError("Must give column as SArray")
if not isinstance(column_name, str):
... | [
"\n Adds the specified column to this SFrame. The number of elements in\n the data given must match every other column of the SFrame.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, returning a new SFrame.\n\n If inplace == True, this operat... |
Please provide a description of the function:def add_columns(self, data, column_names=None, inplace=False):
datalist = data
if isinstance(data, SFrame):
other = data
datalist = [other.select_column(name) for name in other.column_names()]
column_names = other... | [
"\n Adds columns to the SFrame. The number of elements in all columns must\n match every other column of the SFrame.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, returning a new SFrame.\n\n If inplace == True, this operation modifies the ... |
Please provide a description of the function:def remove_column(self, column_name, inplace=False):
if column_name not in self.column_names():
raise KeyError('Cannot find column %s' % column_name)
if inplace:
self.__is_dirty__ = True
try:
with c... | [
"\n Removes the column with the given name from the SFrame.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, returning a new SFrame.\n\n If inplace == True, this operation modifies the current\n SFrame, returning self.\n\n Parameters\n ... |
Please provide a description of the function:def swap_columns(self, column_name_1, column_name_2, inplace=False):
if inplace:
self.__is_dirty__ = True
with cython_context():
if self._is_vertex_frame():
graph_proxy = self.__graph__.__proxy__.sw... | [
"\n Swaps the columns with the given names.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, returning a new SFrame.\n\n If inplace == True, this operation modifies the current\n SFrame, returning self.\n\n Parameters\n ---------... |
Please provide a description of the function:def rename(self, names, inplace=False):
if (type(names) is not dict):
raise TypeError('names must be a dictionary: oldname -> newname')
if inplace:
self.__is_dirty__ = True
with cython_context():
i... | [
"\n Rename the columns using the 'names' dict. This changes the names of\n the columns given as the keys and replaces them with the names given as\n the values.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, returning a new SFrame.\n\n ... |
Please provide a description of the function:def num_rows(self):
if self._is_vertex_frame():
return self.__graph__.summary()['num_vertices']
elif self._is_edge_frame():
return self.__graph__.summary()['num_edges'] | [
"\n Returns the number of rows.\n\n Returns\n -------\n out : int\n Number of rows in the SFrame.\n "
] |
Please provide a description of the function:def column_names(self):
if self._is_vertex_frame():
return self.__graph__.__proxy__.get_vertex_fields()
elif self._is_edge_frame():
return self.__graph__.__proxy__.get_edge_fields() | [
"\n Returns the column names.\n\n Returns\n -------\n out : list[string]\n Column names of the SFrame.\n "
] |
Please provide a description of the function:def column_types(self):
if self.__type__ == VERTEX_GFRAME:
return self.__graph__.__proxy__.get_vertex_field_types()
elif self.__type__ == EDGE_GFRAME:
return self.__graph__.__proxy__.get_edge_field_types() | [
"\n Returns the column types.\n\n Returns\n -------\n out : list[type]\n Column types of the SFrame.\n "
] |
Please provide a description of the function:def create(dataset, target, features=None, validation_set = 'auto',
verbose=True):
dataset, validation_set = _validate_data(dataset, target, features,
validation_set)
if validation_set is None:
valida... | [
"\n Automatically create a suitable regression model based on the provided\n training data.\n\n To use specific options of a desired model, use the ``create`` function\n of the corresponding model.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset for training the model.\n\n ta... |
Please provide a description of the function:def removable(self, node):
'''
node is removable only if all of its children are as well.
'''
throw_away = []
for child in self.children(node):
throw_away.append(self.visit(child))
if self.mode == 'exclusive':
return all(throw_away)
... | [] |
Please provide a description of the function:def reduce(self, body):
'''
remove nodes from a list
'''
i = 0
while i < len(body):
stmnt = body[i]
if self.visit(stmnt):
body.pop(i)
else:
i += 1 | [] |
Please provide a description of the function:def load_audio(path, with_path=True, recursive=True, ignore_failure=True, random_order=False):
from scipy.io import wavfile as _wavfile
all_wav_files = []
if _fnmatch(path, '*.wav'): # single file
all_wav_files.append(path)
elif recursive:
... | [
"\n Loads WAV file(s) from a path.\n\n Parameters\n ----------\n path : str\n Path to WAV files to be loaded.\n\n with_path : bool, optional\n Indicates whether a path column is added to the returned SFrame.\n\n recursive : bool, optional\n Indicates whether ``load_audio`` sho... |
Please provide a description of the function:def RegisterMessage(self, message):
desc = message.DESCRIPTOR
self._classes[desc.full_name] = message
self.pool.AddDescriptor(desc)
return message | [
"Registers the given message type in the local database.\n\n Calls to GetSymbol() and GetMessages() will return messages registered here.\n\n Args:\n message: a message.Message, to be registered.\n\n Returns:\n The provided message.\n "
] |
Please provide a description of the function:def GetMessages(self, files):
# TODO(amauryfa): Fix the differences with MessageFactory.
def _GetAllMessageNames(desc):
yield desc.full_name
for msg_desc in desc.nested_types:
for full_name in _GetAllMessageNames(msg_desc):
... | [
"Gets all registered messages from a specified file.\n\n Only messages already created and registered will be returned; (this is the\n case for imported _pb2 modules)\n But unlike MessageFactory, this version also returns already defined nested\n messages, but does not register any message extensions.\n... |
Please provide a description of the function:def _string_hash(s):
h = 5381
for c in s:
h = h * 33 + ord(c)
return h | [
"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."
] |
Please provide a description of the function:def draw_bounding_boxes(images, annotations, confidence_threshold=0):
_numeric_param_check_range('confidence_threshold', confidence_threshold, 0.0, 1.0)
from PIL import Image
def draw_single_image(row):
image = row['image']
anns = row['annota... | [
"\n Visualizes bounding boxes (ground truth or predictions) by\n returning annotated copies of the images.\n\n Parameters\n ----------\n images: SArray or Image\n An `SArray` of type `Image`. A single `Image` instance may also be\n given.\n\n annotations: SArray or list\n An `... |
Please provide a description of the function:def create(dataset, target, model_name, features=None,
validation_set='auto', distributed='auto',
verbose=True, seed=None, **kwargs):
# Perform error-checking and trim inputs to specified columns
dataset, validation_set = _validate_data(da... | [
"\n Create a :class:`~turicreate.toolkits.SupervisedLearningModel`,\n\n This is generic function that allows you to create any model that\n implements SupervisedLearningModel This function is normally not called, call\n specific model's create function instead\n\n Parameters\n ----------\n data... |
Please provide a description of the function:def create_classification_with_model_selector(dataset, target, model_selector,
features=None, validation_set='auto', verbose=True):
# Perform error-checking and trim inputs to specified columns
dataset, validation_set = _validate_data(dataset, target, featu... | [
"\n Create a :class:`~turicreate.toolkits.SupervisedLearningModel`,\n\n This is generic function that allows you to create any model that\n implements SupervisedLearningModel. This function is normally not called, call\n specific model's create function instead.\n\n Parameters\n ----------\n da... |
Please provide a description of the function:def predict(self, dataset, missing_value_action='auto',
output_type='', options={}, **kwargs):
if missing_value_action == 'auto':
missing_value_action = select_default_missing_value_policy(self, 'predict')
# Low latency p... | [
"\n Return predictions for ``dataset``, using the trained supervised_learning\n model. Predictions are generated as class labels (0 or\n 1).\n\n Parameters\n ----------\n dataset : SFrame\n Dataset of new observations. Must include columns with the same\n ... |
Please provide a description of the function:def evaluate(self, dataset, metric="auto",
missing_value_action='auto', with_predictions=False, options={}, **kwargs):
if missing_value_action == 'auto':
missing_value_action = select_default_missing_value_policy(
... | [
"\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 in the same format used for training. The columns names and\n types of the dataset must be the same ... |
Please provide a description of the function:def classify(self, dataset, missing_value_action='auto'):
if (missing_value_action == 'auto'):
missing_value_action = select_default_missing_value_policy(self, 'classify')
# Low latency path
if isinstance(dataset, list):
... | [
"\n Return predictions for ``dataset``, using the trained supervised_learning\n model. Predictions are generated as class labels (0 or\n 1).\n\n Parameters\n ----------\n dataset: SFrame\n Dataset of new observations. Must include columns with the same\n ... |
Please provide a description of the function:def evaluate(self, dataset, metric='auto', missing_value_action='auto'):
_raise_error_evaluation_metric_is_valid(
metric, ['auto', 'rmse', 'max_error'])
return super(BoostedTreesRegression, self).evaluate(dataset,
... | [
"\n Evaluate the model on the given dataset.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset in the same format used for training. The columns names and\n types of the dataset must be the same as that used in training.\n\n metric : str, optional\n ... |
Please provide a description of the function:def predict(self, dataset, missing_value_action='auto'):
return super(BoostedTreesRegression, self).predict(dataset, output_type='margin',
missing_value_action=missing_value_action) | [
"\n Predict the target column of the given dataset.\n\n The target column is provided during\n :func:`~turicreate.boosted_trees_regression.create`. If the target column is in the\n `dataset` it will be ignored.\n\n Parameters\n ----------\n dataset : SFrame\n ... |
Please provide a description of the function:def print_code(co, lasti= -1, level=0):
code = co.co_code
for constant in co.co_consts:
print( '| |' * level, end=' ')
print( 'constant:', constant)
labels = findlabels(code)
linestarts = dict(findlinestarts(co)... | [
"Disassemble a code object."
] |
Please provide a description of the function:def convert(model, feature_names, target):
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
_sklearn_util.check_expected_type(model, _tree.DecisionTreeRegressor)
_sklearn_util.check_fitted(... | [
"Convert a decision tree model to protobuf format.\n\n Parameters\n ----------\n decision_tree : DecisionTreeRegressor\n A trained scikit-learn tree 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 -----... |
Please provide a description of the function:def _check_prob_and_prob_vector(predictions):
from .._deps import numpy
ptype = predictions.dtype
import array
if ptype not in [float, numpy.ndarray, array.array, int]:
err_msg = "Input `predictions` must be of numeric type (for binary "
... | [
"\n Check that the predictionsa are either probabilities of prob-vectors.\n "
] |
Please provide a description of the function:def _supervised_evaluation_error_checking(targets, predictions):
_raise_error_if_not_sarray(targets, "targets")
_raise_error_if_not_sarray(predictions, "predictions")
if (len(targets) != len(predictions)):
raise _ToolkitError(
"Input SArrays... | [
"\n Perform basic error checking for the evaluation metrics. Check\n types and sizes of the inputs.\n "
] |
Please provide a description of the function:def log_loss(targets, predictions, index_map=None):
r
_supervised_evaluation_error_checking(targets, predictions)
_check_prob_and_prob_vector(predictions)
_check_target_not_float(targets)
_check_index_map(index_map)
multiclass = predictions.dtype no... | [
"\n Compute the logloss for the given targets and the given predicted\n probabilities. This quantity is defined to be the negative of the sum\n of the log probability of each observation, normalized by the number of\n observations:\n\n .. math::\n\n \\textrm{logloss} = - \\frac{1}{N} \\sum_{i ... |
Please provide a description of the function:def max_error(targets, predictions):
r
_supervised_evaluation_error_checking(targets, predictions)
return _turicreate.extensions._supervised_streaming_evaluator(targets,
predictions, "max_error", {}) | [
"\n Compute the maximum absolute deviation between two SArrays.\n\n Parameters\n ----------\n targets : SArray[float or int]\n An Sarray of ground truth target values.\n\n predictions : SArray[float or int]\n The prediction that corresponds to each target value.\n This vector mus... |
Please provide a description of the function:def rmse(targets, predictions):
r
_supervised_evaluation_error_checking(targets, predictions)
return _turicreate.extensions._supervised_streaming_evaluator(targets,
predictions, "rmse", {}) | [
"\n Compute the root mean squared error between two SArrays.\n\n Parameters\n ----------\n targets : SArray[float or int]\n An Sarray of ground truth target values.\n\n predictions : SArray[float or int]\n The prediction that corresponds to each target value.\n This vector must h... |
Please provide a description of the function:def confusion_matrix(targets, predictions):
r
_supervised_evaluation_error_checking(targets, predictions)
_check_same_type_not_float(targets, predictions)
return _turicreate.extensions._supervised_streaming_evaluator(targets,
predictio... | [
"\n Compute the confusion matrix for classifier predictions.\n\n Parameters\n ----------\n targets : SArray\n Ground truth class labels (cannot be of type float).\n\n predictions : SArray\n The prediction that corresponds to each target value.\n This vector must have the same len... |
Please provide a description of the function:def accuracy(targets, predictions, average='micro'):
r
_supervised_evaluation_error_checking(targets, predictions)
_check_same_type_not_float(targets, predictions)
opts = {"average": average}
return _turicreate.extensions._supervised_streaming_evaluator(t... | [
"\n Compute the accuracy score; which measures the fraction of predictions made\n by the classifier that are exactly correct. The score lies in the range [0,1]\n with 0 being the worst and 1 being the best.\n\n Parameters\n ----------\n targets : SArray\n An SArray of ground truth class lab... |
Please provide a description of the function:def fbeta_score(targets, predictions, beta=1.0, average='macro'):
r
_supervised_evaluation_error_checking(targets, predictions)
_check_categorical_option_type('average', average,
['micro', 'macro', None])
_check_same_type_not_float(ta... | [
"\n Compute the F-beta score. The F-beta score is the weighted harmonic mean of\n precision and recall. The score lies in the range [0,1] with 1 being ideal\n and 0 being the worst.\n\n The `beta` value is the weight given to `precision` vs `recall` in the\n combined score. `beta=0` considers only pr... |
Please provide a description of the function:def f1_score(targets, predictions, average='macro'):
r
return fbeta_score(targets, predictions, beta = 1.0, average = average) | [
"\n Compute the F1 score (sometimes known as the balanced F-score or\n F-measure). The F1 score is commonly interpreted as the average of\n precision and recall. The score lies in the range [0,1] with 1 being ideal\n and 0 being the worst.\n\n The F1 score is defined as:\n\n .. math::\n ... |
Please provide a description of the function:def precision(targets, predictions, average='macro'):
r
_supervised_evaluation_error_checking(targets, predictions)
_check_categorical_option_type('average', average,
['micro', 'macro', None])
_check_same_type_not_float(targets, predi... | [
"\n\n Compute the precision score for classification tasks. The precision score\n quantifies the ability of a classifier to not label a `negative` example as\n `positive`. The precision score can be interpreted as the probability that\n a `positive` prediction made by the classifier is `positive`. The s... |
Please provide a description of the function:def auc(targets, predictions, average='macro', index_map=None):
r
_supervised_evaluation_error_checking(targets, predictions)
_check_categorical_option_type('average', average,
['macro', None])
_check_prob_and_prob_vector(predictions)... | [
"\n Compute the area under the ROC curve for the given targets and predictions.\n\n Parameters\n ----------\n targets : SArray\n An SArray containing the observed values. For binary classification,\n the alpha-numerically first category is considered the reference\n category.\n\n ... |
Please provide a description of the function:def get_library_meta(self):
'''
Fetches the meta data for the current library. The data could be in
the superlib meta data file. If we can't find the data None is returned.
'''
parent_dir = os.path.dirname(self.library_dir)
if ... | [] |
Please provide a description of the function:def convert(model, feature_names = None, target = 'target', force_32bit_float = True):
return _MLModel(_convert_tree_ensemble(model, feature_names, target, force_32bit_float = force_32bit_float)) | [
"\n Convert a trained XGBoost model to Core ML format.\n\n Parameters\n ----------\n decision_tree : Booster\n A trained XGboost tree model.\n\n feature_names: [str] | str\n Names of input features that will be exposed in the Core ML model\n interface.\n\n Can be set to on... |
Please provide a description of the function:def dumps(obj):
(data, schema) = to_serializable(obj)
return _json.dumps({'data': data, 'schema': schema}) | [
"\n Dumps a serializable object to JSON. This API maps to the Python built-in\n json dumps method, with a few differences:\n\n * The return value is always valid JSON according to RFC 7159.\n * The input can be any of the following types:\n - SFrame\n - SArray\n - SGraph\n - ... |
Please provide a description of the function:def draw_strokes(stroke_based_drawings):
single_input = False
if (not isinstance(stroke_based_drawings, _tc.SArray)
and not isinstance(stroke_based_drawings, list)):
raise _ToolkitError("Input to draw_strokes must be of type "
+ "tu... | [
"\n Visualizes drawings (ground truth or predictions) by\n returning images to represent the stroke-based data from \n the user.\n\n Parameters\n ----------\n stroke_based_drawings: SArray or list\n An `SArray` of type `list`. Each element in the SArray \n should be a list of strokes... |
Please provide a description of the function:def fit(self, data):
_raise_error_if_not_sframe(data, "data")
self.__proxy__.fit(data)
return self | [
"\n Fit a transformer using the SFrame `data`.\n\n Parameters\n ----------\n data : SFrame\n The data used to fit the transformer.\n\n Returns\n -------\n self (A fitted version of the object)\n\n See Also\n --------\n transform, fit_t... |
Please provide a description of the function:def _get_summary_struct(self):
section = []
section_titles = ['Attributes']
for f in self._list_fields():
section.append( ("%s" % f,"%s"% f) )
return ([section], section_titles) | [
"\n Returns a structured description of the model, including (where\n relevant) the schema of the training data, description of the training\n data, 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 extract_features(self, dataset, missing_value_action='auto'):
_raise_error_if_not_sframe(dataset, "dataset")
if missing_value_action == 'auto':
missing_value_action = select_default_missing_value_policy(self,
'extr... | [
"\n For each example in the dataset, extract the leaf indices of\n each tree as features.\n\n For multiclass classification, each leaf index contains #num_class\n numbers.\n\n The returned feature vectors can be used as input to train another\n supervised learning model suc... |
Please provide a description of the function:def _extract_features_with_missing(self, dataset, tree_id = 0,
missing_value_action = 'auto'):
# Extract the features from only one tree.
sf = dataset
sf['leaf_id'] = self.extract_features(dataset, missing_value_action)\
... | [
"\n Extract features along with all the missing features associated with\n a dataset.\n\n Parameters\n ----------\n dataset: bool\n Dataset on which to make predictions.\n\n missing_value_action: str, optional\n Action to perform when missing values ar... |
Please provide a description of the function:def _dump_to_text(self, with_stats):
return tc.extensions._xgboost_dump_model(self.__proxy__, with_stats=with_stats, format='text') | [
"\n Dump the models into a list of strings. Each\n string is a text representation of a tree.\n\n Parameters\n ----------\n with_stats : bool\n If true, include node statistics in the output.\n\n Returns\n -------\n out : SFrame\n A table... |
Please provide a description of the function:def _get_summary_struct(self):
data_fields = [
('Number of examples', 'num_examples'),
('Number of feature columns', 'num_features'),
('Number of unpacked features', 'num_unpacked_features')]
if 'num_classes' in se... | [
"\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 convert(model, input_features, output_features):
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
_sklearn_util.check_expected_type(model, _ensemble.GradientBoostingRegressor)
def is_gb... | [
"Convert a boosted tree model to protobuf format.\n\n Parameters\n ----------\n decision_tree : GradientBoostingRegressor\n A trained scikit-learn tree model.\n\n input_feature: [str]\n Name of the input columns.\n\n output_features: str\n Name of the output column.\n\n Return... |
Please provide a description of the function:def _sort_topk_votes(x, k):
y = sorted(x.items(), key=lambda x: x[1], reverse=True)[:k]
return [{'class': i[0], 'votes': i[1]} for i in y] | [
"\n Sort a dictionary of classes and corresponding vote totals according to the\n votes, then truncate to the highest 'k' classes.\n "
] |
Please provide a description of the function:def _construct_auto_distance(features, column_types):
## Put input features into buckets based on type.
numeric_ftrs = []
string_ftrs = []
dict_ftrs = []
for ftr in features:
try:
ftr_type = column_types[ftr]
except:
... | [
"\n Construct a composite distance function for a set of features, based on the\n types of those features.\n\n NOTE: This function is very similar to\n `:func:_nearest_neighbors.choose_auto_distance`. The function is separate\n because the auto-distance logic different than for each nearest\n neig... |
Please provide a description of the function:def create(dataset, target, features=None, distance=None, verbose=True):
## Set up
## ------
start_time = _time.time()
## Validation and preprocessing
## ----------------------------
## 'dataset' must be a non-empty SFrame
_raise_error_if... | [
"\n Create a\n :class:`~turicreate.nearest_neighbor_classifier.NearestNeighborClassifier`\n model. This model predicts the class of a query instance by finding the most\n common class among the query's nearest neighbors.\n\n .. warning::\n\n The 'dot_product' distance is deprecated and will be... |
Please provide a description of the function:def _load_version(cls, state, version):
assert(version == cls._PYTHON_NN_CLASSIFIER_MODEL_VERSION)
knn_model = _tc.nearest_neighbors.NearestNeighborsModel(state['knn_model'])
del state['knn_model']
state['_target_type'] = eval(state['... | [
"\n A function to load a previously saved NearestNeighborClassifier model.\n\n Parameters\n ----------\n unpickler : GLUnpickler\n A GLUnpickler file handler.\n\n version : int\n Version number maintained by the class writer.\n "
] |
Please provide a description of the function:def classify(self, dataset, max_neighbors=10, radius=None, verbose=True):
## Validate the query 'dataset'. Note that the 'max_neighbors' and
# 'radius' parameters are validated by the nearest neighbor model's
# query method.
_raise... | [
"\n Return the predicted class for each observation in *dataset*. This\n prediction is made based on the closest neighbors stored in the nearest\n neighbors classifier model.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset of new observations. Must inclu... |
Please provide a description of the function:def predict(self, dataset, max_neighbors=10, radius=None,
output_type='class', verbose=True):
ystar = self.classify(dataset=dataset, max_neighbors=max_neighbors,
radius=radius, verbose=verbose)
if outpu... | [
"\n Return predicted class labels for instances in *dataset*. This model\n makes predictions based on the closest neighbors stored in the nearest\n neighbors classifier model.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset of new observations. Must incl... |
Please provide a description of the function:def predict_topk(self, dataset, max_neighbors=10, radius=None, k=3,
verbose=False):
## Validate the number of results to return. Note that the
# 'max_neighbors' and 'radius' parameters are validated by the nearest
# n... | [
"\n Return top-k most likely predictions for each observation in\n ``dataset``. Predictions are returned as an SFrame with three columns:\n `row_id`, `class`, and `probability`.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset of new observations. Must in... |
Please provide a description of the function:def evaluate(self, dataset, metric='auto', max_neighbors=10, radius=None):
## Validate the metric name
_raise_error_evaluation_metric_is_valid(metric,
['auto', 'accuracy', 'confusion_matrix', 'roc_curve'])
## Make sure t... | [
"\n Evaluate the model's predictive accuracy. This is done by predicting the\n target class for instances in a new dataset and comparing to known\n target values.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset of new observations. Must include columns w... |
Please provide a description of the function:def _compact_class_repr(obj):
dict_str_list = []
post_repr_string = ""
# If features are present, then shorten it.
init_func = obj.__init__
if _sys.version_info.major == 2:
init_func = init_func.__func__
... | [
" A compact version of __repr__ for each of the steps.\n "
] |
Please provide a description of the function:def _preprocess(self, data):
transformed_data = _copy(data)
for name, step in self._transformers[:-1]:
transformed_data = step.fit_transform(transformed_data)
if type(transformed_data) != _tc.SFrame:
raise Runt... | [
"\n Internal function to perform fit_transform() on all but last step.\n "
] |
Please provide a description of the function:def fit(self, data):
if not self._transformers:
return
transformed_data = self._preprocess(data)
final_step = self._transformers[-1]
final_step[1].fit(transformed_data) | [
"\n Fits a transformer using the SFrame `data`.\n\n Parameters\n ----------\n data : SFrame\n The data used to fit the transformer.\n\n Returns\n -------\n self (A fitted object)\n\n See Also\n --------\n transform, fit_transform\n\n ... |
Please provide a description of the function:def fit_transform(self, data):
if not self._transformers:
return self._preprocess(data)
transformed_data = self._preprocess(data)
final_step = self._transformers[-1]
return final_step[1].fit_transform(transformed_data) | [
"\n First fit a transformer using the SFrame `data` and then return a transformed\n version of `data`.\n\n Parameters\n ----------\n data : SFrame\n The data used to fit the transformer. The same data is then also\n transformed.\n\n Returns\n --... |
Please provide a description of the function:def transform(self, data):
transformed_data = _copy(data)
for name, step in self._transformers:
transformed_data = step.transform(transformed_data)
if type(transformed_data) != _tc.SFrame:
raise TypeError("The ... | [
"\n Transform the SFrame `data` using a fitted model.\n\n Parameters\n ----------\n data : SFrame\n The data to be transformed.\n\n Returns\n -------\n A transformed SFrame.\n\n Returns\n -------\n out: SFrame\n A transform... |
Please provide a description of the function:def _load_version(cls, unpickler, version):
obj = unpickler.load()
return TransformerChain(obj._state["steps"]) | [
"\n An function to load an object with a specific version of the class.\n\n Parameters\n ----------\n pickler : file\n A GLUnpickler file handle.\n\n version : int\n A version number as maintained by the class writer.\n "
] |
Please provide a description of the function:def create(graph, reset_probability=0.15,
threshold=1e-2,
max_iterations=20,
_single_precision=False,
_distributed='auto',
verbose=True):
from turicreate._cython.cy_server import QuietProgress
if not isinst... | [
"\n Compute the PageRank for each vertex in the graph. Return a model object\n with total PageRank as well as the PageRank value for each vertex in the\n graph.\n\n Parameters\n ----------\n graph : SGraph\n The graph on which to compute the pagerank value.\n\n reset_probability : float,... |
Please provide a description of the function:def init(version = None, command = None, options = None):
options = to_seq(options)
command = to_seq(command)
# Information about the gcc command...
# The command.
command = to_seq(common.get_invocation_command('gcc', 'g++', command))
# The... | [
"\n Initializes the gcc toolset for the given version. If necessary, command may\n be used to specify where the compiler is located. The parameter 'options' is a\n space-delimited list of options, each one specified as\n <option-name>option-value. Valid option names are: cxxflags, linkfl... |
Please provide a description of the function:def init_link_flags(toolset, linker, condition):
toolset_link = toolset + '.link'
if linker == 'gnu':
# Strip the binary when no debugging is needed. We use --strip-all flag
# as opposed to -s since icc (intel's compiler) is generally
# o... | [
"\n Now, the vendor specific flags.\n The parameter linker can be either gnu, darwin, osf, hpux or sun.\n "
] |
Please provide a description of the function:def add_dependency (self, targets, sources):
if isinstance (targets, str):
targets = [targets]
if isinstance (sources, str):
sources = [sources]
assert is_iterable(targets)
assert is_iterable(sources)
... | [
"Adds a dependency from 'targets' to 'sources'\n\n Both 'targets' and 'sources' can be either list\n of target names, or a single target name.\n "
] |
Please provide a description of the function:def get_target_variable(self, targets, variable):
if isinstance(targets, str):
targets = [targets]
assert is_iterable(targets)
assert isinstance(variable, basestring)
return bjam_interface.call('get-target-variable', targ... | [
"Gets the value of `variable` on set on the first target in `targets`.\n\n Args:\n targets (str or list): one or more targets to get the variable from.\n variable (str): the name of the variable\n\n Returns:\n the value of `variable` set on `targets` (list)\n\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.