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 copy_submission_locally(self, cloud_path): """Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Goo...
local_path = os.path.join(self.download_dir, os.path.basename(cloud_path)) cmd = ['gsutil', 'cp', cloud_path, local_path] if subprocess.call(cmd) != 0: logging.error('Can\'t copy submission locally') return None return local_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 copy_submission_to_destination(self, src_filename, dst_subdir, submission_id): """Copies submission to target directory. Args: src_filename: source filename ...
extension = [e for e in ALLOWED_EXTENSIONS if src_filename.endswith(e)] if len(extension) != 1: logging.error('Invalid submission extension: %s', src_filename) return dst_filename = os.path.join(self.target_dir, dst_subdir, submission_id + extension[0]) cmd ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_and_copy_one_submission(self, submission_path): """Validates one submission and copies it to target directory. Args: submission_path: path in Google...
if os.path.exists(self.download_dir): shutil.rmtree(self.download_dir) os.makedirs(self.download_dir) if os.path.exists(self.validate_dir): shutil.rmtree(self.validate_dir) os.makedirs(self.validate_dir) logging.info('\n' + ('#' * 80) + '\n# Processing submission: %s\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 save_id_to_path_mapping(self): """Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory. """
if not self.id_to_path_mapping: return with open(self.local_id_to_path_mapping_file, 'w') as f: writer = csv.writer(f) writer.writerow(['id', 'path']) for k, v in sorted(iteritems(self.id_to_path_mapping)): writer.writerow([k, v]) cmd = ['gsutil', 'cp', self.local_id_to_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 run(self): """Runs validation of all submissions."""
cmd = ['gsutil', 'ls', os.path.join(self.source_dir, '**')] try: files_list = subprocess.check_output(cmd).split('\n') except subprocess.CalledProcessError: logging.error('Can''t read source directory') all_submissions = [ s for s in files_list if s.endswith('.zip') or s.end...
<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(argv=None): """Takes the path to a directory with reports and renders success fail plots."""
report_paths = argv[1:] fail_names = FLAGS.fail_names.split(',') for report_path in report_paths: plot_report_from_path(report_path, label=report_path, fail_names=fail_names) pyplot.legend() pyplot.xlim(-.01, 1.) pyplot.ylim(0., 1.) pyplot.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 is_unclaimed(work): """Returns True if work piece is unclaimed."""
if work['is_completed']: return False cutoff_time = time.time() - MAX_PROCESSING_TIME if (work['claimed_worker_id'] and work['claimed_worker_start_time'] is not None and work['claimed_worker_start_time'] >= cutoff_time): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_all_to_datastore(self): """Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work piece...
client = self._datastore_client with client.no_transact_batch() as batch: parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) batch.put(client.entity(parent_key)) for work_id, work_val in iteritems(self._work): entity = client.entity(client.key(KIND_WORK, work_id, ...
<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_all_from_datastore(self): """Reads all work pieces from the datastore."""
self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key): work_id = entity.key.flat_path[-1] self.work[work_id] = dict(entity)
<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_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id."""
self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) filters = [('is_completed', '=', False)] if shard_id is not None: filters.append(('shard_id', '=', shard_id)) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent...
<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_undone_from_datastore(self, shard_id=None, num_shards=None): """Reads undone work from the datastore. If shard_id and num_shards are specified then this...
if shard_id is not None: shards_list = [(i + shard_id) % num_shards for i in range(num_shards)] else: shards_list = [] shards_list.append(None) for shard in shards_list: self._read_undone_shard_from_datastore(shard) if self._work: return shard return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_pick_piece_of_work(self, worker_id, submission_id=None): """Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Clou...
client = self._datastore_client unclaimed_work_ids = None if submission_id: unclaimed_work_ids = [ k for k, v in iteritems(self.work) if is_unclaimed(v) and (v['submission_id'] == submission_id) ] if not unclaimed_work_ids: unclaimed_work_ids = [k for k, v in iteri...
<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_work_as_completed(self, worker_id, work_id, other_values=None, error=None): """Updates work piece in datastore as completed. Args: worker_id: ID of th...
client = self._datastore_client try: with client.transaction() as transaction: work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id, KIND_WORK, work_id) work_entity = client.get(work_key, transaction=transaction) if work_entity['claimed_wor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_work_statistics(self): """Computes statistics from all work pieces stored in this class."""
result = {} for v in itervalues(self.work): submission_id = v['submission_id'] if submission_id not in result: result[submission_id] = { 'completed': 0, 'num_errors': 0, 'error_messages': set(), 'eval_times': [], 'min_eval_time': 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 init_from_adversarial_batches(self, adv_batches): """Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, coul...
for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)): work_id = ATTACK_WORK_ID_PATTERN.format(idx) self.work[work_id] = { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_from_class_batches(self, class_batches, num_shards=None): """Initializes work pieces from classification batches. Args: class_batches: dict with classif...
shards_for_submissions = {} shard_idx = 0 for idx, (batch_id, batch_val) in enumerate(iteritems(class_batches)): work_id = DEFENSE_WORK_ID_PATTERN.format(idx) submission_id = batch_val['submission_id'] shard_id = None if num_shards: shard_id = shards_for_submissions.get(subm...
<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(self, x, **kwargs): """ Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `...
# Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.get_or_guess_labels(x, kwargs) return fgm( x, self.model.get_logits(x), y=labels, eps=self.eps, ord=self.ord, clip_min=self.clip_min, clip_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): """Function to read the weights from checkpoint based on json description. Args: chec...
# Load checkpoint reader = tf.train.load_checkpoint(checkpoint) variable_map = reader.get_variable_to_shape_map() checkpoint_variable_names = variable_map.keys() # Parse JSON file for names with tf.gfile.Open(model_json) as f: list_model_var = json.load(f) net_layer_types = [] net_weights = [] 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 forward_pass(self, vector, layer_index, is_transpose=False, is_abs=False): """Performs forward pass through the layer weights at layer_index. Args: vector: v...
if(layer_index < 0 or layer_index > self.num_hidden_layers): raise ValueError('Invalid layer index') layer_type = self.layer_types[layer_index] weight = self.weights[layer_index] if is_abs: weight = tf.abs(weight) if is_transpose: vector = tf.reshape(vector, self.output_shapes[la...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dev_version(): """ Returns a hexdigest of all the python files in the module. """
md5_hash = hashlib.md5() py_files = sorted(list_files(suffix=".py")) if not py_files: return '' for filename in py_files: with open(filename, 'rb') as fobj: content = fobj.read() md5_hash.update(content) return md5_hash.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_dual(neural_net_params_object, init_dual_file=None, random_init_variance=0.01, init_nu=200.0): """Function to initialize the dual variables of the...
lambda_pos = [] lambda_neg = [] lambda_quad = [] lambda_lu = [] if init_dual_file is None: for i in range(0, neural_net_params_object.num_hidden_layers + 1): initializer = (np.random.uniform(0, random_init_variance, size=( neural_net_params_object.sizes[i], 1))).astype(np.float32) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn): """Computes eigenvector which corresponds to minimum eigenvalue. Args: x: initial value of...
x = tf.nn.l2_normalize(x) for _ in range(num_steps): x = eig_one_step(x, learning_rate, vector_prod_fn) return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tf_lanczos_smallest_eigval(vector_prod_fn, matrix_dim, initial_vector, num_iter=1000, max_iter=1000, collapse_tol=1e-9, dtype=tf.float32): """Computes smalle...
# alpha will store diagonal elements alpha = tf.TensorArray(dtype, size=1, dynamic_size=True, element_shape=()) # beta will store off diagonal elements beta = tf.TensorArray(dtype, size=0, dynamic_size=True, element_shape=()) # q will store Krylov space basis q_vectors = tf.TensorArray( dtype, size=...
<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(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over ...
assert self.sess is not None, \ 'Cannot use `generate` when no `sess` was provided' self.parse_params(**kwargs) labels, nb_classes = self.get_or_guess_labels(x, kwargs) attack = CWL2(self.sess, self.model, self.batch_size, self.confidence, 'y_target' in kwargs, self.learning...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attack(self, imgs, targets): """ Perform the L_2 attack on the given instance for the given targets. If self.targeted is true, then the targets represents th...
r = [] for i in range(0, len(imgs), self.batch_size): _logger.debug( ("Running CWL2 attack on instance %s of %s", i, len(imgs))) r.extend( self.attack_batch(imgs[i:i + self.batch_size], targets[i:i + self.batch_size])) return np.array(r)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maybe_load_model(savedir, container): """Load model if present at the specified path."""
if savedir is None: return state_path = os.path.join(os.path.join(savedir, 'training_state.pkl.zip')) if container is not None: logger.log("Attempting to download model from Azure") found_model = container.get(savedir, 'training_state.pkl.zip') else: found_model = os.path.exists(state_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 check_installation(cur_file): """Warn user if running cleverhans from a different directory than tutorial."""
cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0] ch_dir = os.path.split(cleverhans.__path__[0])[0] if cur_dir != ch_dir: warnings.warn("It appears that you have at least two versions of " "cleverhans installed, one at %s and one at" " %s. You are runn...
<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_image(row, output_dir): """Downloads the image that corresponds to the given row. Prints a notification if the download fails."""
if not download_image(image_id=row[0], url=row[1], x1=float(row[2]), y1=float(row[3]), x2=float(row[4]), y2=float(row[5]), output_dir=output_dir): print("Download failed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_image(image_id, url, x1, y1, x2, y2, output_dir): """Downloads one image, crops it, resizes it and saves it locally."""
output_filename = os.path.join(output_dir, image_id + '.png') if os.path.exists(output_filename): # Don't download image if it's already there return True try: # Download image url_file = urlopen(url) if url_file.getcode() != 200: return False image_buffer = url_file.read() # Cr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def py_func_grad(func, inp, Tout, stateful=True, name=None, grad=None): """Custom py_func with gradient support """
# Need to generate a unique name to avoid duplicates: rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8)) tf.RegisterGradient(rnd_name)(grad) g = tf.get_default_graph() with g.gradient_override_map({"PyFunc": rnd_name, "PyFuncStateless": rnd_name}): return tf.py_fun...
<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_logits_over_interval(sess, model, x_data, fgsm_params, min_epsilon=-10., max_epsilon=10., num_points=21): """Get logits when the input is perturbed in an...
# Get the height, width and number of channels height = x_data.shape[0] width = x_data.shape[1] channels = x_data.shape[2] x_data = np.expand_dims(x_data, axis=0) import tensorflow as tf from cleverhans.attacks import FastGradientMethod # Define the data placeholder x = tf.placeholder(dtype=tf.floa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linear_extrapolation_plot(log_prob_adv_array, y, file_name, min_epsilon=-10, max_epsilon=10, num_points=21): """Generate linear extrapolation plot. Args: log...
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt figure = plt.figure() figure.canvas.set_window_title('Cleverhans: Linear Extrapolation Plot') correct_idx = np.argmax(y, axis=0) fig = plt.figure() plt.xlabel('Epsilon') plt.ylabel('Logits') x_axis = np.linspace(min_epsilon, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_cmd(self, cmd: str): """Encode IQFeed API messages."""
self._sock.sendall(cmd.encode(encoding='latin-1', errors='strict'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iq_query(self, message: str): """Send data query to IQFeed API."""
end_msg = '!ENDMSG!' recv_buffer = 4096 # Send the historical data request message and buffer the data self._send_cmd(message) chunk = "" data = "" while True: chunk = self._sock.recv(recv_buffer).decode('latin-1') data += chunk ...
<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_historical_minute_data(self, ticker: str): """Request historical 5 minute data from DTN."""
start = self._start stop = self._stop if len(stop) > 4: stop = stop[:4] if len(start) > 4: start = start[:4] for year in range(int(start), int(stop) + 1): beg_time = ('%s0101000000' % year) end_time = ('%s1231235959' % year) ...
<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_data_to_df(self, data: np.array): """Build Pandas Dataframe in memory"""
col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi'] data = np.array(data).reshape(-1, len(col_names) + 1) df = pd.DataFrame(data=data[:, 1:], index=data[:, 0], columns=col_names) df.index = pd.to_datetime(df.index) # Sort the datafr...
<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_tickers_from_file(self, filename): """Load ticker list from txt file"""
if not os.path.exists(filename): log.error("Ticker List file does not exist: %s", filename) tickers = [] with io.open(filename, 'r') as fd: for ticker in fd: tickers.append(ticker.rstrip()) return tickers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_dataframe_to_idb(self, ticker): """Write Pandas Dataframe to InfluxDB database"""
cachepath = self._cache cachefile = ('%s/%s-1M.csv.gz' % (cachepath, ticker)) if not os.path.exists(cachefile): log.warn('Import file does not exist: %s' % (cachefile)) return df = pd.read_csv(cachefile, compression='infer', header=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 connect(self, **kwargs): """ Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None """
self.app = self._app.connect(**kwargs) try: self._top_window = self.app.top_window().wrapper_object() self.set_foreground() except RuntimeError: self._top_window = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_rect(self): """ Get rectangle of app or desktop resolution Returns: RECT(left, top, right, bottom) """
if self.handle: left, top, right, bottom = win32gui.GetWindowRect(self.handle) return RECT(left, top, right, bottom) else: desktop = win32gui.GetDesktopWindow() left, top, right, bottom = win32gui.GetWindowRect(desktop) return RECT(left, top, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def snapshot(self, filename="tmp.png"): """ Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screen...
if not filename: filename = "tmp.png" if self.handle: try: screenshot(filename, self.handle) except win32gui.error: self.handle = None screenshot(filename) else: screenshot(filename) img = 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 _SimpleDecoder(wire_type, decode_value): """Return a constructor for a decoder for fields of a particular type. Args: wire_type: The field's wire type. decod...
def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default): if is_packed: local_DecodeVarint = _DecodeVarint def DecodePackedField(buffer, pos, end, message, field_dict): value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ModifiedDecoder(wire_type, decode_value, modify_value): """Like SimpleDecoder but additionally invokes modify_value on every value before storing it. Usuall...
# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but # not enough to make a significant difference. def InnerDecode(buffer, pos): (result, new_pos) = decode_value(buffer, pos) return (modify_value(result), new_pos) return _SimpleDecoder(wire_type, InnerDecode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _StructPackDecoder(wire_type, format): """Return a constructor for a decoder for a fixed-width field. Args: wire_type: The field's wire type. format: The for...
value_size = struct.calcsize(format) local_unpack = struct.unpack # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but # not enough to make a significant difference. # Note that we expect someone up-stack to catch struct.error and convert # it to _DecodeError -- this way we don'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _FloatDecoder(): """Returns a decoder for a float field. This code works around a bug in struct.unpack for non-finite 32-bit floating-point values. """
local_unpack = struct.unpack def InnerDecode(buffer, pos): # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand. new_pos = pos + 4 float_bytes = buffer[pos:new_pos] # If this value has all its ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _DoubleDecoder(): """Returns a decoder for a double field. This code works around a bug in struct.unpack for not-a-number. """
local_unpack = struct.unpack def InnerDecode(buffer, pos): # We expect a 64-bit value in little-endian byte order. Bit 1 is the sign # bit, bits 2-12 represent the exponent, and bits 13-64 are the significand. new_pos = pos + 8 double_bytes = buffer[pos:new_pos] # If this value has all its ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def StringDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a string field."""
local_DecodeVarint = _DecodeVarint local_unicode = six.text_type def _ConvertToUnicode(byte_str): try: return local_unicode(byte_str, 'utf-8') except UnicodeDecodeError as e: # add more information to the error message and re-raise it. e.reason = '%s in field: %s' % (e, key.full_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 BytesDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a bytes field."""
local_DecodeVarint = _DecodeVarint assert not is_packed if is_repeated: tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) def DecodeRepeatedField(buffer, pos, end, message, field_dict): value = field_dic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GroupDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a group field."""
end_tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_END_GROUP) end_tag_len = len(end_tag_bytes) assert not is_packed if is_repeated: tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_START_GROUP) tag_len...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def MapDecoder(field_descriptor, new_default, is_message_map): """Returns a decoder for a map field."""
key = field_descriptor tag_bytes = encoder.TagBytes(field_descriptor.number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) local_DecodeVarint = _DecodeVarint # Can't read _concrete_class yet; might not be initialized. message_type = field_descriptor.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 _SkipVarint(buffer, pos, end): """Skip a varint value. Returns the new position."""
# Previously ord(buffer[pos]) raised IndexError when pos is out of range. # With this code, ord(b'') raises TypeError. Both are handled in # python_message.py to generate a 'Truncated message' error. while ord(buffer[pos:pos+1]) & 0x80: pos += 1 pos += 1 if pos > end: raise _DecodeError('Truncated...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _SkipLengthDelimited(buffer, pos, end): """Skip a length-delimited value. Returns the new position."""
(size, pos) = _DecodeVarint(buffer, pos) pos += size if pos > end: raise _DecodeError('Truncated message.') return pos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _SkipGroup(buffer, pos, end): """Skip sub-group. Returns the new position."""
while 1: (tag_bytes, pos) = ReadTag(buffer, pos) new_pos = SkipField(buffer, pos, end, tag_bytes) if new_pos == -1: return pos pos = new_pos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _FieldSkipper(): """Constructs the SkipField function."""
WIRETYPE_TO_SKIPPER = [ _SkipVarint, _SkipFixed64, _SkipLengthDelimited, _SkipGroup, _EndGroup, _SkipFixed32, _RaiseInvalidWireType, _RaiseInvalidWireType, ] wiretype_mask = wire_format.TAG_TYPE_MASK def SkipField(buffer, pos, end, tag_bytes): """Skips...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, dataset, output_type='class', missing_value_action='auto'): """ A flexible and advanced prediction API. The target column is provided during :f...
_check_categorical_option_type('output_type', output_type, ['class', 'margin', 'probability', 'probability_vector']) return super(_Classifier, self).predict(dataset, output_type=output_type, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slave_envs(self): """ get enviroment variables for slaves can be passed in as args or envs """
if self.hostIP == 'dns': host = socket.gethostname() elif self.hostIP == 'ip': host = socket.gethostbyname(socket.getfqdn()) else: host = self.hostIP return {'rabit_tracker_uri': host, 'rabit_tracker_port': self.port}
<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_share_ring(self, tree_map, parent_map, r): """ get a ring structure that tends to share nodes with the tree return a list starting from r """
nset = set(tree_map[r]) cset = nset - set([parent_map[r]]) if len(cset) == 0: return [r] rlst = [r] cnt = 0 for v in cset: vlst = self.find_share_ring(tree_map, parent_map, v) cnt += 1 if cnt == len(cset): 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 get_ring(self, tree_map, parent_map): """ get a ring connection used to recover local data """
assert parent_map[0] == -1 rlst = self.find_share_ring(tree_map, parent_map, 0) assert len(rlst) == len(tree_map) ring_map = {} nslave = len(tree_map) for r in range(nslave): rprev = (r + nslave - 1) % nslave rnext = (r + 1) % nslave r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_link_map(self, nslave): """ get the link map, this is a bit hacky, call for better algorithm to place similar nodes together """
tree_map, parent_map = self.get_tree(nslave) ring_map = self.get_ring(tree_map, parent_map) rmap = {0 : 0} k = 0 for i in range(nslave - 1): k = ring_map[k][1] rmap[k] = i + 1 ring_map_ = {} tree_map_ = {} parent_map_ ={} ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maybe_rewrite_setup(toolset, setup_script, setup_options, version, rewrite_setup='off'): """ Helper rule to generate a faster alternative to MSVC setup scrip...
result = '"{}" {}'.format(setup_script, setup_options) # At the moment we only know how to rewrite scripts with cmd shell. if os.name == 'nt' and rewrite_setup != 'off': basename = os.path.basename(setup_script) filename, _ = os.path.splitext(basename) setup_script_id = 'b2_{}_{}_{...
<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(dataset, target, features=None, validation_set = 'auto', verbose=True): """ Automatically create a suitable classifier model based on the provided tra...
return _sl.create_classification_with_model_selector( dataset, target, model_selector = _turicreate.extensions._supervised_learning._classifier_available_models, features = features, validation_set = validation_set, verbose = verbose)
<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_column(self, data, column_name="", inplace=False): """ Adds the specified column to this SFrame. The number of elements in the data given must match ever...
# Check type for pandas dataframe or SArray? if not isinstance(data, SArray): raise TypeError("Must give column as SArray") if not isinstance(column_name, str): raise TypeError("Invalid column name: must be str") if inplace: self.__is_dirty__ = True ...
<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_columns(self, data, column_names=None, inplace=False): """ Adds columns to the SFrame. The number of elements in all columns must match every other colum...
datalist = data if isinstance(data, SFrame): other = data datalist = [other.select_column(name) for name in other.column_names()] column_names = other.column_names() my_columns = set(self.column_names()) for name in column_names: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_column(self, column_name, inplace=False): """ Removes the column with the given name from the SFrame. If inplace == False (default) this operation doe...
if column_name not in self.column_names(): raise KeyError('Cannot find column %s' % column_name) if inplace: self.__is_dirty__ = True try: with cython_context(): if self._is_vertex_frame(): assert column_nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def swap_columns(self, column_name_1, column_name_2, inplace=False): """ Swaps the columns with the given names. If inplace == False (default) this operation doe...
if inplace: self.__is_dirty__ = True with cython_context(): if self._is_vertex_frame(): graph_proxy = self.__graph__.__proxy__.swap_vertex_fields(column_name_1, column_name_2) self.__graph__.__proxy__ = graph_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 rename(self, names, inplace=False): """ Rename the columns using the 'names' dict. This changes the names of the columns given as the keys and replaces them ...
if (type(names) is not dict): raise TypeError('names must be a dictionary: oldname -> newname') if inplace: self.__is_dirty__ = True with cython_context(): if self._is_vertex_frame(): graph_proxy = self.__graph__.__proxy__.rename_...
<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_rows(self): """ Returns the number of rows. Returns ------- out : int Number of rows in the SFrame. """
if self._is_vertex_frame(): return self.__graph__.summary()['num_vertices'] elif self._is_edge_frame(): return self.__graph__.summary()['num_edges']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column_names(self): """ Returns the column names. Returns ------- out : list[string] Column names of the SFrame. """
if self._is_vertex_frame(): return self.__graph__.__proxy__.get_vertex_fields() elif self._is_edge_frame(): return self.__graph__.__proxy__.get_edge_fields()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column_types(self): """ Returns the column types. Returns ------- out : list[type] Column types of the SFrame. """
if self.__type__ == VERTEX_GFRAME: return self.__graph__.__proxy__.get_vertex_field_types() elif self.__type__ == EDGE_GFRAME: return self.__graph__.__proxy__.get_edge_field_types()
<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(dataset, target, features=None, validation_set = 'auto', verbose=True): """ Automatically create a suitable regression model based on the provided tra...
dataset, validation_set = _validate_data(dataset, target, features, validation_set) if validation_set is None: validation_set = _turicreate.SFrame() model_proxy = _turicreate.extensions.create_automatic_regression_model( dataset, target, valida...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def removable(self, node): ''' node is removable only if all of its children are as well. ''' throw_away = [] for child in self.children(node): throw_away.append(self.visit(child)) if self.mode == 'exclusive': return all(throw_away) elif self.mode == 'inclusive': 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 reduce(self, body): ''' remove nodes from a list ''' i = 0 while i < len(body): stmnt = body[i] if self.visit(stmnt): body.pop(i) else: i += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RegisterMessage(self, message): """Registers the given message type in the local database. Calls to GetSymbol() and GetMessages() will return messages regist...
desc = message.DESCRIPTOR self._classes[desc.full_name] = message self.pool.AddDescriptor(desc) 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 GetMessages(self, files): # TODO(amauryfa): Fix the differences with MessageFactory. """Gets all registered messages from a specified file. Only messages al...
def _GetAllMessageNames(desc): """Walk a message Descriptor and recursively yields all message names.""" yield desc.full_name for msg_desc in desc.nested_types: for full_name in _GetAllMessageNames(msg_desc): yield full_name result = {} for file_name in files: fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_prob_and_prob_vector(predictions): """ Check that the predictionsa are either probabilities of prob-vectors. """
from .._deps import numpy ptype = predictions.dtype import array if ptype not in [float, numpy.ndarray, array.array, int]: err_msg = "Input `predictions` must be of numeric type (for binary " err_msg += "classification) or array (of probability vectors) for " err_msg += "multi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _supervised_evaluation_error_checking(targets, predictions): """ Perform basic error checking for the evaluation metrics. Check types and sizes of the inputs...
_raise_error_if_not_sarray(targets, "targets") _raise_error_if_not_sarray(predictions, "predictions") if (len(targets) != len(predictions)): raise _ToolkitError( "Input SArrays 'targets' and 'predictions' must be of the same 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 max_error(targets, predictions): r""" Compute the maximum absolute deviation between two SArrays. Parameters targets : SArray[float or int] An Sarray of grou...
_supervised_evaluation_error_checking(targets, predictions) return _turicreate.extensions._supervised_streaming_evaluator(targets, predictions, "max_error", {})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rmse(targets, predictions): r""" Compute the root mean squared error between two SArrays. Parameters targets : SArray[float or int] An Sarray of ground truth...
_supervised_evaluation_error_checking(targets, predictions) return _turicreate.extensions._supervised_streaming_evaluator(targets, predictions, "rmse", {})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confusion_matrix(targets, predictions): r""" Compute the confusion matrix for classifier predictions. Parameters targets : SArray Ground truth class labels (...
_supervised_evaluation_error_checking(targets, predictions) _check_same_type_not_float(targets, predictions) return _turicreate.extensions._supervised_streaming_evaluator(targets, predictions, "confusion_matrix_no_map", {})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auc(targets, predictions, average='macro', index_map=None): r""" Compute the area under the ROC curve for the given targets and predictions. Parameters targe...
_supervised_evaluation_error_checking(targets, predictions) _check_categorical_option_type('average', average, ['macro', None]) _check_prob_and_prob_vector(predictions) _check_target_not_float(targets) _check_index_map(index_map) opts = {"average": average, ...
<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_library_meta(self): ''' Fetches the meta data for the current library. The data could be in the superlib meta data file. If we can't find the data None is returned. ''' parent_dir = os.path.dirname(self.library_dir) if self.test_file_exists(os.path.join(self.libra...
<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(model, feature_names = None, target = 'target', force_32bit_float = True): """ Convert a trained XGBoost model to Core ML format. Parameters decision...
return _MLModel(_convert_tree_ensemble(model, feature_names, target, force_32bit_float = force_32bit_float))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit(self, data): """ Fit a transformer using the SFrame `data`. Parameters data : SFrame The data used to fit the transformer. Returns ------- self (A fitted...
_raise_error_if_not_sframe(data, "data") self.__proxy__.fit(data) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_features(self, dataset, missing_value_action='auto'): """ For each example in the dataset, extract the leaf indices of each tree as features. For mul...
_raise_error_if_not_sframe(dataset, "dataset") if missing_value_action == 'auto': missing_value_action = select_default_missing_value_policy(self, 'extract_features') return self.__proxy__.extract_features(dataset, missing_value_action)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_features_with_missing(self, dataset, tree_id = 0, missing_value_action = 'auto'): """ Extract features along with all the missing features associate...
# Extract the features from only one tree. sf = dataset sf['leaf_id'] = self.extract_features(dataset, missing_value_action)\ .vector_slice(tree_id)\ .astype(int) tree = self._get_tree(tree_id) type_map = dict(zip(datas...
<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_topk_votes(x, k): """ Sort a dictionary of classes and corresponding vote totals according to the votes, then truncate to the highest 'k' classes. """
y = sorted(x.items(), key=lambda x: x[1], reverse=True)[:k] return [{'class': i[0], 'votes': i[1]} for i in y]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _construct_auto_distance(features, column_types): """ Construct a composite distance function for a set of features, based on the types of those features. NO...
## Put input features into buckets based on type. numeric_ftrs = [] string_ftrs = [] dict_ftrs = [] for ftr in features: try: ftr_type = column_types[ftr] except: raise ValueError("The specified feature does not exist in the " + ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_version(cls, state, version): """ A function to load a previously saved NearestNeighborClassifier model. Parameters unpickler : GLUnpickler A GLUnpickl...
assert(version == cls._PYTHON_NN_CLASSIFIER_MODEL_VERSION) knn_model = _tc.nearest_neighbors.NearestNeighborsModel(state['knn_model']) del state['knn_model'] state['_target_type'] = eval(state['_target_type']) return cls(knn_model, state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(self, dataset, metric='auto', max_neighbors=10, radius=None): """ Evaluate the model's predictive accuracy. This is done by predicting the target cl...
## Validate the metric name _raise_error_evaluation_metric_is_valid(metric, ['auto', 'accuracy', 'confusion_matrix', 'roc_curve']) ## Make sure the input dataset has a target column with an appropriate # type. target = self.target _raise_error_if_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 fit_transform(self, data): """ First fit a transformer using the SFrame `data` and then return a transformed version of `data`. Parameters data : SFrame The ...
if not self._transformers: return self._preprocess(data) transformed_data = self._preprocess(data) final_step = self._transformers[-1] return final_step[1].fit_transform(transformed_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_version(cls, unpickler, version): """ An function to load an object with a specific version of the class. Parameters pickler : file A GLUnpickler file ...
obj = unpickler.load() return TransformerChain(obj._state["steps"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(graph, reset_probability=0.15, threshold=1e-2, max_iterations=20, _single_precision=False, _distributed='auto', verbose=True): """ Compute the PageRan...
from turicreate._cython.cy_server import QuietProgress if not isinstance(graph, _SGraph): raise TypeError('graph input must be a SGraph object.') opts = {'threshold': threshold, 'reset_probability': reset_probability, 'max_iterations': max_iterations, 'single_precision': _...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_link_flags(toolset, linker, condition): """ Now, the vendor specific flags. The parameter linker can be either gnu, darwin, osf, hpux or sun. """
toolset_link = toolset + '.link' if linker == 'gnu': # Strip the binary when no debugging is needed. We use --strip-all flag # as opposed to -s since icc (intel's compiler) is generally # option-compatible with and inherits from the gcc toolset, but does not # support -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 add_dependency (self, targets, sources): """Adds a dependency from 'targets' to 'sources' Both 'targets' and 'sources' can be either list of target names, or...
if isinstance (targets, str): targets = [targets] if isinstance (sources, str): sources = [sources] assert is_iterable(targets) assert is_iterable(sources) for target in targets: for source in sources: self.do_add_dependency (...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_target_variable(self, targets, variable): """Gets the value of `variable` on set on the first target in `targets`. Args: targets (str or list): one or m...
if isinstance(targets, str): targets = [targets] assert is_iterable(targets) assert isinstance(variable, basestring) return bjam_interface.call('get-target-variable', targets, variable)
<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_target_variable (self, targets, variable, value, append=0): """ Sets a target variable. The 'variable' will be available to bjam when it decides where to...
if isinstance (targets, str): targets = [targets] if isinstance(value, str): value = [value] assert is_iterable(targets) assert isinstance(variable, basestring) assert is_iterable(value) if targets: if append: bjam_in...
<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_update_action (self, action_name, targets, sources, properties=None): """ Binds a target to the corresponding update action. If target needs to be update...
if isinstance(targets, str): targets = [targets] if isinstance(sources, str): sources = [sources] if properties is None: properties = property_set.empty() assert isinstance(action_name, basestring) assert is_iterable(targets) assert 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 register_action (self, action_name, command='', bound_list = [], flags = [], function = None): """Creates a new build engine action. Creates on bjam side an ...
assert isinstance(action_name, basestring) assert isinstance(command, basestring) assert is_iterable(bound_list) assert is_iterable(flags) assert function is None or callable(function) bjam_flags = reduce(operator.or_, (action_modifiers[flag]...
<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_bjam_action (self, action_name, function=None): """Informs self that 'action_name' is declared in bjam. From this point, 'action_name' is a valid ar...
# We allow duplicate calls to this rule for the same # action name. This way, jamfile rules that take action names # can just register them without specially checking if # action is already registered. assert isinstance(action_name, basestring) assert function 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 pixel_data(self): """ Returns the pixel data stored in the Image object. Returns ------- out : numpy.array The pixel data of the Image object. It returns a m...
from .. import extensions as _extensions data = _np.zeros((self.height, self.width, self.channels), dtype=_np.uint8) _extensions.image_load_to_numpy(self, data.ctypes.data, data.strides) if self.channels == 1: data = data.squeeze(2) return data