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 imdecode(self, s): """Decodes a string or byte string to an NDArray. See mx.img.imdecode for more details."""
def locate(): """Locate the image file/index if decode fails.""" if self.seq is not None: idx = self.seq[(self.cur % self.num_image) - 1] else: idx = (self.cur % self.num_image) - 1 if self.imglist is not None: _, f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def word_to_vector(word): """ Convert character vectors to integer vectors. """
vector = [] for char in list(word): vector.append(char2int(char)) return vector
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vector_to_word(vector): """ Convert integer vectors to character vectors. """
word = "" for vec in vector: word = word + int2char(vec) return word
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def char_conv(out): """ Convert integer vectors to character vectors for batch. """
out_conv = list() for i in range(out.shape[0]): tmp_str = '' for j in range(out.shape[1]): if int(out[i][j]) >= 0: tmp_char = int2char(int(out[i][j])) if int(out[i][j]) == 27: tmp_char = '' tmp_str = tmp_str + tmp_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_frames(root_path): """Get path to all the frame in view SAX and contain complete frames"""
ret = [] for root, _, files in os.walk(root_path): root=root.replace('\\','/') files=[s for s in files if ".dcm" in s] if len(files) == 0 or not files[0].endswith(".dcm") or root.find("sax") == -1: continue prefix = files[0].rsplit('-', 1)[0] fileset = set(files) ...
<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_data_csv(fname, frames, preproc): """Write data to csv file"""
fdata = open(fname, "w") dr = Parallel()(delayed(get_data)(lst,preproc) for lst in frames) data,result = zip(*dr) for entry in data: fdata.write(','.join(entry)+'\r\n') print("All finished, %d slices in total" % len(data)) fdata.close() result = np.ravel(result) 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 crop_resize(img, size): """crop center and resize"""
if img.shape[0] < img.shape[1]: img = img.T # we crop image from center short_egde = min(img.shape[:2]) yy = int((img.shape[0] - short_egde) / 2) xx = int((img.shape[1] - short_egde) / 2) crop_img = img[yy : yy + short_egde, xx : xx + short_egde] # resize to 64, 64 resized_img = transfor...
<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_generator(): """ construct and return generator """
g_net = gluon.nn.Sequential() with g_net.name_scope(): g_net.add(gluon.nn.Conv2DTranspose( channels=512, kernel_size=4, strides=1, padding=0, use_bias=False)) g_net.add(gluon.nn.BatchNorm()) g_net.add(gluon.nn.LeakyReLU(0.2)) g_net.add(gluon.nn.Conv2DTranspose( ...
<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_descriptor(ctx): """ construct and return descriptor """
d_net = gluon.nn.Sequential() with d_net.name_scope(): d_net.add(SNConv2D(num_filter=64, kernel_size=4, strides=2, padding=1, in_channels=3, ctx=ctx)) d_net.add(gluon.nn.LeakyReLU(0.2)) d_net.add(SNConv2D(num_filter=128, kernel_size=4, strides=2, padding=1, in_channels=64, ctx=ctx)) ...
<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, label): """ generate random cropping boxes according to parameters if satifactory crops generated, apply to ground-truth as well Parameters: lab...
samples = [] count = 0 for trial in range(self.max_trials): if count >= self.max_sample: return samples scale = np.random.uniform(self.min_scale, self.max_scale) min_ratio = max(self.min_aspect_ratio, scale * scale) max_ratio = min...
<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_satisfy(self, rand_box, gt_boxes): """ check if overlap with any gt box is larger than threshold """
l, t, r, b = rand_box num_gt = gt_boxes.shape[0] ls = np.ones(num_gt) * l ts = np.ones(num_gt) * t rs = np.ones(num_gt) * r bs = np.ones(num_gt) * b mask = np.where(ls < gt_boxes[:, 1])[0] ls[mask] = gt_boxes[mask, 1] mask = np.where(ts < gt_boxes...
<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, label): """ generate random padding boxes according to parameters if satifactory padding generated, apply to ground-truth as well Parameters: la...
samples = [] count = 0 for trial in range(self.max_trials): if count >= self.max_sample: return samples scale = np.random.uniform(self.min_scale, self.max_scale) min_ratio = max(self.min_aspect_ratio, scale * scale) max_ratio = min...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs): """Measure time cost of running a function """
mx.nd.waitall() args_list = [] for arg in args: args_list.append(arg) start = time.time() if scipy_trans_lhs: args_list[0] = np.transpose(args_list[0]) if scipy_dns_lhs else sp.spmatrix.transpose(args_list[0]) for _ in range(repeat): func_name(*args_list, **kwargs) m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_batchify_fn(data): """Collate data into batch."""
if isinstance(data[0], nd.NDArray): return nd.stack(*data) elif isinstance(data[0], tuple): data = zip(*data) return [default_batchify_fn(i) for i in data] else: data = np.asarray(data) return nd.array(data, dtype=data.dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_mp_batchify_fn(data): """Collate data into batch. Use shared memory for stacking."""
if isinstance(data[0], nd.NDArray): out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype, ctx=context.Context('cpu_shared', 0)) return nd.stack(*data, out=out) elif isinstance(data[0], tuple): data = zip(*data) return [default_mp_batchify_fn(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 _as_in_context(data, ctx): """Move data into new context."""
if isinstance(data, nd.NDArray): return data.as_in_context(ctx) elif isinstance(data, (list, tuple)): return [_as_in_context(d, ctx) for d in data] return 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 worker_loop_v1(dataset, key_queue, data_queue, batchify_fn): """Worker loop for multiprocessing DataLoader."""
while True: idx, samples = key_queue.get() if idx is None: break batch = batchify_fn([dataset[i] for i in samples]) data_queue.put((idx, batch))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetcher_loop_v1(data_queue, data_buffer, pin_memory=False, pin_device_id=0, data_buffer_lock=None): """Fetcher loop for fetching data from queue and put in r...
while True: idx, batch = data_queue.get() if idx is None: break if pin_memory: batch = _as_in_context(batch, context.cpu_pinned(pin_device_id)) else: batch = _as_in_context(batch, context.cpu()) if data_buffer_lock is not 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 shutdown(self): """Shutdown internal workers by pushing terminate signals."""
if not self._shutdown: # send shutdown signal to the fetcher and join data queue first # Remark: loop_fetcher need to be joined prior to the workers. # otherwise, the the fetcher may fail at getting data self._data_queue.put((None, 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 _ctype_key_value(keys, vals): """ Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only. """
if isinstance(keys, (tuple, list)): assert(len(keys) == len(vals)) c_keys = [] c_vals = [] use_str_keys = None for key, val in zip(keys, vals): c_key_i, c_val_i, str_keys_i = _ctype_key_value(key, val) c_keys += c_key_i c_vals += c_val_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 create(name='local'): """Creates a new KVStore. For single machine training, there are two commonly used types: ``local``: Copies all gradients to CPU memory...
if not isinstance(name, string_types): raise TypeError('name must be a string') handle = KVStoreHandle() check_call(_LIB.MXKVStoreCreate(c_str(name), ctypes.byref(handle))) kv = KVStore(handle) set_kvstore_handle(kv.handle) return kv
<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(self, key, value): """ Initializes a single or a sequence of key-value pairs into the store. For each key, one must `init` it before calling `push` or `...
ckeys, cvals, use_str_keys = _ctype_key_value(key, value) if use_str_keys: check_call(_LIB.MXKVStoreInitEx(self.handle, mx_uint(len(ckeys)), ckeys, cvals)) else: check_call(_LIB.MXKVStoreInit(self.handle, mx_uint(len(ckeys)), ckeys, cvals))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self, key, value, priority=0): """ Pushes a single or a sequence of key-value pairs into the store. This function returns immediately after adding an op...
ckeys, cvals, use_str_keys = _ctype_key_value(key, value) if use_str_keys: check_call(_LIB.MXKVStorePushEx( self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority))) else: check_call(_LIB.MXKVStorePush( self.handle, mx_uint(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pull(self, key, out=None, priority=0, ignore_sparse=True): """ Pulls a single value or a sequence of values from the store. This function returns immediately...
assert(out is not None) ckeys, cvals, use_str_keys = _ctype_key_value(key, out) if use_str_keys: check_call(_LIB.MXKVStorePullWithSparseEx(self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def row_sparse_pull(self, key, out=None, priority=0, row_ids=None): """ Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \ from the...
assert(out is not None) assert(row_ids is not None) if isinstance(row_ids, NDArray): row_ids = [row_ids] assert(isinstance(row_ids, list)), \ "row_ids should be NDArray or list of NDArray" first_out = out # whether row_ids are the same sin...
<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_gradient_compression(self, compression_params): """ Specifies type of low-bit quantization for gradient compression \ and additional arguments depending ...
if ('device' in self.type) or ('dist' in self.type): # pylint: disable=unsupported-membership-test ckeys, cvals = _ctype_dict(compression_params) check_call(_LIB.MXKVStoreSetGradientCompression(self.handle, mx_uint(len(compress...
<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_optimizer(self, optimizer): """ Registers an optimizer with the kvstore. When using a single machine, this function updates the local optimizer. If using...
is_worker = ctypes.c_int() check_call(_LIB.MXKVStoreIsWorkerNode(ctypes.byref(is_worker))) # pylint: disable=invalid-name if 'dist' in self.type and is_worker.value: # pylint: disable=unsupported-membership-test # send the optimizer to server try: ...
<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(self): """ Returns the type of this kvstore. Returns ------- type : str the string type """
kv_type = ctypes.c_char_p() check_call(_LIB.MXKVStoreGetType(self.handle, ctypes.byref(kv_type))) return py_str(kv_type.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 rank(self): """ Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers()) """
rank = ctypes.c_int() check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank))) return rank.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 num_workers(self): """Returns the number of worker nodes. Returns ------- size :int The number of worker nodes. """
size = ctypes.c_int() check_call(_LIB.MXKVStoreGetGroupSize(self.handle, ctypes.byref(size))) return size.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 _set_updater(self, updater): """Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must us...
self._updater = updater # set updater with int keys _updater_proto = ctypes.CFUNCTYPE( None, ctypes.c_int, NDArrayHandle, NDArrayHandle, ctypes.c_void_p) self._updater_func = _updater_proto(_updater_wrapper(updater)) # set updater with str keys _str_updater_p...
<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_command_to_servers(self, head, body): """Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``...
check_call(_LIB.MXKVStoreSendCommmandToServers( self.handle, mx_uint(head), c_str(body)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, module, **kwargs): """Add a module to the chain. Parameters module : BaseModule The new module to add. kwargs : ``**keywords`` All the keyword argu...
self._modules.append(module) # a sanity check to avoid typo for key in kwargs: assert key in self._meta_keys, ('Unknown meta "%s", a typo?' % key) self._metas.append(kwargs) # after adding new modules, we are reset back to raw states, needs # to bind, init...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_monitor(self, mon): """Installs monitor on all executors."""
assert self.binded for module in self._modules: module.install_monitor(mon)
<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_iterator(data_shape, use_caffe_data): """Generate the iterator of mnist dataset"""
def get_iterator_impl_mnist(args, kv): """return train and val iterators for mnist""" # download data get_mnist_ubyte() flat = False if len(data_shape) != 1 else True train = mx.io.MNISTIter( image="data/train-images-idx3-ubyte", label="data/train-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 predict(prediction_dir='./Test'): """The function is used to run predictions on the audio files in the directory `pred_directory`. Parameters net: The model ...
if not os.path.exists(prediction_dir): warnings.warn("The directory on which predictions are to be made is not found!") return if len(os.listdir(prediction_dir)) == 0: warnings.warn("The directory on which predictions are to be made is empty! Exiting...") return # Loading...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _proc_loop(proc_id, alive, queue, fn): """Thread loop for generating data Parameters proc_id: int Process id alive: multiprocessing.Value variable for signal...
print("proc {} started".format(proc_id)) try: while alive.value: data = fn() put_success = False while alive.value and not put_success: try: queue.put(data, timeout=0.5) put_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 _init_proc(self): """Start processes if not already started"""
if not self.proc: self.proc = [ mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn)) for i in range(self.num_proc) ] self.alive.value = True for p in self.proc: p.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Resets the generator by stopping all processes"""
self.alive.value = False qsize = 0 try: while True: self.queue.get(timeout=0.1) qsize += 1 except QEmptyExcept: pass print("Queue size on reset: {}".format(qsize)) for i, p in enumerate(self.proc): p.joi...
<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_lib(): """Load library by searching possible path."""
lib_path = libinfo.find_lib_path() lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL) # DMatrix functions lib.MXGetLastError.restype = ctypes.c_char_p return lib
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def c_array(ctype, values): """Create ctypes array from a Python array. Parameters ctype : ctypes data type Data type of the array we want to convert to, such as...
out = (ctype * len(values))() out[:] = values return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ctypes2numpy_shared(cptr, shape): """Convert a ctypes pointer to a numpy array. The resulting NumPy array shares the memory with the pointer. Parameters cptr...
if not isinstance(cptr, ctypes.POINTER(mx_float)): raise RuntimeError('expected float pointer') size = 1 for s in shape: size *= s dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents)) return _np.frombuffer(dbuffer, dtype=_np.float32).reshape(shape)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True): """Build argument docs in python style. arg_names : list of str Argument names. arg_types ...
param_keys = set() param_str = [] for key, type_info, desc in zip(arg_names, arg_types, arg_descs): if key in param_keys and remove_dup: continue if key == 'num_args': continue param_keys.add(key) ret = '%s : %s' % (key, type_info) if len(desc...
<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_fileline_to_docstring(module, incursive=True): """Append the definition position to each function contained in module. Examples -------- # Put the follow...
def _add_fileline(obj): """Add fileinto to a object. """ if obj.__doc__ is None or 'From:' in obj.__doc__: return fname = inspect.getsourcefile(obj) if fname is None: return try: line = inspect.getsourcelines(obj)[-1] exce...
<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_np_compat(): """ Checks whether the NumPy compatibility is currently turned on. NumPy-compatibility is turned off by default in backend. Returns ------- A...
curr = ctypes.c_bool() check_call(_LIB.MXIsNumpyCompatible(ctypes.byref(curr))) return curr.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 use_np_compat(func): """Wraps a function with an activated NumPy-compatibility scope. This ensures that the execution of the function is guaranteed with NumP...
@wraps(func) def _with_np_compat(*args, **kwargs): with np_compat(active=True): return func(*args, **kwargs) return _with_np_compat
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def corr(label, pred): """computes the empirical correlation coefficient"""
numerator1 = label - np.mean(label, axis=0) numerator2 = pred - np.mean(pred, axis = 0) numerator = np.mean(numerator1 * numerator2, axis=0) denominator = np.std(label, axis=0) * np.std(pred, axis=0) return np.mean(numerator / denominator)
<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_input(proto): """Get input size """
layer = caffe_parser.get_layers(proto) if len(proto.input_dim) > 0: input_dim = proto.input_dim elif len(proto.input_shape) > 0: input_dim = proto.input_shape[0].dim elif layer[0].type == "Input": input_dim = layer[0].input_param.shape[0].dim layer.pop(0) 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_conv_param(param): """ Convert convolution layer parameter from Caffe to MXNet """
param_string = "num_filter=%d" % param.num_output pad_w = 0 pad_h = 0 if isinstance(param.pad, int): pad = param.pad param_string += ", pad=(%d, %d)" % (pad, pad) else: if len(param.pad) > 0: pad = param.pad[0] param_string += ", pad=(%d, %d)" % (pad...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_pooling_param(param): """Convert the pooling layer parameter """
param_string = "pooling_convention='full', " if param.global_pooling: param_string += "global_pool=True, kernel=(1,1)" else: param_string += "pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)" % ( param.pad, param.pad, param.kernel_size, param.kernel_size, param.stride, pa...
<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_caffemodel(file_path): """ parses the trained .caffemodel file filepath: /path/to/trained-model.caffemodel returns: layers """
f = open(file_path, 'rb') contents = f.read() net_param = caffe_pb2.NetParameter() net_param.ParseFromString(contents) layers = find_layers(net_param) return layers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(data, target_wd, target_ht, is_train, box): """Crop and normnalize an image nd array."""
if box is not None: x, y, w, h = box data = data[y:min(y+h, data.shape[0]), x:min(x+w, data.shape[1])] # Resize to target_wd * target_ht. data = mx.image.imresize(data, target_wd, target_ht) # Normalize in the same way as the pre-trained model. data = data.astype(np.float32) / 255...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cub200_iterator(data_path, batch_k, batch_size, data_shape): """Return training and testing iterator for the CUB200-2011 dataset."""
return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True), CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=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 get_image(self, img, is_train): """Load and transform an image."""
img_arr = mx.image.imread(img) img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img]) return img_arr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """Return a batch."""
if self.is_train: data, labels = self.sample_train_batch() else: if self.test_count * self.batch_size < len(self.test_image_files): data, labels = self.get_test_batch() self.test_count += 1 else: self.test_count = 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 load_mnist(training_num=50000): """Load mnist dataset"""
data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from six.moves import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def feature_list(): """ Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc Returns ------- list List of...
lib_features_c_array = ctypes.POINTER(Feature)() lib_features_size = ctypes.c_size_t() check_call(_LIB.MXLibInfoFeatures(ctypes.byref(lib_features_c_array), ctypes.byref(lib_features_size))) features = [lib_features_c_array[i] for i in range(lib_features_size.value)] return features
<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_enabled(self, feature_name): """ Check for a particular feature by name Parameters feature_name: str The name of a valid feature as string for example 'CU...
feature_name = feature_name.upper() if feature_name not in self: raise RuntimeError("Feature '{}' is unknown, known features are: {}".format( feature_name, list(self.keys()))) return self[feature_name].enabled
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_path(self): """ make a directory to store all caches Returns: --------- cache path """
cache_path = os.path.join(os.path.dirname(__file__), '..', 'cache') if not os.path.exists(cache_path): os.mkdir(cache_path) return cache_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 do_python_eval(self): """ python evaluation wrapper Returns: None """
annopath = os.path.join(self.data_path, 'Annotations', '{:s}.xml') imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt') cache_dir = os.path.join(self.cache_path, self.name) aps = [] # The PASCAL VOC metric changed in 2010 use_07_metr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CreateMultiRandCropAugmenter(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), min_eject_coverage=0.3, max_attempts=50, skip_pr...
def align_parameters(params): """Align parameters as pairs""" out_params = [] num = 1 for p in params: if not isinstance(p, list): p = [p] out_params.append(p) num = max(num, len(p)) # align for each param for k, p ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CreateDetAugmenter(data_shape, resize=0, rand_crop=0, rand_pad=0, rand_gray=0, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0,...
auglist = [] if resize > 0: auglist.append(DetBorrowAug(ResizeAug(resize, inter_method))) if rand_crop > 0: crop_augs = CreateMultiRandCropAugmenter(min_object_covered, aspect_ratio_range, area_range, min_eject_coverage, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dumps(self): """Override default."""
return [self.__class__.__name__.lower(), [x.dumps() for x in self.aug_list]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculate_areas(self, label): """Calculate areas for multiple labels"""
heights = np.maximum(0, label[:, 3] - label[:, 1]) widths = np.maximum(0, label[:, 2] - label[:, 0]) return heights * widths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _intersect(self, label, xmin, ymin, xmax, ymax): """Calculate intersect areas, normalized."""
left = np.maximum(label[:, 0], xmin) right = np.minimum(label[:, 2], xmax) top = np.maximum(label[:, 1], ymin) bot = np.minimum(label[:, 3], ymax) invalid = np.where(np.logical_or(left >= right, top >= bot))[0] out = label.copy() out[:, 0] = left out[:, 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 _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height): """Check if constrains are satisfied"""
if (xmax - xmin) * (ymax - ymin) < 2: return False # only 1 pixel x1 = float(xmin) / width y1 = float(ymin) / height x2 = float(xmax) / width y2 = float(ymax) / height object_areas = self._calculate_areas(label[:, 1:]) valid_objects = np.where(object...
<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_labels(self, label, crop_box, height, width): """Convert labels according to crop box"""
xmin = float(crop_box[0]) / width ymin = float(crop_box[1]) / height w = float(crop_box[2]) / width h = float(crop_box[3]) / height out = label.copy() out[:, (1, 3)] -= xmin out[:, (2, 4)] -= ymin out[:, (1, 3)] /= w out[:, (2, 4)] /= h ou...
<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_crop_proposal(self, label, height, width): """Propose cropping areas"""
from math import sqrt if not self.enabled or height <= 0 or width <= 0: return () min_area = self.area_range[0] * height * width max_area = self.area_range[1] * height * width for _ in range(self.max_attempts): ratio = random.uniform(*self.aspect_ratio_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 _update_labels(self, label, pad_box, height, width): """Update label according to padding region"""
out = label.copy() out[:, (1, 3)] = (out[:, (1, 3)] * width + pad_box[0]) / pad_box[2] out[:, (2, 4)] = (out[:, (2, 4)] * height + pad_box[1]) / pad_box[3] return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _random_pad_proposal(self, label, height, width): """Generate random padding region"""
from math import sqrt if not self.enabled or height <= 0 or width <= 0: return () min_area = self.area_range[0] * height * width max_area = self.area_range[1] * height * width for _ in range(self.max_attempts): ratio = random.uniform(*self.aspect_ratio_ra...
<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_valid_label(self, label): """Validate label and its shape."""
if len(label.shape) != 2 or label.shape[1] < 5: msg = "Label with shape (1+, 5+) required, %s received." % str(label) raise RuntimeError(msg) valid_label = np.where(np.logical_and(label[:, 0] >= 0, label[:, 3] > label[:, 1], label[:,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _estimate_label_shape(self): """Helper function to estimate label shape"""
max_count = 0 self.reset() try: while True: label, _ = self.next_sample() label = self._parse_label(label) max_count = max(max_count, label.shape[0]) except StopIteration: pass self.reset() return (m...
<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_label(self, label): """Helper function to parse object detection label. Format for raw label: where n is the width of header, 2 or larger k is the wid...
if isinstance(label, nd.NDArray): label = label.asnumpy() raw = label.ravel() if raw.size < 7: raise RuntimeError("Label shape is invalid: " + str(raw.shape)) header_width = int(raw[0]) obj_width = int(raw[1]) if (raw.size - header_width) % obj_wi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reshape(self, data_shape=None, label_shape=None): """Reshape iterator for data_shape or label_shape. Parameters data_shape : tuple or None Reshape the data_s...
if data_shape is not None: self.check_data_shape(data_shape) self.provide_data = [(self.provide_data[0][0], (self.batch_size,) + data_shape)] self.data_shape = data_shape if label_shape is not None: self.check_label_shape(label_shape) self.pro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _batchify(self, batch_data, batch_label, start=0): """Override the helper function for batchifying data"""
i = start batch_size = self.batch_size try: while i < batch_size: label, s = self.next_sample() data = self.imdecode(s) try: self.check_valid_image([data]) label = self._parse_label(label) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """Override the function for returning next batch."""
batch_size = self.batch_size c, h, w = self.data_shape # if last batch data is rolled over if self._cache_data is not None: # check both the data and label have values assert self._cache_label is not None, "_cache_label didn't have values" assert 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 augmentation_transform(self, data, label): # pylint: disable=arguments-differ """Override Transforms input data with specified augmentations."""
for aug in self.auglist: data, label = aug(data, label) return (data, label)
<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_label_shape(self, label_shape): """Checks if the new label shape is valid"""
if not len(label_shape) == 2: raise ValueError('label_shape should have length 2') if label_shape[0] < self.label_shape[0]: msg = 'Attempts to reduce label count from %d to %d, not allowed.' \ % (self.label_shape[0], label_shape[0]) raise ValueError(m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ratio_enum(anchor, ratios): """ Enumerate a set of anchors for each aspect ratio wrt an anchor. """
w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor) size = w * h size_ratios = size / ratios ws = np.round(np.sqrt(size_ratios)) hs = np.round(ws * ratios) anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr) return anchors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _scale_enum(anchor, scales): """ Enumerate a set of anchors for each scale wrt an anchor. """
w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor) ws = w * scales hs = h * scales anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr) return anchors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_data(args): """ set atual shape of data """
rnn_type = args.config.get("arch", "rnn_type") num_rnn_layer = args.config.getint("arch", "num_rnn_layer") num_hidden_rnn_list = json.loads(args.config.get("arch", "num_hidden_rnn_list")) batch_size = args.config.getint("common", "batch_size") if rnn_type == 'lstm': init_c = [('l%d_init_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 check_error(model, path, shapes, output = 'softmax_output', verbose = True): """ Check the difference between predictions from MXNet and CoreML. """
coreml_model = _coremltools.models.MLModel(path) input_data = {} input_data_copy = {} for ip in shapes: input_data[ip] = _np.random.rand(*shapes[ip]).astype('f') input_data_copy[ip] = _np.copy(input_data[ip]) dataIter = _mxnet.io.NDArrayIter(input_data_copy) mx_out = model.pred...
<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_categorical(prob, rng): """Sample from independent categorical distributions Each batch is an independent categorical distribution. Parameters prob : ...
ret = numpy.empty(prob.shape[0], dtype=numpy.float32) for ind in range(prob.shape[0]): ret[ind] = numpy.searchsorted(numpy.cumsum(prob[ind]), rng.rand()).clip(min=0.0, max=prob.shape[ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_normal(mean, var, rng): """Sample from independent normal distributions Each element is an independent normal distribution. Parameters mean : numpy.nd...
ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean 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 nce_loss_subwords( data, label, label_mask, label_weight, embed_weight, vocab_size, num_hidden): """NCE-Loss layer under subword-units input. """
# get subword-units embedding. label_units_embed = mx.sym.Embedding(data=label, input_dim=vocab_size, weight=embed_weight, output_dim=num_hidden) # get valid subword-units embedding wi...
<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_dataset(prefetch=False): """Download the BSDS500 dataset and return train and test iters."""
if path.exists(data_dir): print( "Directory {} already exists, skipping.\n" "To force download and extraction, delete the directory and re-run." "".format(data_dir), file=sys.stderr, ) else: print("Downloading dataset...", file=sys.stderr...
<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(mod, data_iter, epoch, log_interval): """ Run evaluation on cpu. """
start = time.time() total_L = 0.0 nbatch = 0 density = 0 mod.set_states(value=0) for batch in data_iter: mod.forward(batch, is_train=False) outputs = mod.get_outputs(merge_multi_context=False) states = outputs[:-1] total_L += outputs[-1][0] mod.set_states...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """return one dict which contains "data" and "label" """
if self.iter_next(): self.data, self.label = self._read() return {self.data_name : self.data[0][1], self.label_name : self.label[0][1]} else: raise StopIteration
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_onnx(self, graph): """Construct symbol from onnx graph. Parameters graph : onnx protobuf object The loaded onnx graph Returns ------- sym :symbol.Symbol...
# get input, output shapes self.model_metadata = self.get_graph_metadata(graph) # parse network inputs, aka parameters for init_tensor in graph.initializer: if not init_tensor.name.strip(): raise ValueError("Tensor's name is required.") self._para...
<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_graph_metadata(self, graph): """ Get the model metadata from a given onnx graph. """
_params = set() for tensor_vals in graph.initializer: _params.add(tensor_vals.name) input_data = [] for graph_input in graph.input: if graph_input.name not in _params: shape = [val.dim_value for val in graph_input.type.tensor_type.shape.dim] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_to_gluon(self, graph, ctx): """Construct SymbolBlock from onnx graph. Parameters graph : onnx protobuf object The loaded onnx graph ctx : Context or li...
sym, arg_params, aux_params = self.from_onnx(graph) metadata = self.get_graph_metadata(graph) data_names = [input_tensor[0] for input_tensor in metadata['input_tensor_data']] data_inputs = [symbol.var(data_name) for data_name in data_names] from ....gluon import SymbolBlock ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reshape(self, data_shapes, label_shapes=None): """Reshapes both modules for new input shapes. Parameters data_shapes : list of (str, tuple) Typically is ``da...
super(SVRGModule, self).reshape(data_shapes, label_shapes=label_shapes) self._mod_aux.reshape(data_shapes, label_shapes=label_shapes)
<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_optimizer(self, kvstore='local', optimizer='sgd', optimizer_params=(('learning_rate', 0.01),), force_init=False): """Installs and initializes SVRGOptimi...
# Init dict for storing average of full gradients for each device self._param_dict = [{key: mx.nd.zeros(shape=value.shape, ctx=self._context[i]) for key, value in self.get_params()[0].items()} for i in range(self._ctx_len)] svrg_optimizer = self._create_optimizer(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binds the...
# force rebinding is typically used when one want to switch from # training to prediction phase. super(SVRGModule, self).bind(data_shapes, label_shapes, for_training, inputs_need_grad, force_rebind, shared_module, grad_req) if for_training: ...
<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(self, data_batch, is_train=None): """Forward computation for both two modules. It supports data batches with different shapes, such as different batc...
super(SVRGModule, self).forward(data_batch, is_train) if is_train: self._mod_aux.forward(data_batch, is_train)
<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_full_grads(self, train_data): """Computes the gradients over all data w.r.t weights of past m epochs. For distributed env, it will accumulate full gra...
param_names = self._exec_group.param_names arg, aux = self.get_params() self._mod_aux.set_params(arg_params=arg, aux_params=aux) train_data.reset() nbatch = 0 padding = 0 for batch in train_data: self._mod_aux.forward(batch, is_train=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 _accumulate_kvstore(self, key, value): """Accumulate gradients over all data in the KVStore. In distributed setting, each worker sees a portion of data. The ...
# Accumulate full gradients for current epochs self._kvstore.push(key + "_full", value) self._kvstore._barrier() self._kvstore.pull(key + "_full", value) self._allocate_gradients(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 _allocate_gradients(self, key, value): """Allocate average of full gradients accumulated in the KVStore to each device. Parameters key: int or str Key in the...
for i in range(self._ctx_len): self._param_dict[i][key] = value[i] / self._ctx_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 _update_svrg_gradients(self): """Calculates gradients based on the SVRG update rule. """
param_names = self._exec_group.param_names for ctx in range(self._ctx_len): for index, name in enumerate(param_names): g_curr_batch_reg = self._exec_group.grad_arrays[index][ctx] g_curr_batch_special = self._mod_aux._exec_group.grad_arrays[index][ctx] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, data_batch, sparse_row_id_fn=None): """Prepares two modules for processing a data batch. Usually involves switching bucket and reshaping. For m...
super(SVRGModule, self).prepare(data_batch, sparse_row_id_fn=sparse_row_id_fn) self._mod_aux.prepare(data_batch, sparse_row_id_fn=sparse_row_id_fn)