INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Returns suffix that should be used when generating target of 'type',
with the specified properties. If not suffix were specified for
'type', returns suffix for base type, if any. | def generated_target_ps(is_suffix, type, prop_set):
""" Returns suffix that should be used when generating target of 'type',
with the specified properties. If not suffix were specified for
'type', returns suffix for base type, if any.
"""
if __debug__:
from .property_set import Prope... |
Returns file type given it's name. If there are several dots in filename,
tries each suffix. E.g. for name of "file.so.1.2" suffixes "2", "1", and
"so" will be tried. | def type(filename):
""" Returns file type given it's name. If there are several dots in filename,
tries each suffix. E.g. for name of "file.so.1.2" suffixes "2", "1", and
"so" will be tried.
"""
assert isinstance(filename, basestring)
while 1:
filename, suffix = os.path.splitext... |
Register the given type on the specified OSes, or on remaining OSes
if os is not specified. This rule is injected into each of the type
modules for the sake of convenience. | def register_type (type, suffixes, base_type = None, os = []):
""" Register the given type on the specified OSes, or on remaining OSes
if os is not specified. This rule is injected into each of the type
modules for the sake of convenience.
"""
assert isinstance(type, basestring)
assert ... |
keys of kwargs must be the names passed to __init__(...) as `column_names` | def print_row(self, **kwargs):
'''
keys of kwargs must be the names passed to __init__(...) as `column_names`
'''
meta_string = '|'
for key in self.column_names:
float_specifier = ''
if isinstance(kwargs[key], float):
float_specifier = '.3f... |
Parameters
----------
features : list[str] | str | None, optional
Column names of features to be transformed. If None, all columns
are selected. If string, that column is transformed. If list of strings,
this list of column names is selected.
exclude : list[str] | str | None, option... | def process_features(features, exclude):
"""
Parameters
----------
features : list[str] | str | None, optional
Column names of features to be transformed. If None, all columns
are selected. If string, that column is transformed. If list of strings,
this list of column names is se... |
Pretty print a list to be readable. | def pretty_print_list(lst, name = 'features', repr_format=True):
""" Pretty print a list to be readable.
"""
if not lst or len(lst) < 8:
if repr_format:
return lst.__repr__()
else:
return ', '.join(map(str, lst))
else:
topk = ', '.join(map(str, lst[:3]))
... |
Get the keras layer name from the activation name. | def _get_elementwise_name_from_keras_layer(keras_layer):
"""
Get the keras layer name from the activation name.
"""
mode = keras_layer.mode
if mode == 'sum':
return 'ADD'
elif mode == 'mul':
return 'MULTIPLY'
elif mode == 'concat':
if len(keras_layer.input_shape[0]) =... |
Test if a 3D (H,W,C) matrix x has the same element in each (H,W) matrix for each channel | def _same_elements_per_channel(x):
"""
Test if a 3D (H,W,C) matrix x has the same element in each (H,W) matrix for each channel
"""
eps = 1e-5
dims = x.shape
for c in range(dims[-1]):
xc = x[:,:,c].flatten()
if not np.all(np.absolute(xc - xc[0]) < eps):
return False
... |
Convert a dense layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_dense(builder, layer, input_names, output_names, keras_layer):
"""Convert a dense layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output... |
Convert an activation layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_activation(builder, layer, input_names, output_names, keras_layer):
"""Convert an activation layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input... |
Convert padding layer from keras to coreml.
Keras only supports zero padding at this time.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_padding(builder, layer, input_names, output_names, keras_layer):
"""Convert padding layer from keras to coreml.
Keras only supports zero padding at this time.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural networ... |
Convert padding layer from keras to coreml.
Keras only supports zero padding at this time.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_cropping(builder, layer, input_names, output_names, keras_layer):
"""Convert padding layer from keras to coreml.
Keras only supports zero padding at this time.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural netwo... |
Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_upsample(builder, layer, input_names, output_names, keras_layer):
"""Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and... |
Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_convolution(builder, layer, input_names, output_names, keras_layer):
"""Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input ... |
Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_convolution1d(builder, layer, input_names, output_names, keras_layer):
"""Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get inpu... |
Convert an LSTM layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_lstm(builder, layer, input_names, output_names, keras_layer):
"""Convert an LSTM layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
hidden_size = keras_la... |
Convert an SimpleRNN layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_simple_rnn(builder, layer, input_names, output_names, keras_layer):
"""Convert an SimpleRNN layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input ... |
Convert a GRU layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_gru(builder, layer, input_names, output_names, keras_layer):
"""Convert a GRU layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
hidden_size = keras_layer... |
Convert a bidirectional layer from keras to coreml.
Currently assumes the units are LSTMs.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_bidirectional(builder, layer, input_names, output_names, keras_layer):
"""Convert a bidirectional layer from keras to coreml.
Currently assumes the units are LSTMs.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A ne... |
Parameters
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_batchnorm(builder, layer, input_names, output_names, keras_layer):
"""
Parameters
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], ... |
Convert a flatten layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_flatten(builder, layer, input_names, output_names, keras_layer):
"""Convert a flatten layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output... |
Convert a softmax layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_softmax(builder, layer, input_names, output_names, keras_layer):
"""Convert a softmax layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output... |
Convert a softmax layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | def convert_permute(builder, layer, input_names, output_names, keras_layer):
"""Convert a softmax layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output... |
customized submit script, that submit nslave jobs, each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
nslave number of slave process to start up
args arguments to launch each job
this usually includes th... | def sge_submit(nslave, worker_args, worker_envs):
"""
customized submit script, that submit nslave jobs, each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
nslave number of slave process to start up
args arg... |
Returns a string representing the ast.
:param ast: the ast to print.
:param indent: how far to indent a newline.
:param newline: The newline character. | def dump_ast(ast, indent=' ', newline='\n'):
'''
Returns a string representing the ast.
:param ast: the ast to print.
:param indent: how far to indent a newline.
:param newline: The newline character.
'''
visitor = ASTPrinter(indent=indent, level=0, newline=newline)
v... |
Pretty print an ast node.
:param ast: the ast to print.
:param indent: how far to indent a newline.
:param initlevel: starting indent level
:param newline: The newline character.
:param file: file object to print to
To print a short ast you may want to use::
node = ast.par... | def print_ast(ast, indent=' ', initlevel=0, newline='\n', file=sys.stdout):
'''
Pretty print an ast node.
:param ast: the ast to print.
:param indent: how far to indent a newline.
:param initlevel: starting indent level
:param newline: The newline character.
:param file: file object to ... |
Convert a ctypes pointer array to a numpy array. | def ctypes2numpy(cptr, length, dtype):
"""Convert a ctypes pointer array to a numpy array.
"""
if not isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
raise RuntimeError('expected float pointer')
res = np.zeros(length, dtype=dtype)
if not ctypes.memmove(res.ctypes.data, cptr, length * res.s... |
Extract internal data from pd.DataFrame | def _maybe_from_pandas(data, feature_names, feature_types):
""" Extract internal data from pd.DataFrame """
try:
import pandas as pd
except ImportError:
return data, feature_names, feature_types
if not isinstance(data, pd.DataFrame):
return data, feature_names, feature_types
... |
Initialize data from a CSR matrix. | def _init_from_csr(self, csr):
"""
Initialize data from a CSR matrix.
"""
if len(csr.indices) != len(csr.data):
raise ValueError('length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data)))
self.handle = ctypes.c_void_p()
_check_call(_LIB.XGDMatrixCrea... |
Initialize data from a CSC matrix. | def _init_from_csc(self, csc):
"""
Initialize data from a CSC matrix.
"""
if len(csc.indices) != len(csc.data):
raise ValueError('length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data)))
self.handle = ctypes.c_void_p()
_check_call(_LIB.XGDMatrixCrea... |
Initialize data from a 2-D numpy matrix. | def _init_from_npy2d(self, mat, missing):
"""
Initialize data from a 2-D numpy matrix.
"""
if len(mat.shape) != 2:
raise ValueError('Input numpy.ndarray must be 2 dimensional')
data = np.array(mat.reshape(mat.size), dtype=np.float32)
self.handle = ctypes.c_voi... |
Get float property from the DMatrix.
Parameters
----------
field: str
The field name of the information
Returns
-------
info : array
a numpy array of float information of the data | def get_float_info(self, field):
"""Get float property from the DMatrix.
Parameters
----------
field: str
The field name of the information
Returns
-------
info : array
a numpy array of float information of the data
"""
le... |
Get unsigned integer property from the DMatrix.
Parameters
----------
field: str
The field name of the information
Returns
-------
info : array
a numpy array of float information of the data | def get_uint_info(self, field):
"""Get unsigned integer property from the DMatrix.
Parameters
----------
field: str
The field name of the information
Returns
-------
info : array
a numpy array of float information of the data
"""
... |
Set float type property into the DMatrix.
Parameters
----------
field: str
The field name of the information
data: numpy array
The array ofdata to be set | def set_float_info(self, field, data):
"""Set float type property into the DMatrix.
Parameters
----------
field: str
The field name of the information
data: numpy array
The array ofdata to be set
"""
_check_call(_LIB.XGDMatrixSetFloatInfo... |
Set uint type property into the DMatrix.
Parameters
----------
field: str
The field name of the information
data: numpy array
The array ofdata to be set | def set_uint_info(self, field, data):
"""Set uint type property into the DMatrix.
Parameters
----------
field: str
The field name of the information
data: numpy array
The array ofdata to be set
"""
_check_call(_LIB.XGDMatrixSetUIntInfo(se... |
Save DMatrix to an XGBoost buffer.
Parameters
----------
fname : string
Name of the output buffer file.
silent : bool (optional; default: True)
If set, the output is suppressed. | def save_binary(self, fname, silent=True):
"""Save DMatrix to an XGBoost buffer.
Parameters
----------
fname : string
Name of the output buffer file.
silent : bool (optional; default: True)
If set, the output is suppressed.
"""
_check_call... |
Get the number of rows in the DMatrix.
Returns
-------
number of rows : int | def num_row(self):
"""Get the number of rows in the DMatrix.
Returns
-------
number of rows : int
"""
ret = ctypes.c_ulong()
_check_call(_LIB.XGDMatrixNumRow(self.handle,
ctypes.byref(ret)))
return ret.value |
Get the number of columns (features) in the DMatrix.
Returns
-------
number of columns : int | def num_col(self):
"""Get the number of columns (features) in the DMatrix.
Returns
-------
number of columns : int
"""
ret = ctypes.c_uint()
_check_call(_LIB.XGDMatrixNumCol(self.handle,
ctypes.byref(ret)))
return ... |
Slice the DMatrix and return a new DMatrix that only contains `rindex`.
Parameters
----------
rindex : list
List of indices to be selected.
Returns
-------
res : DMatrix
A new DMatrix containing only selected indices. | def slice(self, rindex):
"""Slice the DMatrix and return a new DMatrix that only contains `rindex`.
Parameters
----------
rindex : list
List of indices to be selected.
Returns
-------
res : DMatrix
A new DMatrix containing only selected i... |
Set feature names (column labels).
Parameters
----------
feature_names : list or None
Labels for features. None will reset existing feature names | def feature_names(self, feature_names):
"""Set feature names (column labels).
Parameters
----------
feature_names : list or None
Labels for features. None will reset existing feature names
"""
if not feature_names is None:
# validate feature name
... |
Set feature types (column types).
This is for displaying the results and unrelated
to the learning process.
Parameters
----------
feature_types : list or None
Labels for features. None will reset existing feature names | def feature_types(self, feature_types):
"""Set feature types (column types).
This is for displaying the results and unrelated
to the learning process.
Parameters
----------
feature_types : list or None
Labels for features. None will reset existing feature na... |
Update for one iteration, with objective function calculated internally.
Parameters
----------
dtrain : DMatrix
Training data.
iteration : int
Current iteration number.
fobj : function
Customized objective function. | def update(self, dtrain, iteration, fobj=None):
"""
Update for one iteration, with objective function calculated internally.
Parameters
----------
dtrain : DMatrix
Training data.
iteration : int
Current iteration number.
fobj : function
... |
Boost the booster for one iteration, with customized gradient statistics.
Parameters
----------
dtrain : DMatrix
The training DMatrix.
grad : list
The first order of gradient.
hess : list
The second order of gradient. | def boost(self, dtrain, grad, hess):
"""
Boost the booster for one iteration, with customized gradient statistics.
Parameters
----------
dtrain : DMatrix
The training DMatrix.
grad : list
The first order of gradient.
hess : list
... |
Evaluate a set of data.
Parameters
----------
evals : list of tuples (DMatrix, string)
List of items to be evaluated.
iteration : int
Current iteration.
feval : function
Custom evaluation function.
Returns
-------
res... | def eval_set(self, evals, iteration=0, feval=None):
# pylint: disable=invalid-name
"""Evaluate a set of data.
Parameters
----------
evals : list of tuples (DMatrix, string)
List of items to be evaluated.
iteration : int
Current iteration.
... |
Predict with data.
NOTE: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call bst.copy() to make copies
of model object and then call predict
Parameters... | def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False):
"""
Predict with data.
NOTE: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call... |
Save the model to a in memory buffer represetation
Returns
-------
a in memory buffer represetation of the model | def save_raw(self):
"""
Save the model to a in memory buffer represetation
Returns
-------
a in memory buffer represetation of the model
"""
length = ctypes.c_ulong()
cptr = ctypes.POINTER(ctypes.c_char)()
_check_call(_LIB.XGBoosterGetModelRaw(sel... |
Load the model from a file.
Parameters
----------
fname : string or a memory buffer
Input file name or memory buffer(see also save_raw) | def load_model(self, fname):
"""
Load the model from a file.
Parameters
----------
fname : string or a memory buffer
Input file name or memory buffer(see also save_raw)
"""
if isinstance(fname, STRING_TYPES): # assume file name
if os.path... |
Dump model into a text file.
Parameters
----------
foout : string
Output file name.
fmap : string, optional
Name of the file containing feature map names.
with_stats : bool (optional)
Controls whether the split statistics are output. | def dump_model(self, fout, fmap='', with_stats=False):
"""
Dump model into a text file.
Parameters
----------
foout : string
Output file name.
fmap : string, optional
Name of the file containing feature map names.
with_stats : bool (option... |
Returns the dump the model as a list of strings. | def get_dump(self, fmap='', with_stats=False):
"""
Returns the dump the model as a list of strings.
"""
length = ctypes.c_ulong()
sarr = ctypes.POINTER(ctypes.c_char_p)()
if self.feature_names is not None and fmap == '':
flen = int(len(self.feature_names))
... |
Get feature importance of each feature.
Parameters
----------
fmap: str (optional)
The name of feature map file | def get_fscore(self, fmap=''):
"""Get feature importance of each feature.
Parameters
----------
fmap: str (optional)
The name of feature map file
"""
trees = self.get_dump(fmap)
fmap = {}
for tree in trees:
for line in tree.split('\... |
Validate Booster and data's feature_names are identical.
Set feature_names and feature_types from DMatrix | def _validate_features(self, data):
"""
Validate Booster and data's feature_names are identical.
Set feature_names and feature_types from DMatrix
"""
if self.feature_names is None:
self.feature_names = data.feature_names
self.feature_types = data.feature_t... |
Disassemble a code object.
:param co: code object
:param lasti: internal
:yields: Instructions. | def disassembler(co, lasti= -1):
"""Disassemble a code object.
:param co: code object
:param lasti: internal
:yields: Instructions.
"""
code = co.co_code
labels = dis.findlabels(code)
linestarts = dict(dis.findlinestarts(co))
i = 0
extended_arg = 0
lineno = 0
... |
Matches all elements of 'list' agains the 'pattern'
and returns a list of the elements indicated by indices of
all successfull matches. If 'indices' is omitted returns
a list of first paranthethised groups of all successfull
matches. | def transform (list, pattern, indices = [1]):
""" Matches all elements of 'list' agains the 'pattern'
and returns a list of the elements indicated by indices of
all successfull matches. If 'indices' is omitted returns
a list of first paranthethised groups of all successfull
matches.
... |
Replaces occurrences of a match string in a given
string and returns the new string. The match string
can be a regex expression.
Args:
s (str): the string to modify
pattern (str): the search expression
replacement (str): the string to replace each match with | def replace(s, pattern, replacement):
"""Replaces occurrences of a match string in a given
string and returns the new string. The match string
can be a regex expression.
Args:
s (str): the string to modify
pattern (str): the search expression
replacement (str): the... |
Replaces occurrences of a match string in a given list of strings and returns
a list of new strings. The match string can be a regex expression.
Args:
items (list): the list of strings to modify.
match (str): the search expression.
replacement (str): the string to replace ... | def replace_list(items, match, replacement):
"""Replaces occurrences of a match string in a given list of strings and returns
a list of new strings. The match string can be a regex expression.
Args:
items (list): the list of strings to modify.
match (str): the search expression... |
Create a topic model from the given data set. A topic model assumes each
document is a mixture of a set of topics, where for each topic some words
are more likely than others. One statistical approach to do this is called a
"topic model". This method learns a topic model for the given document
collectio... | def create(dataset,
num_topics=10,
initial_topics=None,
alpha=None,
beta=.1,
num_iterations=10,
num_burnin=5,
associations=None,
verbose=False,
print_interval=10,
validation_set=None,
method='auto'):... |
Compute the perplexity of a set of test documents given a set
of predicted topics.
Let theta be the matrix of document-topic probabilities, where
theta_ik = p(topic k | document i). Let Phi be the matrix of term-topic
probabilities, where phi_jk = p(word j | topic k).
Then for each word in each do... | def perplexity(test_data, predictions, topics, vocabulary):
"""
Compute the perplexity of a set of test documents given a set
of predicted topics.
Let theta be the matrix of document-topic probabilities, where
theta_ik = p(topic k | document i). Let Phi be the matrix of term-topic
probabilities... |
Returns a structured description of the model, including (where relevant)
the schema of the training data, description of the training data,
training statistics, and model hyperparameters.
Returns
-------
sections : list (of list of tuples)
A list of summary sections... | def _get_summary_struct(self):
"""
Returns a structured description of the model, including (where relevant)
the schema of the training data, description of the training data,
training statistics, and model hyperparameters.
Returns
-------
sections : list (of lis... |
Return the value of a given field. The list of all queryable fields is
detailed below, and can be obtained with the
:py:func:`~TopicModel._list_fields` method.
+-----------------------+----------------------------------------------+
| Field | Description ... | def _get(self, field):
"""
Return the value of a given field. The list of all queryable fields is
detailed below, and can be obtained with the
:py:func:`~TopicModel._list_fields` method.
+-----------------------+----------------------------------------------+
| Fiel... |
Return a dictionary of statistics collected during creation of the
model. These statistics are also available with the ``get`` method and
are described in more detail in that method's documentation.
Returns
-------
out : dict
Dictionary of statistics compiled during ... | def _training_stats(self):
"""
Return a dictionary of statistics collected during creation of the
model. These statistics are also available with the ``get`` method and
are described in more detail in that method's documentation.
Returns
-------
out : dict
... |
Get the words associated with a given topic. The score column is the
probability of choosing that word given that you have chosen a
particular topic.
Parameters
----------
topic_ids : list of int, optional
The topics to retrieve words. Topic ids are zero-based.
... | def get_topics(self, topic_ids=None, num_words=5, cdf_cutoff=1.0,
output_type='topic_probabilities'):
"""
Get the words associated with a given topic. The score column is the
probability of choosing that word given that you have chosen a
particular topic.
Par... |
Use the model to predict topics for each document. The provided
`dataset` should be an SArray object where each element is a dict
representing a single document in bag-of-words format, where keys
are words and values are their corresponding counts. If `dataset` is
an SFrame, then it must... | def predict(self, dataset, output_type='assignment', num_burnin=None):
"""
Use the model to predict topics for each document. The provided
`dataset` should be an SArray object where each element is a dict
representing a single document in bag-of-words format, where keys
are words... |
Convert from corner bounding box to center/shape | def bbox_to_ybox(bbox):
"""Convert from corner bounding box to center/shape"""
return [
(bbox[1] + bbox[3]) / 2,
(bbox[0] + bbox[2]) / 2,
(bbox[3] - bbox[1]),
(bbox[2] - bbox[0]),
] |
Performs some sanity checks on the SFrame provided as input to
`turicreate.drawing_classifier.create` and raises a ToolkitError
if something in the dataset is missing or wrong. | def _raise_error_if_not_drawing_classifier_input_sframe(
dataset, feature, target):
"""
Performs some sanity checks on the SFrame provided as input to
`turicreate.drawing_classifier.create` and raises a ToolkitError
if something in the dataset is missing or wrong.
"""
from turicreate.toolki... |
Create a :class:`DrawingClassifier` model.
Parameters
----------
dataset : SFrame
Input data. The columns named by the ``feature`` and ``target``
parameters will be extracted for training the drawing classifier.
target : string
Name of the column containing the target variable.... | def create(input_dataset, target, feature=None, validation_set='auto',
warm_start='auto', batch_size=256,
max_iterations=100, verbose=True):
"""
Create a :class:`DrawingClassifier` model.
Parameters
----------
dataset : SFrame
Input data. The columns named by the ``... |
Save the model in Core ML format. The Core ML model takes a grayscale
drawing of fixed size as input and produces two outputs:
`classLabel` and `labelProbabilities`.
The first one, `classLabel` is an integer or string (depending on the
classes the model was trained on) to store the la... | def export_coreml(self, filename, verbose=False):
"""
Save the model in Core ML format. The Core ML model takes a grayscale
drawing of fixed size as input and produces two outputs:
`classLabel` and `labelProbabilities`.
The first one, `classLabel` is an integer or string (depe... |
Predict with probabilities. The core prediction part that both
`evaluate` and `predict` share.
Returns an SFrame with two columns, self.target, and "probabilities".
The column with column name, self.target, contains the predictions made
by the model for the provided dataset.
... | def _predict_with_probabilities(self, input_dataset, batch_size=None,
verbose=True):
"""
Predict with probabilities. The core prediction part that both
`evaluate` and `predict` share.
Returns an SFrame with two columns, self.target, and "probabilities".
The column wit... |
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the feature and target columns used for model t... | def evaluate(self, dataset, metric='auto', batch_size=None, verbose=True):
"""
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must inc... |
Return top-k predictions for the ``dataset``, using the trained model.
Predictions are returned as an SFrame with three columns: `id`,
`class`, and `probability` or `rank`, depending on the ``output_type``
parameter.
Parameters
----------
dataset : SFrame | SArray | turi... | def predict_topk(self, dataset, output_type="probability", k=3,
batch_size=None):
"""
Return top-k predictions for the ``dataset``, using the trained model.
Predictions are returned as an SFrame with three columns: `id`,
`class`, and `probability` or `rank`, depending on the ``ou... |
Predict on an SFrame or SArray of drawings, or on a single drawing.
Parameters
----------
data : SFrame | SArray | tc.Image | list
The drawing(s) on which to perform drawing classification.
If dataset is an SFrame, it must have a column with the same name
as ... | def predict(self, data, output_type='class', batch_size=None, verbose=True):
"""
Predict on an SFrame or SArray of drawings, or on a single drawing.
Parameters
----------
data : SFrame | SArray | tc.Image | list
The drawing(s) on which to perform drawing classificati... |
Parameters
----------
dataset: SFrame
SFrame of images | def extract_features(self, dataset, feature, batch_size=64, verbose=False):
"""
Parameters
----------
dataset: SFrame
SFrame of images
"""
from ._mxnet._mx_sframe_iter import SFrameImageIter as _SFrameImageIter
from six.moves.queue import Queue as _Que... |
Parameters
----------
mode: str ('classifier', 'regressor' or None)
Mode of the converted coreml model.
When mode = 'classifier', a NeuralNetworkClassifier spec will be constructed.
When mode = 'regressor', a NeuralNetworkRegressor spec will be constructed.
R... | def get_coreml_model(self, mode = 'classifier'):
"""
Parameters
----------
mode: str ('classifier', 'regressor' or None)
Mode of the converted coreml model.
When mode = 'classifier', a NeuralNetworkClassifier spec will be constructed.
When mode = 'regr... |
Takes an mxnet parameter collect (from Block.collect_params()) and
subsets it with the parameters available in this base network. | def available_parameters_subset(self, mx_params):
"""
Takes an mxnet parameter collect (from Block.collect_params()) and
subsets it with the parameters available in this base network.
"""
from copy import copy
from collections import OrderedDict
subset_params = co... |
Return an SFrame containing a bag of words representation of each column. | def _BOW_FEATURE_EXTRACTOR(sf, target=None):
"""
Return an SFrame containing a bag of words representation of each column.
"""
if isinstance(sf, dict):
out = _tc.SArray([sf]).unpack('')
elif isinstance(sf, _tc.SFrame):
out = sf.__copy__()
else:
raise ValueError("Unrecogni... |
Create a model that trains a classifier to classify text from a
collection of documents. The model is a
:class:`~turicreate.logistic_classifier.LogisticClassifier` model trained
using a bag-of-words representation of the text dataset.
Parameters
----------
dataset : SFrame
Contains one or... | def create(dataset, target, features = None, drop_stop_words = True,
word_count_threshold = 2, method = 'auto', validation_set = 'auto',
max_iterations = 10):
"""
Create a model that trains a classifier to classify text from a
collection of documents. The model is a
:class:`~turicr... |
Returns a list of names of columns that are string type. | def _get_str_columns(sf):
"""
Returns a list of names of columns that are string type.
"""
return [name for name in sf.column_names() if sf[name].dtype == str] |
Return predictions for ``dataset``, using the trained model.
Parameters
----------
dataset : SFrame
dataset of new observations. Must include columns with the same
names as the features used for model training, but does not require
a target column. Additional... | def predict(self, dataset, output_type='class'):
"""
Return predictions for ``dataset``, using the trained model.
Parameters
----------
dataset : SFrame
dataset of new observations. Must include columns with the same
names as the features used for model t... |
Return a classification, for each example in the ``dataset``, using the
trained model. The output SFrame contains predictions as both class
labels as well as probabilities that the predicted value is the
associated label.
Parameters
----------
dataset : SFrame
... | def classify(self, dataset):
"""
Return a classification, for each example in the ``dataset``, using the
trained model. The output SFrame contains predictions as both class
labels as well as probabilities that the predicted value is the
associated label.
Parameters
... |
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
An SFrame having the same feature columns as provided when creating
the model.
metric : str, optional
Name ... | def evaluate(self, dataset, metric='auto', **kwargs):
"""
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
An SFrame having the same feature columns as provided when creatin... |
Convert a Support Vector Regressor (SVR) model to the protobuf spec.
Parameters
----------
model: SVR
A trained SVR encoder model.
feature_names: [str]
Name of the input columns.
target: str
Name of the output column.
Returns
-------
model_spec: An object of ty... | def convert(model, features, target):
"""Convert a Support Vector Regressor (SVR) model to the protobuf spec.
Parameters
----------
model: SVR
A trained SVR encoder model.
feature_names: [str]
Name of the input columns.
target: str
Name of the output column.
Return... |
Verify that the given extension handle is valid. | def _VerifyExtensionHandle(message, extension_handle):
"""Verify that the given extension handle is valid."""
if not isinstance(extension_handle, _FieldDescriptor):
raise KeyError('HasExtension() expects an extension handle, got: %s' %
extension_handle)
if not extension_handle.is_extensio... |
Sets class-level attributes for all enum fields defined in this message.
Also exporting a class-level object that can name enum values.
Args:
descriptor: Descriptor object for this message type.
cls: Class we're constructing for this message type. | def _AddEnumValues(descriptor, cls):
"""Sets class-level attributes for all enum fields defined in this message.
Also exporting a class-level object that can name enum values.
Args:
descriptor: Descriptor object for this message type.
cls: Class we're constructing for this message type.
"""
for enum... |
Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in turn returns a default value for this field. The... | def _DefaultValueConstructorForField(field):
"""Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in... |
Re-raise the currently-handled TypeError with the field name added. | def _ReraiseTypeErrorWithFieldName(message_name, field_name):
"""Re-raise the currently-handled TypeError with the field name added."""
exc = sys.exc_info()[1]
if len(exc.args) == 1 and type(exc) is TypeError:
# simple TypeError; add field name to exception message
exc = TypeError('%s for field %s.%s' % (... |
Adds an __init__ method to cls. | def _AddInitMethod(message_descriptor, cls):
"""Adds an __init__ method to cls."""
def _GetIntegerEnumValue(enum_type, value):
"""Convert a string or integer enum value to an integer.
If the value is a string, it is converted to the enum value in
enum_type with the same name. If the value is not a st... |
Returns a field descriptor by field name.
Args:
message_descriptor: A Descriptor describing all fields in message.
field_name: The name of the field to retrieve.
Returns:
The field descriptor associated with the field name. | def _GetFieldByName(message_descriptor, field_name):
"""Returns a field descriptor by field name.
Args:
message_descriptor: A Descriptor describing all fields in message.
field_name: The name of the field to retrieve.
Returns:
The field descriptor associated with the field name.
"""
try:
retu... |
Adds properties for all fields in this protocol message type. | def _AddPropertiesForFields(descriptor, cls):
"""Adds properties for all fields in this protocol message type."""
for field in descriptor.fields:
_AddPropertiesForField(field, cls)
if descriptor.is_extendable:
# _ExtensionDict is just an adaptor with no state so we allocate a new one
# every time it ... |
Adds a public property for a protocol message field.
Clients can use this property to get and (in the case
of non-repeated scalar fields) directly set the value
of a protocol message field.
Args:
field: A FieldDescriptor for this field.
cls: The class we're constructing. | def _AddPropertiesForField(field, cls):
"""Adds a public property for a protocol message field.
Clients can use this property to get and (in the case
of non-repeated scalar fields) directly set the value
of a protocol message field.
Args:
field: A FieldDescriptor for this field.
cls: The class we're ... |
Adds a public property for a "repeated" protocol message field. Clients
can use this property to get the value of the field, which will be either a
_RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see
below).
Note that when clients add values to these containers, we perform
type-checking i... | def _AddPropertiesForRepeatedField(field, cls):
"""Adds a public property for a "repeated" protocol message field. Clients
can use this property to get the value of the field, which will be either a
_RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see
below).
Note that when clients add val... |
Adds a public property for a nonrepeated, scalar protocol message field.
Clients can use this property to get and directly set the value of the field.
Note that when the client sets the value of a field by using this property,
all necessary "has" bits are set as a side-effect, and we also perform
type-checking.... | def _AddPropertiesForNonRepeatedScalarField(field, cls):
"""Adds a public property for a nonrepeated, scalar protocol message field.
Clients can use this property to get and directly set the value of the field.
Note that when the client sets the value of a field by using this property,
all necessary "has" bits ... |
Adds properties for all fields in this protocol message type. | def _AddPropertiesForExtensions(descriptor, cls):
"""Adds properties for all fields in this protocol message type."""
extension_dict = descriptor.extensions_by_name
for extension_name, extension_field in extension_dict.items():
constant_name = extension_name.upper() + "_FIELD_NUMBER"
setattr(cls, constant... |
Given a (FieldDescriptor, value) tuple from _fields, return true if the
value should be included in the list returned by ListFields(). | def _IsPresent(item):
"""Given a (FieldDescriptor, value) tuple from _fields, return true if the
value should be included in the list returned by ListFields()."""
if item[0].label == _FieldDescriptor.LABEL_REPEATED:
return bool(item[1])
elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
return ... |
Helper for _AddMessageMethods(). | def _AddListFieldsMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def ListFields(self):
all_fields = [item for item in self._fields.items() if _IsPresent(item)]
all_fields.sort(key = lambda item: item[0].number)
return all_fields
cls.ListFields = ListFields |
Helper for _AddMessageMethods(). | def _AddHasFieldMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
is_proto3 = (message_descriptor.syntax == "proto3")
error_msg = _Proto3HasError if is_proto3 else _Proto2HasError
hassable_fields = {}
for field in message_descriptor.fields:
if field.label == _FieldDescriptor.LABEL_... |
Helper for _AddMessageMethods(). | def _AddClearFieldMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def ClearField(self, field_name):
try:
field = message_descriptor.fields_by_name[field_name]
except KeyError:
try:
field = message_descriptor.oneofs_by_name[field_name]
if field in self._one... |
Helper for _AddMessageMethods(). | def _AddClearExtensionMethod(cls):
"""Helper for _AddMessageMethods()."""
def ClearExtension(self, extension_handle):
_VerifyExtensionHandle(self, extension_handle)
# Similar to ClearField(), above.
if extension_handle in self._fields:
del self._fields[extension_handle]
self._Modified()
cls... |
Helper for _AddMessageMethods(). | def _AddHasExtensionMethod(cls):
"""Helper for _AddMessageMethods()."""
def HasExtension(self, extension_handle):
_VerifyExtensionHandle(self, extension_handle)
if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:
raise KeyError('"%s" is repeated.' % extension_handle.full_name)
if extens... |
Unpacks Any message and returns the unpacked message.
This internal method is different from public Any Unpack method which takes
the target message as argument. _InternalUnpackAny method does not have
target message type and need to find the message type in descriptor pool.
Args:
msg: An Any message to b... | def _InternalUnpackAny(msg):
"""Unpacks Any message and returns the unpacked message.
This internal method is different from public Any Unpack method which takes
the target message as argument. _InternalUnpackAny method does not have
target message type and need to find the message type in descriptor pool.
... |
Helper for _AddMessageMethods(). | def _AddEqualsMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def __eq__(self, other):
if (not isinstance(other, message_mod.Message) or
other.DESCRIPTOR != self.DESCRIPTOR):
return False
if self is other:
return True
if self.DESCRIPTOR.full_name == _AnyFull... |
Helper for _AddMessageMethods(). | def _AddStrMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def __str__(self):
return text_format.MessageToString(self)
cls.__str__ = __str__ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.