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 sample(self, fraction, seed=None, exact=False):
""" Create an SArray which contains a subsample of the current SArray. Parameters fraction : float Fraction o... |
if (fraction > 1 or fraction < 0):
raise ValueError('Invalid sampling rate: ' + str(fraction))
if (len(self) == 0):
return SArray()
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
with cython_context():
return SArra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash(self, seed=0):
""" Returns an SArray with a hash of each element. seed can be used to change the hash function to allow this method to be used for rando... |
with cython_context():
return SArray(_proxy=self.__proxy__.hash(seed)) |
<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_integers(cls, size, seed=None):
""" Returns an SArray with random integer values. """ |
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
return cls.from_sequence(size).hash(seed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def argmin(self):
""" Get the index of the minimum numeric value in SArray. Returns None on an empty SArray. Raises an exception if called on an SArray with non-... |
from .sframe import SFrame as _SFrame
if len(self) == 0:
return None
if not any([isinstance(self[0], i) for i in [int,float,long]]):
raise TypeError("SArray must be of type 'int', 'long', or 'float'.")
sf = _SFrame(self).add_row_number()
sf_out = sf.gro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mean(self):
""" Mean of all the values in the SArray, or mean image. Returns None on an empty SArray. Raises an exception if called on an SArray with non-num... |
with cython_context():
if self.dtype == _Image:
from .. import extensions
return extensions.generate_mean(self)
else:
return self.__proxy__.mean() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
""" Create a new SArray with all the values cast to str. The string format is specified by the 'format' ... |
if(self.dtype != datetime.datetime):
raise TypeError("datetime_to_str expects SArray of datetime as input SArray")
with cython_context():
return SArray(_proxy=self.__proxy__.datetime_to_str(format)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
""" Create a new SArray with all the values cast to datetime. The string format is specified by the 'for... |
if(self.dtype != str):
raise TypeError("str_to_datetime expects SArray of str as input SArray")
with cython_context():
return SArray(_proxy=self.__proxy__.str_to_datetime(format)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def astype(self, dtype, undefined_on_failure=False):
""" Create a new SArray with all values cast to the given type. Throws an exception if the types are not cas... |
if (dtype == _Image) and (self.dtype == array.array):
raise TypeError("Cannot cast from image type to array with sarray.astype(). Please use sarray.pixel_array_to_image() instead.")
with cython_context():
return SArray(_proxy=self.__proxy__.astype(dtype, undefined_on_failure)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clip(self, lower=float('nan'), upper=float('nan')):
""" Create a new SArray with each value clipped to be within the given bounds. In this case, "clipped" me... |
with cython_context():
return SArray(_proxy=self.__proxy__.clip(lower, upper)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clip_lower(self, threshold):
""" Create new SArray with all values clipped to the given lower bound. This function can operate on numeric arrays, as well as ... |
with cython_context():
return SArray(_proxy=self.__proxy__.clip(threshold, float('nan'))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tail(self, n=10):
""" Get an SArray that contains the last n elements in the SArray. Parameters n : int The number of elements to fetch Returns ------- out :... |
with cython_context():
return SArray(_proxy=self.__proxy__.tail(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 is_topk(self, topk=10, reverse=False):
""" Create an SArray indicating which elements are in the top k. Entries are '1' if the corresponding element in the c... |
with cython_context():
return SArray(_proxy = self.__proxy__.topk_index(topk, reverse)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summary(self, background=False, sub_sketch_keys=None):
""" Summary statistics that can be calculated with one pass over the SArray. Returns a turicreate.Sket... |
from ..data_structures.sketch import Sketch
if (self.dtype == _Image):
raise TypeError("summary() is not supported for arrays of image type")
if (type(background) != bool):
raise TypeError("'background' parameter has to be a boolean value")
if (sub_sketch_keys is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value_counts(self):
""" Return an SFrame containing counts of unique values. The resulting SFrame will be sorted in descending frequency. Returns ------- out... |
from .sframe import SFrame as _SFrame
return _SFrame({'value':self}).groupby('value', {'count':_aggregate.COUNT}).sort('count', ascending=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 append(self, other):
""" Append an SArray to the current SArray. Creates a new SArray with the rows from both SArrays. Both SArrays must be of the same type.... |
if type(other) is not SArray:
raise RuntimeError("SArray append can only work with SArray")
if self.dtype != other.dtype:
raise RuntimeError("Data types in both SArrays have to be the same")
with cython_context():
return SArray(_proxy = self.__proxy__.appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unique(self):
""" Get all unique values in the current SArray. Raises a TypeError if the SArray is of dictionary type. Will not necessarily preserve the orde... |
from .sframe import SFrame as _SFrame
tmp_sf = _SFrame()
tmp_sf.add_column(self, 'X1', inplace=True)
res = tmp_sf.groupby('X1',{})
return SArray(_proxy=res['X1'].__proxy__) |
<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, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
""" Visualize the SArray. Notes ----- - The plot will render either inline in a ... |
returned_plot = self.plot(title, xlabel, ylabel)
returned_plot.show() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
""" Create a Plot object representing the SArray. Notes ----- - The plot will re... |
if title == "":
title = " "
if xlabel == "":
xlabel = " "
if ylabel == "":
ylabel = " "
if title is None:
title = "" # C++ otherwise gets "None" as std::string
if xlabel is None:
xlabel = ""
if ylabel 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 item_length(self):
""" Length of each element in the current SArray. Only works on SArrays of dict, array, or list type. If a given element is a missing valu... |
if (self.dtype not in [list, dict, array.array]):
raise TypeError("item_length() is only applicable for SArray of type list, dict and array.")
with cython_context():
return SArray(_proxy = self.__proxy__.item_length()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stack(self, new_column_name=None, drop_na=False, new_column_type=None):
""" Convert a "wide" SArray to one or two "tall" columns in an SFrame by stacking all... |
from .sframe import SFrame as _SFrame
return _SFrame({'SArray': self}).stack('SArray',
new_column_name=new_column_name,
drop_na=drop_na,
new_column_type=new_colum... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort(self, ascending=True):
""" Sort all values in this SArray. Sort only works for sarray of type str, int and float, otherwise TypeError will be raised. Cr... |
from .sframe import SFrame as _SFrame
if self.dtype not in (int, float, str, datetime.datetime):
raise TypeError("Only sarray with type (int, float, str, datetime.datetime) can be sorted")
sf = _SFrame()
sf['a'] = self
return sf.sort('a', ascending)['a'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rolling_sum(self, window_start, window_end, min_observations=None):
""" Calculate a new SArray of the sum of different subsets over this SArray. Also known a... |
min_observations = self.__check_min_observations(min_observations)
agg_op = None
if self.dtype is array.array:
agg_op = '__builtin__vector__sum__'
else:
agg_op = '__builtin__sum__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_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 rolling_max(self, window_start, window_end, min_observations=None):
""" Calculate a new SArray of the maximum value of different subsets over this SArray. Th... |
min_observations = self.__check_min_observations(min_observations)
agg_op = '__builtin__max__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rolling_count(self, window_start, window_end):
""" Count the number of non-NULL values of different subsets over this SArray. The subset that the count is ex... |
agg_op = '__builtin__nonnull__count__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, 0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cumulative_sum(self):
""" Return the cumulative sum of the elements in the SArray. Returns an SArray where each element in the output corresponds to the sum ... |
from .. import extensions
agg_op = "__builtin__cum_sum__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cumulative_mean(self):
""" Return the cumulative mean of the elements in the SArray. Returns an SArray where each element in the output corresponds to the me... |
from .. import extensions
agg_op = "__builtin__cum_avg__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cumulative_min(self):
""" Return the cumulative minimum value of the elements in the SArray. Returns an SArray where each element in the output corresponds t... |
from .. import extensions
agg_op = "__builtin__cum_min__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cumulative_max(self):
""" Return the cumulative maximum value of the elements in the SArray. Returns an SArray where each element in the output corresponds t... |
from .. import extensions
agg_op = "__builtin__cum_max__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cumulative_std(self):
""" Return the cumulative standard deviation of the elements in the SArray. Returns an SArray where each element in the output correspo... |
from .. import extensions
agg_op = "__builtin__cum_std__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cumulative_var(self):
""" Return the cumulative variance of the elements in the SArray. Returns an SArray where each element in the output corresponds to the... |
from .. import extensions
agg_op = "__builtin__cum_var__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) |
<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_doxygen_xml(app):
"""Run the doxygen make commands if we're on the ReadTheDocs server""" |
read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
if read_the_docs_build:
run_doxygen('..')
sys.stderr.write('Check if shared lib exists\n')
run_build_lib('..')
sys.stderr.write('The wrapper path: %s\n' % str(os.listdir('../wrapper')))
rabit._loadlib() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False):
"""Converts protobuf message to JSON format. Args: message: ... |
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
return printer.ToJsonString(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MessageToDict(message, including_default_value_fields=False, preserving_proto_field_name=False):
"""Converts protobuf message to a JSON dictionary. Args: mes... |
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
# pylint: disable=protected-access
return printer._MessageToJsonObject(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ParseDict(js_dict, message, ignore_unknown_fields=False):
"""Parses a JSON dictionary representation into a message. Args: js_dict: Dict representation of a ... |
parser = _Parser(ignore_unknown_fields)
parser.ConvertMessage(js_dict, message)
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ConvertScalarFieldValue(value, field, require_str=False):
"""Convert a single scalar field value. Args: value: A scalar value to convert the scalar field va... |
if field.cpp_type in _INT_TYPES:
return _ConvertInteger(value)
elif field.cpp_type in _FLOAT_TYPES:
return _ConvertFloat(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return _ConvertBool(value, require_str)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ConvertInteger(value):
"""Convert an integer. Args: value: A scalar value to convert. Returns: The integer value. Raises: ParseError: If an integer couldn't... |
if isinstance(value, float) and not value.is_integer():
raise ParseError('Couldn\'t parse integer: {0}.'.format(value))
if isinstance(value, six.text_type) and value.find(' ') != -1:
raise ParseError('Couldn\'t parse integer: "{0}".'.format(value))
return int(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 _ConvertFloat(value):
"""Convert an floating point number.""" |
if value == 'nan':
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
try:
# Assume Python compatible syntax.
return float(value)
except ValueError:
# Check alternative spellings.
if value == _NEG_INFINITY:
return float('-inf')
elif value == _INFINITY:
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ConvertBool(value, require_str):
"""Convert a boolean value. Args: value: A scalar value to convert. require_str: If True, value must be a str. Returns: The... |
if require_str:
if value == 'true':
return True
elif value == 'false':
return False
else:
raise ParseError('Expected "true" or "false", not {0}.'.format(value))
if not isinstance(value, bool):
raise ParseError('Expected true or false without quotes.')
return 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 _MessageToJsonObject(self, message):
"""Converts message to an object according to Proto3 JSON Specification.""" |
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
return self._WrapperMessageToJsonObject(message)
if full_name in _WKTJSONMETHODS:
return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self)
js = {}
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _RegularMessageToJsonObject(self, message, js):
"""Converts normal message according to Proto3 JSON Specification.""" |
fields = message.ListFields()
try:
for field, value in fields:
if self.preserving_proto_field_name:
name = field.name
else:
name = field.json_name
if _IsMapEntry(field):
# Convert a map field.
v_field = field.message_type.fields_by_name['va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _FieldToJsonObject(self, field, value):
"""Converts field value according to Proto3 JSON Specification.""" |
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = field.enum_type.values_by_number.get(value, None)
if enum_value is not None:
return enum_value.name
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _AnyMessageToJsonObject(self, message):
"""Converts Any message according to Proto3 JSON Specification.""" |
if not message.ListFields():
return {}
# Must print @type first, use OrderedDict instead of {}
js = OrderedDict()
type_url = message.type_url
js['@type'] = type_url
sub_message = _CreateMessageFromTypeUrl(type_url)
sub_message.ParseFromString(message.value)
message_descriptor = su... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ValueMessageToJsonObject(self, message):
"""Converts Value message according to Proto3 JSON Specification.""" |
which = message.WhichOneof('kind')
# If the Value message is not set treat as null_value when serialize
# to JSON. The parse back result will be different from original message.
if which is None or which == 'null_value':
return None
if which == 'list_value':
return self._ListValueMessag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _StructMessageToJsonObject(self, message):
"""Converts Struct message according to Proto3 JSON Specification.""" |
fields = message.fields
ret = {}
for key in fields:
ret[key] = self._ValueMessageToJsonObject(fields[key])
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ConvertMessage(self, value, message):
"""Convert a JSON object into a message. Args: value: A JSON object. message: A WKT or regular protocol message to reco... |
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value, message)
elif full_name in _WKTJSONMETHODS:
methodcaller(_WKTJSONMETHODS[full_name][1], value, message)(self)
else:
self._C... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ConvertAnyMessage(self, value, message):
"""Convert a JSON representation into Any message.""" |
if isinstance(value, dict) and not value:
return
try:
type_url = value['@type']
except KeyError:
raise ParseError('@type is missing when parsing any message.')
sub_message = _CreateMessageFromTypeUrl(type_url)
message_descriptor = sub_message.DESCRIPTOR
full_name = message_de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ConvertWrapperMessage(self, value, message):
"""Convert a JSON representation into Wrapper message.""" |
field = message.DESCRIPTOR.fields_by_name['value']
setattr(message, 'value', _ConvertScalarFieldValue(value, field)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ConvertMapFieldValue(self, value, message, field):
"""Convert map field value for a message map field. Args: value: A JSON object to convert the map field v... |
if not isinstance(value, dict):
raise ParseError(
'Map field {0} must be in a dict which is {1}.'.format(
field.name, value))
key_field = field.message_type.fields_by_name['key']
value_field = field.message_type.fields_by_name['value']
for key in value:
key_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 categorical_heatmap(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
""" Plots the data in `x` on the X axis and the data in `y` on th... |
if (not isinstance(x, tc.data_structures.sarray.SArray) or
not isinstance(y, tc.data_structures.sarray.SArray) or
x.dtype != str or y.dtype != str):
raise ValueError("turicreate.visualization.categorical_heatmap supports " +
"SArrays of dtype: str")
# legit input
title... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def columnwise_summary(sf):
""" Plots a columnwise summary of the sframe provided as input, and returns the resulting Plot object. The function supports SFrames.... |
if not isinstance(sf, tc.data_structures.sframe.SFrame):
raise ValueError("turicreate.visualization.columnwise_summary " +
"supports SFrame")
plt_ref = tc.extensions.plot_columnwise_summary(sf)
return Plot(plt_ref) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histogram(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
""" Plots a histogram of the sarray provided as input, and returns the result... |
if (not isinstance(sa, tc.data_structures.sarray.SArray) or
sa.dtype not in [int, float]):
raise ValueError("turicreate.visualization.histogram supports " +
"SArrays of dtypes: int, float")
title = _get_title(title)
plt_ref = tc.extensions.plot_histogram(sa,
xlabel, yla... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def item_frequency(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
""" Plots an item frequency of the sarray provided as input, and returns... |
if (not isinstance(sa, tc.data_structures.sarray.SArray) or
sa.dtype != str):
raise ValueError("turicreate.visualization.item_frequency supports " +
"SArrays of dtype str")
title = _get_title(title)
plt_ref = tc.extensions.plot_item_frequency(sa,
xlabel, ylabel, title)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Parse(factory, file):
""" Parses the input file and returns C code and corresponding header file. """ |
entities = []
while 1:
# Just gets the whole struct nicely formatted
data = GetNextStruct(file)
if not data:
break
entities.extend(ProcessStruct(factory, data))
return entities |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def EntryTagName(self, entry):
"""Creates the name inside an enumeration for distinguishing data types.""" |
name = "%s_%s" % (self._name, entry.Name())
return name.upper() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PrintIndented(self, file, ident, code):
"""Takes an array, add indentation to each entry and prints it.""" |
for entry in code:
print >>file, '%s%s' % (ident, entry) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PrintTags(self, file):
"""Prints the tag definitions for a structure.""" |
print >>file, '/* Tag definition for %s */' % self._name
print >>file, 'enum %s_ {' % self._name.lower()
for entry in self._entries:
print >>file, ' %s=%d,' % (self.EntryTagName(entry),
entry.Tag())
print >>file, ' %s_MAX_TAGS' % (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 create(graph, kmin=0, kmax=10, verbose=True):
""" Compute the K-core decomposition of the graph. Return a model object with total number of cores as well as ... |
from turicreate._cython.cy_server import QuietProgress
if not isinstance(graph, _SGraph):
raise TypeError('graph input must be a SGraph object.')
opts = {'graph': graph.__proxy__, 'kmin': kmin, 'kmax': kmax}
with QuietProgress(verbose):
params = _tc.extensions._toolkits.graph.kcore.c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raise_error_unsupported_categorical_option(option_name, option_value, layer_type, layer_name):
""" Raise an error if an option is not supported. """ |
raise RuntimeError("Unsupported option %s=%s in layer %s(%s)" % (option_name, option_value,
layer_type, layer_name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_or_validate_classifier_output_features( output_features, class_labels, supports_class_scores = True):
""" Given a list of class labels and a list of ... |
def raise_error(msg):
raise ValueError("Classifier error: %s" % msg)
class_labels = list(class_labels)
# First, we need to determine the type of the classes.
_int_types = _integer_types + (bool, _np.bool_, _np.int32, _np.int64)
if all(isinstance(cl, _int_types) for cl in class_labels):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""The main function of the utility""" |
parser = argparse.ArgumentParser(
description='Manage the build environment of Boost.Metaparse'
)
parser.add_argument(
'--dep_json',
required=True,
help='The json file describing the dependencies'
)
parser.add_argument(
'--git',
required=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 read_history(self, num=10, segment=0):
""" Outputs the last `num` elements that were appended either by `append` or `append_multiple`. Returns ------- out : ... |
if num < 0:
num = 0
if segment < 0:
raise TypeError("segment must be >= 0")
return self._builder.read_history(num, segment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_satisfied_condition(conditions, ps):
"""Returns the first element of 'property-sets' which is a subset of 'properties', or an empty list if no such elem... |
assert is_iterable_typed(conditions, property_set.PropertySet)
assert isinstance(ps, property_set.PropertySet)
for condition in conditions:
found_all = True
for i in condition.all():
if i.value:
found = i.value in ps.get(i.feature)
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 __add_flag (rule_or_module, variable_name, condition, values):
""" Adds a new flag setting with the specified values. Does no checking. """ |
assert isinstance(rule_or_module, basestring)
assert isinstance(variable_name, basestring)
assert is_iterable_typed(condition, property_set.PropertySet)
assert is_iterable(values) and all(
isinstance(v, (basestring, type(None))) for v in values)
f = Flag(variable_name, values, condition, ru... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def root (path, root):
""" If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged. """ |
if os.path.isabs (path):
return path
else:
return os.path.join (root, 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 glob_tree(roots, patterns, exclude_patterns=None):
"""Recursive version of GLOB. Builds the glob of files while also searching in the subdirectories of the g... |
if not exclude_patterns:
exclude_patterns = []
result = glob(roots, patterns, exclude_patterns)
subdirs = [s for s in glob(roots, ["*"], exclude_patterns) if s != "." and s != ".." and os.path.isdir(s)]
if subdirs:
result.extend(glob_tree(subdirs, patterns, exclude_patterns))
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def glob_in_parents(dir, patterns, upper_limit=None):
"""Recursive version of GLOB which glob sall parent directories of dir until the first match is found. Retu... |
assert(isinstance(dir, str))
assert(isinstance(patterns, list))
result = []
absolute_dir = os.path.join(os.getcwd(), dir)
absolute_dir = os.path.normpath(absolute_dir)
while absolute_dir:
new_dir = os.path.split(absolute_dir)[0]
if new_dir == absolute_dir:
break
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrap_function_return(val):
""" Recursively walks each thing in val, opening lists and dictionaries, converting all occurrences of UnityGraphProxy to an SGra... |
if type(val) is _UnityGraphProxy:
return _SGraph(_proxy = val)
elif type(val) is _UnitySFrameProxy:
return _SFrame(_proxy = val)
elif type(val) is _UnitySArrayProxy:
return _SArray(_proxy = val)
elif type(val) is _UnityModel:
# we need to cast it up to the appropriate 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 _run_toolkit_function(fnname, arguments, args, kwargs):
""" Dispatches arguments to a toolkit function. Parameters fnname : string The toolkit function to ru... |
# scan for all the arguments in args
num_args_got = len(args) + len(kwargs)
num_args_required = len(arguments)
if num_args_got != num_args_required:
raise TypeError("Expecting " + str(num_args_required) + " arguments, got " + str(num_args_got))
## fill the dict first with the regular args
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _publish():
import copy """ Publishes all functions and classes registered in unity_server. The functions and classes will appear in the module turicreate.ex... |
unity = _get_unity()
fnlist = unity.list_toolkit_functions()
# Loop through all the functions and inject it into
# turicreate.extensions.[blah]
# Note that [blah] may be somemodule.somefunction
# and so the injection has to be
# turicreate.extensions.somemodule.somefunction
for fn in fn... |
<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_argument_list_from_toolkit_function_name(fn):
""" Given a toolkit function name, return the argument list """ |
unity = _get_unity()
fnprops = unity.describe_toolkit_function(fn)
argnames = fnprops['arguments']
return argnames |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" Print lines of input along with output. """ |
source_lines = (line.rstrip() for line in sys.stdin)
console = InteractiveInterpreter()
console.runsource('import turicreate')
source = ''
try:
while True:
source = source_lines.next()
more = console.runsource(source)
while more:
next_line... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetTypeChecker(field):
"""Returns a type checker for a message field of the specified types. Args: field: FieldDescriptor object for this field. Returns: An ... |
if (field.cpp_type == _FieldDescriptor.CPPTYPE_STRING and
field.type == _FieldDescriptor.TYPE_STRING):
return UnicodeValueChecker()
if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
if SupportsOpenEnums(field):
# When open enums are supported, any int32 can be assigned.
return _VALUE_CH... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CheckValue(self, proposed_value):
"""Type check the provided value and return it. The returned value might have been normalized to another type. """ |
if not isinstance(proposed_value, self._acceptable_types):
message = ('%.1024r has type %s, but expected one of: %s' %
(proposed_value, type(proposed_value), self._acceptable_types))
raise TypeError(message)
return proposed_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 CEscape(text, as_utf8):
"""Escape a bytes string for use in an ascii protocol buffer. text.encode('string_escape') does not seem to satisfy our needs as it e... |
# PY3 hack: make Ord work for str and bytes:
# //platforms/networking/data uses unicode here, hence basestring.
Ord = ord if isinstance(text, six.string_types) else lambda x: x
if as_utf8:
return ''.join(_cescape_utf8_to_str[Ord(c)] for c in text)
return ''.join(_cescape_byte_to_str[Ord(c)] for c in text... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CUnescape(text):
"""Unescape a text string with C-style escape sequences to UTF-8 bytes.""" |
def ReplaceHex(m):
# Only replace the match if the number of leading back slashes is odd. i.e.
# the slash itself is not escaped.
if len(m.group(1)) & 1:
return m.group(1) + 'x0' + m.group(2)
return m.group(0)
# This is required because the 'string_escape' encoding doesn't
# allow single-... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_suffixes (suffixes, type):
""" Specifies that targets with suffix from 'suffixes' have the type 'type'. If a different type is already specified for... |
assert is_iterable_typed(suffixes, basestring)
assert isinstance(type, basestring)
for s in suffixes:
if s in __suffixes_to_types:
old_type = __suffixes_to_types [s]
if old_type != type:
raise BaseException ('Attempting to specify type for suffix "%s"\nOld ty... |
<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_scanner (type, scanner):
""" Sets a scanner class that will be used for this 'type'. """ |
if __debug__:
from .scanner import Scanner
assert isinstance(type, basestring)
assert issubclass(scanner, Scanner)
validate (type)
__types [type]['scanner'] = scanner |
<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_scanner (type, prop_set):
""" Returns a scanner instance appropriate to 'type' and 'property_set'. """ |
if __debug__:
from .property_set import PropertySet
assert isinstance(type, basestring)
assert isinstance(prop_set, PropertySet)
if registered (type):
scanner_type = __types [type]['scanner']
if scanner_type:
return scanner.get (scanner_type, prop_set.raw ())... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_bases (type):
""" Returns type and all of its bases, in the order of their distance from type. """ |
assert isinstance(type, basestring)
result = []
while type:
result.append (type)
type = __types [type]['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 all_derived (type):
""" Returns type and all classes that derive from it, in the order of their distance from type. """ |
assert isinstance(type, basestring)
result = [type]
for d in __types [type]['derived']:
result.extend (all_derived (d))
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 is_derived (type, base):
""" Returns true if 'type' is 'base' or has 'base' as its direct or indirect base. """ |
assert isinstance(type, basestring)
assert isinstance(base, basestring)
# TODO: this isn't very efficient, especially for bases close to type
if base in all_bases (type):
return True
else:
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_subtype (type, base):
""" Same as is_derived. Should be removed. """ |
assert isinstance(type, basestring)
assert isinstance(base, basestring)
# TODO: remove this method
return is_derived (type, base) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 no... |
if __debug__:
from .property_set import PropertySet
assert isinstance(is_suffix, (int, bool))
assert isinstance(type, basestring)
assert isinstance(prop_set, PropertySet)
key = (is_suffix, type, prop_set)
v = __target_suffixes_cache.get(key, None)
if not v:
v = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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",... |
assert isinstance(filename, basestring)
while 1:
filename, suffix = os.path.splitext (filename)
if not suffix: return None
suffix = suffix[1:]
if suffix in __suffixes_to_types:
return __suffixes_to_types[suffix] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. Th... |
assert isinstance(type, basestring)
assert is_iterable_typed(suffixes, basestring)
assert isinstance(base_type, basestring) or base_type is None
assert is_iterable_typed(os, basestring)
if registered (type):
return
if not os or os_name () in os:
register (type, suffixes, base_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 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]))
if repr_format:
lst_separator = "["
lst_end_separator = "]"
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_flatten(builder, layer, input_names, output_names, keras_layer):
"""Convert a flatten layer from keras to coreml. Parameters keras_layer: layer A ker... |
input_name, output_name = (input_names[0], output_names[0])
# blob_order == 0 if the input blob needs not be rearranged
# blob_order == 1 if the input blob needs to be rearranged
blob_order = 0
# using keras_layer.input.shape have a "?" (Dimension[None] at the front),
# making a 3D tensor wit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
dtypes = data.dtypes
if not all(dtype.name in ('int64', 'float64', 'bool') for dtype in dtypes):
... |
<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_float_info(self, field):
"""Get float property from the DMatrix. Parameters field: str The field name of the information Returns ------- info : array a n... |
length = ctypes.c_ulong()
ret = ctypes.POINTER(ctypes.c_float)()
_check_call(_LIB.XGDMatrixGetFloatInfo(self.handle,
c_str(field),
ctypes.byref(length),
c... |
<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_uint_info(self, field):
"""Get unsigned integer property from the DMatrix. Parameters field: str The field name of the information Returns ------- info :... |
length = ctypes.c_ulong()
ret = ctypes.POINTER(ctypes.c_uint)()
_check_call(_LIB.XGDMatrixGetUIntInfo(self.handle,
c_str(field),
ctypes.byref(length),
ctypes... |
<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_binary(self, fname, silent=True):
"""Save DMatrix to an XGBoost buffer. Parameters fname : string Name of the output buffer file. silent : bool (optiona... |
_check_call(_LIB.XGDMatrixSaveBinary(self.handle,
c_str(fname),
int(silent))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. Retu... |
res = DMatrix(None, feature_names=self.feature_names)
res.handle = ctypes.c_void_p()
_check_call(_LIB.XGDMatrixSliceDMatrix(self.handle,
c_array(ctypes.c_int, rindex),
len(rindex),
... |
<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(self, dtrain, iteration, fobj=None):
""" Update for one iteration, with objective function calculated internally. Parameters dtrain : DMatrix Training... |
if not isinstance(dtrain, DMatrix):
raise TypeError('invalid training matrix: {}'.format(type(dtrain).__name__))
self._validate_features(dtrain)
if fobj is None:
_check_call(_LIB.XGBoosterUpdateOneIter(self.handle, iteration, dtrain.handle))
else:
pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def boost(self, dtrain, grad, hess):
""" Boost the booster for one iteration, with customized gradient statistics. Parameters dtrain : DMatrix The training DMatr... |
if len(grad) != len(hess):
raise ValueError('grad / hess length mismatch: {} / {}'.format(len(grad), len(hess)))
if not isinstance(dtrain, DMatrix):
raise TypeError('invalid training matrix: {}'.format(type(dtrain).__name__))
self._validate_features(dtrain)
_che... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)... |
if feval is None:
for d in evals:
if not isinstance(d[0], DMatrix):
raise TypeError('expected DMatrix, got {}'.format(type(d[0]).__name__))
if not isinstance(d[1], STRING_TYPES):
raise TypeError('expected string, got {}'.format... |
<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_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(self.handle,
ctypes.byref(length),
ctypes.byref(cptr)))
return ctypes2buffer(cptr, length.va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
if isinstance(fout, STRING_TYPES):
fout = open(fout, 'w')
need_close = True
else:
need_close = False
ret = self.get_dump(fmap, with_stats)
for i in range(len(ret)):
fout.write('booster[{}]:\n'.format(i))
fout.write(ret[i])
... |
<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_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))
fname = from_pystr_to_cstr(self.feature_names)
if self.feature_types is None:
# use qua... |
<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_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('\n'):
arr = line.split('[')
if len(arr) == 1:
continue
fid = arr[1].split(']')[0]
fid = fid.split('<')[0]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.