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 get_tld(url):
"""Get the tld of the given URL. Args: url (str):
The URL to get the tld from. Returns: str: The tld """ |
if url not in URLHelper.__cache:
URLHelper.__cache[url] = urlparse(url)
parts = URLHelper.__cache[url].netloc.split(".")
if len(parts) == 1:
return ""
else:
return parts[-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 get_ordered_params(url):
"""Get the query parameters of the given URL in alphabetical order. Args: url (str):
The URL to get the query parameters from. Retu... |
if url not in URLHelper.__cache:
URLHelper.__cache[url] = urlparse(url)
params = URLHelper.query_string_to_dict(URLHelper.__cache[url].query)
return OrderedDict(sorted(params.items())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_dict_to_string(query):
"""Convert an OrderedDict to a query string. Args: query (obj):
The key value object with query params. Returns: str: The query... |
query_params = []
for key, value in query.items():
query_params.append(key + "=" + value)
return "&".join(query_params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_string_to_dict(query):
"""Convert a string to a query dict. Args: query (str):
The query string. Returns: obj: The key value object with query params.... |
query_params = {}
for key_value in query.split("&"):
key_value_pair = key_value.split("=", 1)
key = key_value_pair[0] if len(key_value_pair) >= 1 else ""
value = key_value_pair[1] if len(key_value_pair) == 2 else ""
query_params[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 get_version():
"""Get the version number of this package. Returns: str: The version number (marjor.minor.patch). Note: When this package is installed, the ve... |
if PackageHelper.__version:
return PackageHelper.__version
PackageHelper.__version = "Unknown"
# If this is a GIT clone without install, use the ``.semver`` file.
file = os.path.realpath(__file__)
folder = os.path.dirname(file)
try:
semver = o... |
<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):
"""Executes the HTTP call. Note: If this and the parent handler raised an error, the queue item status will be set to errored instead of finished.... |
try:
self.__options.callbacks.request_in_thread_before_start(self.__queue_item)
except Exception as e:
print(e)
new_requests = []
failed = False
try:
handler = Handler(self.__options, self.__queue_item)
new_requests = handler.ge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_with(self, request):
"""Start the crawler using the given request. Args: request (:class:`nyawc.http.Request`):
The startpoint for the crawler. """ |
HTTPRequestHelper.patch_with_options(request, self.__options)
self.queue.add_request(request)
self.__crawler_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 __spawn_new_requests(self):
"""Spawn new requests until the max threads option value is reached. Note: If no new requests were spawned and there are no reque... |
self.__should_spawn_new_requests = False
in_progress_count = len(self.queue.get_all(QueueItem.STATUS_IN_PROGRESS))
while in_progress_count < self.__options.performance.max_threads:
if self.__spawn_new_request():
in_progress_count += 1
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 __spawn_new_request(self):
"""Spawn the first queued request if there is one available. Returns: bool: True if a new request was spawned, false otherwise. ""... |
first_in_line = self.queue.get_first(QueueItem.STATUS_QUEUED)
if first_in_line is None:
return False
while self.routing.is_treshold_reached(first_in_line.request):
self.queue.move(first_in_line, QueueItem.STATUS_CANCELLED)
first_in_line = self.que... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __crawler_start(self):
"""Spawn the first X queued request, where X is the max threads option. Note: The main thread will sleep until the crawler is finished... |
try:
self.__options.callbacks.crawler_before_start()
except Exception as e:
print(e)
print(traceback.format_exc())
self.__spawn_new_requests()
while not self.__stopped:
if self.__should_stop:
self.__crawler_stop()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __crawler_stop(self):
"""Mark the crawler as stopped. Note: If :attr:`__stopped` is True, the main thread will be stopped. Every piece of code that gets exec... |
if self.__stopping:
return
self.__stopping = True
self.__wait_for_current_threads()
self.queue.move_bulk([
QueueItem.STATUS_QUEUED,
QueueItem.STATUS_IN_PROGRESS
], QueueItem.STATUS_CANCELLED)
self.__crawler_finish()
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 __crawler_finish(self):
"""Called when the crawler is finished because there are no queued requests left or it was stopped.""" |
try:
self.__options.callbacks.crawler_after_finish(self.queue)
except Exception as e:
print(e)
print(traceback.format_exc()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __request_start(self, queue_item):
"""Execute the request in given queue item. Args: queue_item (:class:`nyawc.QueueItem`):
The request/response pair to scr... |
try:
action = self.__options.callbacks.request_before_start(self.queue, queue_item)
except Exception as e:
action = None
print(e)
print(traceback.format_exc())
if action == CrawlerActions.DO_STOP_CRAWLING:
self.__should_stop = 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 __request_finish(self, queue_item, new_requests, request_failed=False):
"""Called when the crawler finished the given queue item. Args: queue_item (:class:`n... |
if self.__stopping:
return
del self.__threads[queue_item.get_hash()]
if request_failed:
new_queue_items = []
self.queue.move(queue_item, QueueItem.STATUS_ERRORED)
else:
self.routing.increase_route_count(queue_item.request)
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 __add_scraped_requests_to_queue(self, queue_item, scraped_requests):
"""Convert the scraped requests to queue items, return them and also add them to the que... |
new_queue_items = []
for scraped_request in scraped_requests:
HTTPRequestHelper.patch_with_options(scraped_request, self.__options, queue_item)
if not HTTPRequestHelper.complies_with_scope(queue_item, scraped_request, self.__options.scope):
continue
... |
<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, train_set, test_set):
"""Fit the model to the given data. :param train_set: training data :param test_set: test data """ |
with tf.Graph().as_default(), tf.Session() as self.tf_session:
self.build_model()
tf.global_variables_initializer().run()
third = self.num_epochs // 3
for i in range(self.num_epochs):
lr_decay = self.lr_decay ** max(i - third, 0.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 _run_train_step(self, data, mode='train'):
"""Run a single training step. :param data: input data :param mode: 'train' or 'test'. """ |
epoch_size = ((len(data) // self.batch_size) - 1) // self.num_steps
costs = 0.0
iters = 0
step = 0
state = self._init_state.eval()
op = self._train_op if mode == 'train' else tf.no_op()
for step, (x, y) in enumerate(
utilities.seq_data_iterator(
... |
<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_model(self):
"""Build the model's computational graph.""" |
with tf.variable_scope(
"model", reuse=None, initializer=self.initializer):
self._create_placeholders()
self._create_rnn_cells()
self._create_initstate_and_embeddings()
self._create_rnn_architecture()
self._create_optimizer_node() |
<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_placeholders(self):
"""Create the computational graph's placeholders.""" |
self.input_data = tf.placeholder(
tf.int32, [self.batch_size, self.num_steps])
self.input_labels = tf.placeholder(
tf.int32, [self.batch_size, self.num_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_rnn_cells(self):
"""Create the LSTM cells.""" |
lstm_cell = tf.nn.rnn_cell.LSTMCell(
self.num_hidden, forget_bias=0.0)
lstm_cell = tf.nn.rnn_cell.DropoutWrapper(
lstm_cell, output_keep_prob=self.dropout)
self.cell = tf.nn.rnn_cell.MultiRNNCell(
[lstm_cell] * self.num_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 _create_initstate_and_embeddings(self):
"""Create the initial state for the cell and the data embeddings.""" |
self._init_state = self.cell.zero_state(self.batch_size, tf.float32)
embedding = tf.get_variable(
"embedding", [self.vocab_size, self.num_hidden])
inputs = tf.nn.embedding_lookup(embedding, self.input_data)
self.inputs = tf.nn.dropout(inputs, self.dropout) |
<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_rnn_architecture(self):
"""Create the training architecture and the last layer of the LSTM.""" |
self.inputs = [tf.squeeze(i, [1]) for i in tf.split(
axis=1, num_or_size_splits=self.num_steps, value=self.inputs)]
outputs, state = tf.nn.rnn(
self.cell, self.inputs, initial_state=self._init_state)
output = tf.reshape(tf.concat(axis=1, values=outputs), [-1, self.num_h... |
<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_optimizer_node(self):
"""Create the optimizer node of the graph.""" |
self.lr_var = tf.Variable(0.0, trainable=False)
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars),
self.max_grad_norm)
optimizer = tf.train.GradientDescentOptimizer(self.lr_var)
self._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 _create_encoding_layers(self):
"""Create the encoding layers for supervised finetuning. :return: output of the final encoding layer. """ |
next_train = self.input_data
self.layer_nodes = []
for l, layer in enumerate(self.layers):
with tf.name_scope("encode-{}".format(l)):
y_act = tf.add(
tf.matmul(next_train, self.encoding_w_[l]),
self.encoding_b_[l]
... |
<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_decoding_layers(self):
"""Create the decoding layers for reconstruction finetuning. :return: output of the final encoding layer. """ |
next_decode = self.encode
for l, layer in reversed(list(enumerate(self.layers))):
with tf.name_scope("decode-{}".format(l)):
# Create decoding variables
if self.tied_weights:
dec_w = tf.transpose(self.encoding_w_[l])
els... |
<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_dataset(mode='supervised', one_hot=True):
"""Load the MNIST handwritten digits dataset. :param mode: 'supervised' or 'unsupervised' mode :param on... |
mnist = input_data.read_data_sets("MNIST_data/", one_hot=one_hot)
# Training set
trX = mnist.train.images
trY = mnist.train.labels
# Validation set
vlX = mnist.validation.images
vlY = mnist.validation.labels
# Test set
teX = mnist.test.images
teY = mnist.test.labels
if 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 load_cifar10_dataset(cifar_dir, mode='supervised'):
"""Load the cifar10 dataset. :param cifar_dir: path to the dataset directory (cPicle format from: https:/... |
# Training set
trX = None
trY = np.array([])
# Test set
teX = np.array([])
teY = np.array([])
for fn in os.listdir(cifar_dir):
if not fn.startswith('batches') and not fn.startswith('readme'):
fo = open(os.path.join(cifar_dir, fn), 'rb')
data_batch = pickle... |
<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(prev_layer, out_dim, name="linear"):
"""Create a linear fully-connected layer. Parameters prev_layer : tf.Tensor Last layer's output tensor. out_dim :... |
with tf.name_scope(name):
in_dim = prev_layer.get_shape()[1].value
W = tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=0.1))
b = tf.Variable(tf.constant(0.1, shape=[out_dim]))
out = tf.add(tf.matmul(prev_layer, W), b)
return (out, W, b) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regularization(variables, regtype, regcoef, name="regularization"):
"""Compute the regularization tensor. Parameters variables : list of tf.Variable List of ... |
with tf.name_scope(name):
if regtype != 'none':
regs = tf.constant(0.0)
for v in variables:
if regtype == 'l2':
regs = tf.add(regs, tf.nn.l2_loss(v))
elif regtype == 'l1':
regs = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accuracy(mod_y, ref_y, summary=True, name="accuracy"):
"""Accuracy computation op. Parameters mod_y : tf.Tensor Model output tensor. ref_y : tf.Tensor Refere... |
with tf.name_scope(name):
mod_pred = tf.argmax(mod_y, 1)
correct_pred = tf.equal(mod_pred, tf.argmax(ref_y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
if summary:
tf.summary.scalar('accuracy', accuracy)
return acc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pretrain_procedure(self, layer_objs, layer_graphs, set_params_func, train_set, validation_set=None):
"""Perform unsupervised pretraining of the model. :param... |
next_train = train_set
next_valid = validation_set
for l, layer_obj in enumerate(layer_objs):
print('Training layer {}...'.format(l + 1))
next_train, next_valid = self._pretrain_layer_and_gen_feed(
layer_obj, set_params_func, next_train, next_valid,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pretrain_layer_and_gen_feed(self, layer_obj, set_params_func, train_set, validation_set, graph):
"""Pretrain a single autoencoder and encode the data for th... |
layer_obj.fit(train_set, train_set,
validation_set, validation_set, graph=graph)
with graph.as_default():
set_params_func(layer_obj, graph)
next_train = layer_obj.transform(train_set, graph=graph)
if validation_set 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 get_layers_output(self, dataset):
"""Get output from each layer of the network. :param dataset: input data :return: list of np array, element i is the output... |
layers_out = []
with self.tf_graph.as_default():
with tf.Session() as self.tf_session:
self.tf_saver.restore(self.tf_session, self.model_path)
for l in self.layer_nodes:
layers_out.append(l.eval({self.input_data: dataset,
... |
<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_parameters(self, params, graph=None):
"""Get the parameters of the model. :param params: dictionary of keys (str names) and values (tensors). :return: ev... |
g = graph if graph is not None else self.tf_graph
with g.as_default():
with tf.Session() as self.tf_session:
self.tf_saver.restore(self.tf_session, self.model_path)
out = {}
for par in params:
if type(params[par]) == 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 fit(self, train_X, train_Y, val_X=None, val_Y=None, graph=None):
"""Fit the model to the data. Parameters train_X : array_like, shape (n_samples, n_features)... |
if len(train_Y.shape) != 1:
num_classes = train_Y.shape[1]
else:
raise Exception("Please convert the labels with one-hot encoding.")
g = graph if graph is not None else self.tf_graph
with g.as_default():
# Build model
self.build_model(tr... |
<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, test_X):
"""Predict the labels for the test set. Parameters test_X : array_like, shape (n_samples, n_features) Test data. Returns ------- array... |
with self.tf_graph.as_default():
with tf.Session() as self.tf_session:
self.tf_saver.restore(self.tf_session, self.model_path)
feed = {
self.input_data: test_X,
self.keep_prob: 1
}
return self.mo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def score(self, test_X, test_Y):
"""Compute the mean accuracy over the test set. Parameters test_X : array_like, shape (n_samples, n_features) Test data. test_Y ... |
with self.tf_graph.as_default():
with tf.Session() as self.tf_session:
self.tf_saver.restore(self.tf_session, self.model_path)
feed = {
self.input_data: test_X,
self.input_labels: test_Y,
self.keep_prob: 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 pretrain(self, train_set, validation_set=None):
"""Perform Unsupervised pretraining of the autoencoder.""" |
self.do_pretrain = True
def set_params_func(autoenc, autoencgraph):
params = autoenc.get_parameters(graph=autoencgraph)
self.encoding_w_.append(params['enc_w'])
self.encoding_b_.append(params['enc_b'])
return SupervisedModel.pretrain_procedure(
... |
<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_tf_ops(sess):
"""Initialize TensorFlow operations. This function initialize the following tensorflow ops: * init variables ops * summary ops * create mo... |
summary_merged = tf.summary.merge_all()
init_op = tf.global_variables_initializer()
saver = tf.train.Saver()
sess.run(init_op)
# Retrieve run identifier
run_id = 0
for e in os.listdir(Config().logs_dir):
if e[:3] == 'run':
r = int(e[3:])
if r > run_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 run_summaries( sess, merged_summaries, summary_writer, epoch, feed, tens):
"""Run the summaries and error computation on the validation set. Parameters sess ... |
try:
result = sess.run([merged_summaries, tens], feed_dict=feed)
summary_str = result[0]
out = result[1]
summary_writer.add_summary(summary_str, epoch)
except tf.errors.InvalidArgumentError:
out = sess.run(tens, feed_dict=feed)
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 pretrain(self, train_set, validation_set=None):
"""Perform Unsupervised pretraining of the DBN.""" |
self.do_pretrain = True
def set_params_func(rbmmachine, rbmgraph):
params = rbmmachine.get_parameters(graph=rbmgraph)
self.encoding_w_.append(params['W'])
self.encoding_b_.append(params['bh_'])
return SupervisedModel.pretrain_procedure(
self, se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_encode_layer(self):
"""Create the encoding layer of the network. Returns ------- self """ |
with tf.name_scope("encoder"):
activation = tf.add(
tf.matmul(self.input_data, self.W_),
self.bh_
)
if self.enc_act_func:
self.encode = self.enc_act_func(activation)
else:
self.encode = activation
... |
<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_decode_layer(self):
"""Create the decoding layer of the network. Returns ------- self """ |
with tf.name_scope("decoder"):
activation = tf.add(
tf.matmul(self.encode, tf.transpose(self.W_)),
self.bv_
)
if self.dec_act_func:
self.reconstruction = self.dec_act_func(activation)
else:
self.re... |
<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_prob(probs, rand):
"""Get samples from a tensor of probabilities. :param probs: tensor of probabilities :param rand: tensor (of the same shape as prob... |
return tf.nn.relu(tf.sign(probs - rand)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def corrupt_input(data, sess, corrtype, corrfrac):
"""Corrupt a fraction of data according to the chosen noise method. :return: corrupted data """ |
corruption_ratio = np.round(corrfrac * data.shape[1]).astype(np.int)
if corrtype == 'none':
return np.copy(data)
if corrfrac > 0.0:
if corrtype == 'masking':
return masking_noise(data, sess, corrfrac)
elif corrtype == 'salt_and_pepper':
return salt_and_pep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xavier_init(fan_in, fan_out, const=1):
"""Xavier initialization of network weights. https://stackoverflow.com/questions/33640581/how-to-do-xavier-initializat... |
low = -const * np.sqrt(6.0 / (fan_in + fan_out))
high = const * np.sqrt(6.0 / (fan_in + fan_out))
return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_batches(data, batch_size):
"""Divide input data into batches. :param data: input data :param batch_size: size of each batch :return: data divided into ba... |
data = np.array(data)
for i in range(0, data.shape[0], batch_size):
yield data[i:i + batch_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 to_one_hot(dataY):
"""Convert the vector of labels dataY into one-hot encoding. :param dataY: vector of labels :return: one-hot encoded labels """ |
nc = 1 + np.max(dataY)
onehot = [np.zeros(nc, dtype=np.int8) for _ in dataY]
for i, j in enumerate(dataY):
onehot[i][j] = 1
return onehot |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conv2bin(data):
"""Convert a matrix of probabilities into binary values. If the matrix has values <= 0 or >= 1, the values are normalized to be in [0, 1]. :t... |
if data.min() < 0 or data.max() > 1:
data = normalize(data)
out_data = data.copy()
for i, sample in enumerate(out_data):
for j, val in enumerate(sample):
if np.random.random() <= val:
out_data[i][j] = 1
else:
out_data[i][j] = 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 masking_noise(data, sess, v):
"""Apply masking noise to data in X. In other words a fraction v of elements of X (chosen at random) is forced to zero. :param ... |
data_noise = data.copy()
rand = tf.random_uniform(data.shape)
data_noise[sess.run(tf.nn.relu(tf.sign(v - rand))).astype(np.bool)] = 0
return data_noise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def salt_and_pepper_noise(X, v):
"""Apply salt and pepper noise to data in X. In other words a fraction v of elements of X (chosen at random) is set to its maxim... |
X_noise = X.copy()
n_features = X.shape[1]
mn = X.min()
mx = X.max()
for i, sample in enumerate(X):
mask = np.random.randint(0, n_features, v)
for m in mask:
if np.random.random() < 0.5:
X_noise[i][m] = mn
else:
X_noise[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 expand_args(**args_to_expand):
"""Expand the given lists into the length of the layers. This is used as a convenience so that the user does not need to speci... |
layers = args_to_expand['layers']
try:
items = args_to_expand.iteritems()
except AttributeError:
items = args_to_expand.items()
for key, val in items:
if isinstance(val, list) and len(val) != len(layers):
args_to_expand[key] = [val[0] for _ in layers]
return ar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flag_to_list(flagval, flagtype):
"""Convert a string of comma-separated tf flags to a list of values.""" |
if flagtype == 'int':
return [int(_) for _ in flagval.split(',') if _]
elif flagtype == 'float':
return [float(_) for _ in flagval.split(',') if _]
elif flagtype == 'str':
return [_ for _ in flagval.split(',') if _]
else:
raise Exception("incorrect 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 str2actfunc(act_func):
"""Convert activation function name to tf function.""" |
if act_func == 'sigmoid':
return tf.nn.sigmoid
elif act_func == 'tanh':
return tf.nn.tanh
elif act_func == 'relu':
return tf.nn.relu |
<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_seed_np_tf(seed):
"""Seed numpy and tensorflow random number generators. :param seed: seed parameter """ |
if seed >= 0:
np.random.seed(seed)
tf.set_random_seed(seed)
return True
else:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_image(img, width, height, outfile, img_type='grey'):
"""Save an image with the given parameters.""" |
assert len(img) == width * height or len(img) == width * height * 3
if img_type == 'grey':
misc.imsave(outfile, img.reshape(width, height))
elif img_type == 'color':
misc.imsave(outfile, img.reshape(3, width, height)) |
<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_model(self, n_features, n_classes):
"""Create the computational graph of the model. :param n_features: Number of features. :param n_classes: number of ... |
self._create_placeholders(n_features, n_classes)
self._create_layers(n_classes)
self.cost = self.loss.compile(self.mod_y, self.input_labels)
self.train_step = self.trainer.compile(self.cost)
self.accuracy = Evaluation.accuracy(self.mod_y, self.input_labels) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max_pool(x, dim):
"""Max pooling operation.""" |
return tf.nn.max_pool(
x, ksize=[1, dim, dim, 1], strides=[1, dim, dim, 1],
padding='SAME') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reconstruct(self, data, graph=None):
"""Reconstruct data according to the model. Parameters data : array_like, shape (n_samples, n_features) Data to transfor... |
g = graph if graph is not None else self.tf_graph
with g.as_default():
with tf.Session() as self.tf_session:
self.tf_saver.restore(self.tf_session, self.model_path)
feed = {self.input_data: data, self.keep_prob: 1}
return self.reconstruction.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def score(self, data, data_ref, graph=None):
"""Compute the reconstruction loss over the test set. Parameters data : array_like Data to reconstruct. data_ref : a... |
g = graph if graph is not None else self.tf_graph
with g.as_default():
with tf.Session() as self.tf_session:
self.tf_saver.restore(self.tf_session, self.model_path)
feed = {
self.input_data: data,
self.input_labels: da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile(self, cost, name_scope="train"):
"""Compile the optimizer with the given training parameters. Parameters cost : Tensor A Tensor containing the value ... |
with tf.name_scope(name_scope):
return self.opt_.minimize(cost) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile(self, mod_y, ref_y, regterm=None):
"""Compute the loss function tensor. Parameters mode_y : tf.Tensor model output tensor ref_y : tf.Tensor reference... |
with tf.name_scope(self.name):
if self.lfunc == 'cross_entropy':
clip_inf = tf.clip_by_value(mod_y, 1e-10, float('inf'))
clip_sup = tf.clip_by_value(1 - mod_y, 1e-10, float('inf'))
cost = - tf.reduce_mean(tf.add(
tf.multiply(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 build_model(self, n_features, encoding_w=None, encoding_b=None):
"""Create the computational graph for the reconstruction task. :param n_features: Number of ... |
self._create_placeholders(n_features, n_features)
if encoding_w and encoding_b:
self.encoding_w_ = encoding_w
self.encoding_b_ = encoding_b
else:
self._create_variables(n_features)
self._create_encoding_layers()
self._create_decoding_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 _create_feed_dict(self, data):
"""Create the dictionary of data to feed to tf session during training. :param data: training/validation set batch :return: di... |
return {
self.input_data: data,
self.hrand: np.random.rand(data.shape[0], self.num_hidden),
self.vrand: np.random.rand(data.shape[0], data.shape[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 build_model(self, n_features, regtype='none'):
"""Build the Restricted Boltzmann Machine model in TensorFlow. :param n_features: number of features :param re... |
self._create_placeholders(n_features)
self._create_variables(n_features)
self.encode = self.sample_hidden_from_visible(self.input_data)[0]
self.reconstruction = self.sample_visible_from_hidden(
self.encode, n_features)
hprob0, hstate0, vprob, hprob1, hstate1 = 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 gibbs_sampling_step(self, visible, n_features):
"""Perform one step of gibbs sampling. :param visible: activations of the visible units :param n_features: nu... |
hprobs, hstates = self.sample_hidden_from_visible(visible)
vprobs = self.sample_visible_from_hidden(hprobs, n_features)
hprobs1, hstates1 = self.sample_hidden_from_visible(vprobs)
return hprobs, hstates, vprobs, hprobs1, hstates1 |
<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_hidden_from_visible(self, visible):
"""Sample the hidden units from the visible units. This is the Positive phase of the Contrastive Divergence algori... |
hprobs = tf.nn.sigmoid(tf.add(tf.matmul(visible, self.W), self.bh_))
hstates = utilities.sample_prob(hprobs, self.hrand)
return hprobs, hstates |
<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_visible_from_hidden(self, hidden, n_features):
"""Sample the visible units from the hidden units. This is the Negative phase of the Contrastive Diverg... |
visible_activation = tf.add(
tf.matmul(hidden, tf.transpose(self.W)),
self.bv_
)
if self.visible_unit_type == 'bin':
vprobs = tf.nn.sigmoid(visible_activation)
elif self.visible_unit_type == 'gauss':
vprobs = tf.truncated_normal(
... |
<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_positive_association(self, visible, hidden_probs, hidden_states):
"""Compute positive associations between visible and hidden units. :param visible: ... |
if self.visible_unit_type == 'bin':
positive = tf.matmul(tf.transpose(visible), hidden_states)
elif self.visible_unit_type == 'gauss':
positive = tf.matmul(tf.transpose(visible), hidden_probs)
else:
positive = None
return positive |
<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_model(self, shape, gibbs_sampling_steps, model_path):
"""Load a trained model from disk. The shape of the model (num_visible, num_hidden) and the number... |
n_features, self.num_hidden = shape[0], shape[1]
self.gibbs_sampling_steps = gibbs_sampling_steps
self.build_model(n_features)
init_op = tf.global_variables_initializer()
self.tf_saver = tf.train.Saver()
with tf.Session() as self.tf_session:
self.tf_sessi... |
<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_parameters(self, graph=None):
"""Return the model parameters in the form of numpy arrays. :param graph: tf graph object :return: model parameters """ |
g = graph if graph is not None else self.tf_graph
with g.as_default():
with tf.Session() as self.tf_session:
self.tf_saver.restore(self.tf_session, self.model_path)
return {
'W': self.W.eval(),
'bh_': self.bh_.eval(),... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edit_distance(seq1, seq2, action_function=lowest_cost_action, test=operator.eq):
"""Computes the edit distance between the two given sequences. This uses the... |
m = len(seq1)
n = len(seq2)
# Special, easy cases:
if seq1 == seq2:
return 0, n
if m == 0:
return n, 0
if n == 0:
return m, 0
v0 = [0] * (n + 1) # The two 'error' columns
v1 = [0] * (n + 1)
m0 = [0] * (n + 1) # The two 'match' columns
m1 = [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 get_opcodes_from_bp_table(bp):
"""Given a 2d list structure, collect the opcodes from the best path.""" |
x = len(bp) - 1
y = len(bp[0]) - 1
opcodes = []
while x != 0 or y != 0:
this_bp = bp[x][y]
opcodes.append(this_bp)
if this_bp[0] == EQUAL or this_bp[0] == REPLACE:
x = x - 1
y = y - 1
elif this_bp[0] == INSERT:
y = y - 1
elif t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Read two files line-by-line and print edit distances between each pair of lines. Will terminate at the end of the shorter of the two files.""" |
if len(sys.argv) != 3:
print('Usage: {} <file1> <file2>'.format(sys.argv[0]))
exit(-1)
file1 = sys.argv[1]
file2 = sys.argv[2]
with open(file1) as f1, open(file2) as f2:
for line1, line2 in zip(f1, f2):
print("Line 1: {}".format(line1.strip()))
print("L... |
<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(self):
"""Ratio of matches to the average sequence length.""" |
return 2.0 * self.matches() / (len(self.seq1) + len(self.seq2)) |
<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_distance_fast(self):
"""Calls edit_distance, and asserts that if we already have values for matches and distance, that they match.""" |
d, m = edit_distance(self.seq1, self.seq2,
action_function=self.action_function,
test=self.test)
if self.dist:
assert d == self.dist
if self._matches:
assert m == self._matches
self.dist = d
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 newbie(cls, *args, **kwargs):
""" Create a newbie class, with all the skills needed """ |
parser = cls(*args, **kwargs)
subparser = parser.add_subparsers(dest='command')
parents = [parser.pparser, parser.output_parser]
sparser = subparser.add_parser('search', help='Perform new search of items', parents=parents)
""" Adds search arguments to a parser """
parse... |
<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(items=None, printmd=None, printcal=False, found=False, save=None, download=None, requestor_pays=False, **kwargs):
""" Main function for performing a sea... |
if items is None:
## if there are no items then perform a search
search = Search.search(**kwargs)
if found:
num = search.found()
print('%s items found' % num)
return num
items = search.items()
else:
# otherwise, load a search from... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def found(self):
""" Small query to determine total number of hits """ |
if 'ids' in self.kwargs:
cid = self.kwargs['query']['collection']['eq']
return len(self.items_by_id(self.kwargs['ids'], cid))
kwargs = {
'page': 1,
'limit': 0
}
kwargs.update(self.kwargs)
results = self.query(**kwargs)
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collection(cls, cid):
""" Get a Collection record """ |
url = urljoin(config.API_URL, 'collections/%s' % cid)
return Collection(cls.query(url=url)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def items_by_id(cls, ids, collection):
""" Return Items from collection with matching ids """ |
col = cls.collection(collection)
items = []
base_url = urljoin(config.API_URL, 'collections/%s/items' % collection)
for id in ids:
try:
items.append(Item(cls.query(urljoin(base_url, id))))
except SatSearchError as err:
pass
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def items(self, limit=10000):
""" Return all of the Items and Collections for this search """ |
_limit = 500
if 'ids' in self.kwargs:
col = self.kwargs.get('query', {}).get('collection', {}).get('eq', None)
if col is None:
raise SatSearchError('Collection required when searching by id')
return self.items_by_id(self.kwargs['ids'], col)
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 copy_byte_range(infile, outfile, start=None, stop=None, bufsize=16*1024):
'''Like shutil.copyfileobj, but only copy a range of the streams.
Both start and stop are inclusive.
'''
if start is not None: infile.seek(start)
while 1:
to_read = min(bufsize, stop + 1 - infile.tell() if stop el... |
<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_byte_range(byte_range):
'''Returns the two numbers in 'bytes=123-456' or throws ValueError.
The last number or both numbers may be None.
'''
if byte_range.strip() == '':
return None, None
m = BYTE_RANGE_RE.match(byte_range)
if not m:
raise ValueError('Invalid byte ran... |
<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_page(*args, **kwargs):
'''
Same as django's ``cache_page`` decorator, but wraps the view into
additional decorators before and after that. Makes it possible to serve multiple
flavours without getting into trouble with django's caching that doesn't
know about flavours.
'''
decorator... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CheckLineLength(filename, linenumber, clean_lines, errors):
""" Check for lines longer than the recommended length """ |
line = clean_lines.raw_lines[linenumber]
if len(line) > _lint_state.linelength:
return errors(
filename,
linenumber,
'linelength',
'Lines should be <= %d characters long' %
(_lint_state.linelength)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CheckUpperLowerCase(filename, linenumber, clean_lines, errors):
""" Check that commands are either lower case or upper case, but not both """ |
line = clean_lines.lines[linenumber]
if ContainsCommand(line):
command = GetCommand(line)
if IsCommandMixedCase(command):
return errors(
filename,
linenumber,
'readability/wonkycase',
'Do not use mixed 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 CheckCommandSpaces(filename, linenumber, clean_lines, errors):
""" No extra spaces between command and parenthesis """ |
line = clean_lines.lines[linenumber]
match = ContainsCommand(line)
if match and len(match.group(2)):
errors(filename, linenumber, 'whitespace/extra',
"Extra spaces between '%s' and its ()"%(match.group(1)))
if match:
spaces_after_open = len(_RE_COMMAND_START_SPACES.match... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CheckRepeatLogic(filename, linenumber, clean_lines, errors):
""" Check for logic inside else, endif etc """ |
line = clean_lines.lines[linenumber]
for cmd in _logic_commands:
if re.search(r'\b%s\b'%cmd, line.lower()):
m = _RE_LOGIC_CHECK.search(line)
if m:
errors(filename, linenumber, 'readability/logic',
'Expression repeated inside %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 plot_hurst_hist():
""" Plots a histogram of values obtained for the hurst exponent of uniformly distributed white noise. This function requires the package `... |
# local import to avoid dependency for non-debug use
import matplotlib.pyplot as plt
hs = [nolds.hurst_rs(np.random.random(size=10000), corrected=True) for _ in range(100)]
plt.hist(hs, bins=20)
plt.xlabel("esimated value of hurst exponent")
plt.ylabel("number of experiments")
plt.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 hurst_compare_nvals(data, nvals=None):
""" Creates a plot that compares the results of different choices for nvals for the function hurst_rs. Args: data (arr... |
import matplotlib.pyplot as plt
data = np.asarray(data)
n_all = np.arange(2,len(data)+1)
dd_all = nolds.hurst_rs(data, nvals=n_all, debug_data=True, fit="poly")
dd_def = nolds.hurst_rs(data, debug_data=True, fit="poly")
n_def = np.round(np.exp(dd_def[1][0])).astype("int32")
n_div = n_all[np.where(len(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 fbm(n, H=0.75):
""" Generates fractional brownian motions of desired length. Author: Christian Thomae References: .. [fbm_1] https://en.wikipedia.org/wiki/Fr... |
# TODO more detailed description of fbm
assert H > 0 and H < 1
def R(t, s):
twoH = 2 * H
return 0.5 * (s**twoH + t**twoH - np.abs(t - s)**twoH)
# form the matrix tau
gamma = R(*np.mgrid[0:n, 0:n]) # apply R to every element in matrix
w, P = np.linalg.eigh(gamma)
L = np.diag(w)
sigma = np.dot(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qrandom(n):
""" Creates an array of n true random numbers obtained from the quantum random number generator at qrng.anu.edu.au This function requires the pac... |
import quantumrandom
return np.concatenate([
quantumrandom.get_data(data_type='uint16', array_length=1024)
for i in range(int(np.ceil(n/1024.0)))
])[: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 load_qrandom():
""" Loads a set of 10000 random numbers generated by qrandom. This dataset can be used when you want to do some limited tests with "true" ran... |
fname = "datasets/qrandom.npy"
with pkg_resources.resource_stream(__name__, fname) as f:
return np.load(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 load_brown72():
""" Loads the dataset brown72 with a prescribed Hurst exponent of 0.72 Source: http://www.bearcave.com/misl/misl_tech/wavelets/hurst/ Returns... |
fname = "datasets/brown72.npy"
with pkg_resources.resource_stream(__name__, fname) as f:
return np.load(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 tent_map(x, steps, mu=2):
""" Generates a time series of the tent map. Characteristics and Background: The name of the tent map is derived from the fact that... |
for _ in range(steps):
x = mu * x if x < 0.5 else mu * (1 - x)
yield 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 logistic_map(x, steps, r=4):
r""" Generates a time series of the logistic map. Characteristics and Background: The logistic map is among the simplest example... |
for _ in range(steps):
x = r * x * (1 - x)
yield 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 delay_embedding(data, emb_dim, lag=1):
""" Perform a time-delay embedding of a time series Args: data (array-like):
the data that should be embedded emb_dim... |
data = np.asarray(data)
min_len = (emb_dim - 1) * lag + 1
if len(data) < min_len:
msg = "cannot embed data of length {} with embedding dimension {} " \
+ "and lag {}, minimum required length is {}"
raise ValueError(msg.format(len(data), emb_dim, lag, min_len))
m = len(data) - min_len + 1
indi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lyap_r_len(**kwargs):
""" Helper function that calculates the minimum number of data points required to use lyap_r. Note that none of the required parameters... |
# minimum length required to find single orbit vector
min_len = (kwargs['emb_dim'] - 1) * kwargs['lag'] + 1
# we need trajectory_len orbit vectors to follow a complete trajectory
min_len += kwargs['trajectory_len'] - 1
# we need min_tsep * 2 + 1 orbit vectors to find neighbors for each
min_len += 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 lyap_e_len(**kwargs):
""" Helper function that calculates the minimum number of data points required to use lyap_e. Note that none of the required parameters... |
m = (kwargs['emb_dim'] - 1) // (kwargs['matrix_dim'] - 1)
# minimum length required to find single orbit vector
min_len = kwargs['emb_dim']
# we need to follow each starting point of an orbit vector for m more steps
min_len += m
# we need min_tsep * 2 + 1 orbit vectors to find neighbors for each
min_len ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.