_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q232900 | CycleCallback.on_batch_begin | train | def on_batch_begin(self, batch_info: BatchInfo):
""" Set proper learning rate """
cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1]
cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1]
numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch... | python | {
"resource": ""
} |
q232901 | CycleCallback.set_lr | train | def set_lr(self, lr):
""" Set a learning rate for the optimizer """
if isinstance(lr, list):
for group_lr, param_group in zip(lr, self.optimizer.param_groups):
param_group['lr'] = group_lr
else:
for param_group in self.optimizer.param_groups:
... | python | {
"resource": ""
} |
q232902 | Variable.parameter_constructor | train | def parameter_constructor(cls, loader, node):
""" Construct variable instance from yaml node """
value = loader.construct_scalar(node)
if isinstance(value, str):
if '=' in value:
(varname, varvalue) = Parser.parse_equality(value)
return cls(varname, v... | python | {
"resource": ""
} |
q232903 | Parser.register | train | def register(cls):
""" Register variable handling in YAML """
if not cls.IS_LOADED:
cls.IS_LOADED = True
yaml.add_constructor('!param', Parameter.parameter_constructor, Loader=yaml.SafeLoader)
yaml.add_constructor('!env', EnvironmentVariable.parameter_constructor, Lo... | python | {
"resource": ""
} |
q232904 | Parser.parse_equality | train | def parse_equality(cls, equality_string):
""" Parse some simple equality statements """
cls.register()
assert '=' in equality_string, "There must be an '=' sign in the equality"
[left_side, right_side] = equality_string.split('=', 1)
left_side_value = yaml.safe_load(left_side.st... | python | {
"resource": ""
} |
q232905 | MongoDbBackend.clean | train | def clean(self, initial_epoch):
""" Remove entries from database that would get overwritten """
self.db.metrics.delete_many({'run_name': self.model_config.run_name, 'epoch_idx': {'$gt': initial_epoch}}) | python | {
"resource": ""
} |
q232906 | MongoDbBackend.store_config | train | def store_config(self, configuration):
""" Store model parameters in the database """
run_name = self.model_config.run_name
self.db.configs.delete_many({'run_name': self.model_config.run_name})
configuration = configuration.copy()
configuration['run_name'] = run_name
s... | python | {
"resource": ""
} |
q232907 | MongoDbBackend.get_frame | train | def get_frame(self):
""" Get a dataframe of metrics from this storage """
metric_items = list(self.db.metrics.find({'run_name': self.model_config.run_name}).sort('epoch_idx'))
if len(metric_items) == 0:
return pd.DataFrame(columns=['run_name'])
else:
return pd.Dat... | python | {
"resource": ""
} |
q232908 | PrioritizedCircularReplayBuffer._get_transitions | train | def _get_transitions(self, probs, indexes, tree_idxs, batch_info, forward_steps=1, discount_factor=1.0):
""" Return batch of frames for given indexes """
if forward_steps > 1:
transition_arrays = self.backend.get_transitions_forward_steps(indexes, forward_steps, discount_factor)
else... | python | {
"resource": ""
} |
q232909 | EnvRollerBase.rollout | train | def rollout(self, batch_info: BatchInfo, model: Model, number_of_steps: int) -> Rollout:
""" Roll-out the environment and return it """
raise NotImplementedError | python | {
"resource": ""
} |
q232910 | BufferedMixedPolicyIterationReinforcer.train_epoch | train | def train_epoch(self, epoch_info: EpochInfo, interactive=True):
""" Train model on an epoch of a fixed number of batch updates """
epoch_info.on_epoch_begin()
if interactive:
iterator = tqdm.trange(epoch_info.batches_per_epoch, file=sys.stdout, desc="Training", unit="batch")
... | python | {
"resource": ""
} |
q232911 | BufferedMixedPolicyIterationReinforcer.train_batch | train | def train_batch(self, batch_info: BatchInfo):
""" Single, most atomic 'step' of learning this reinforcer can perform """
batch_info['sub_batch_data'] = []
self.on_policy_train_batch(batch_info)
if self.settings.experience_replay > 0 and self.env_roller.is_ready_for_sampling():
... | python | {
"resource": ""
} |
q232912 | BufferedMixedPolicyIterationReinforcer.on_policy_train_batch | train | def on_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'on-policy' training step of evaluating an env and a single backpropagation step """
self.model.train()
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
... | python | {
"resource": ""
} |
q232913 | BufferedMixedPolicyIterationReinforcer.off_policy_train_batch | train | def off_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'off-policy' training step of sampling the replay buffer and gradient descent """
self.model.train()
rollout = self.env_roller.sample(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
ba... | python | {
"resource": ""
} |
q232914 | ClassicCheckpointStrategy.should_store_best_checkpoint | train | def should_store_best_checkpoint(self, epoch_idx, metrics) -> bool:
""" Should we store current checkpoint as the best """
if not self.store_best:
return False
metric = metrics[self.metric]
if better(self._current_best_metric_value, metric, self.metric_mode):
se... | python | {
"resource": ""
} |
q232915 | create | train | def create(model_config, batch_size, vectors=None):
""" Create an IMDB dataset """
path = model_config.data_dir('imdb')
text_field = data.Field(lower=True, tokenize='spacy', batch_first=True)
label_field = data.LabelField(is_target=True)
train_source, test_source = IMDBCached.splits(
root=... | python | {
"resource": ""
} |
q232916 | AugmentationVisualizationCommand.run | train | def run(self):
""" Run the visualization """
dataset = self.source.train_dataset()
num_samples = len(dataset)
fig, ax = plt.subplots(self.cases, self.samples+1)
selected_sample = np.sort(np.random.choice(num_samples, self.cases, replace=False))
for i in range(self.case... | python | {
"resource": ""
} |
q232917 | env_maker | train | def env_maker(environment_id, seed, serial_id, monitor=False, allow_early_resets=False):
""" Create a classic control environment with basic set of wrappers """
env = gym.make(environment_id)
env.seed(seed + serial_id)
# Monitoring the env
if monitor:
logdir = logger.get_dir() and os.path.j... | python | {
"resource": ""
} |
q232918 | Resnet34.freeze | train | def freeze(self, number=None):
""" Freeze given number of layers in the model """
if number is None:
number = self.head_layers
for idx, child in enumerate(self.model.children()):
if idx < number:
mu.freeze_layer(child) | python | {
"resource": ""
} |
q232919 | Resnet34.unfreeze | train | def unfreeze(self):
""" Unfreeze model layers """
for idx, child in enumerate(self.model.children()):
mu.unfreeze_layer(child) | python | {
"resource": ""
} |
q232920 | AcerPolicyGradient.update_average_model | train | def update_average_model(self, model):
""" Update weights of the average model with new model observation """
for model_param, average_param in zip(model.parameters(), self.average_model.parameters()):
# EWMA average model update
average_param.data.mul_(self.average_model_alpha).... | python | {
"resource": ""
} |
q232921 | AcerPolicyGradient.retrace | train | def retrace(self, rewards, dones, q_values, state_values, rho, final_values):
""" Calculate Q retraced targets """
rho_bar = torch.min(torch.ones_like(rho) * self.retrace_rho_cap, rho)
q_retraced_buffer = torch.zeros_like(rewards)
next_value = final_values
for i in reversed(ra... | python | {
"resource": ""
} |
q232922 | DiagGaussianActionHead.logprob | train | def logprob(self, action_sample, pd_params):
""" Log-likelihood """
means = pd_params[:, :, 0]
log_std = pd_params[:, :, 1]
std = torch.exp(log_std)
z_score = (action_sample - means) / std
return - (0.5 * ((z_score**2 + self.LOG2PI).sum(dim=-1)) + log_std.sum(dim=-1)) | python | {
"resource": ""
} |
q232923 | CategoricalActionHead.logprob | train | def logprob(self, actions, action_logits):
""" Logarithm of probability of given sample """
neg_log_prob = F.nll_loss(action_logits, actions, reduction='none')
return -neg_log_prob | python | {
"resource": ""
} |
q232924 | Accuracy._value_function | train | def _value_function(self, x_input, y_true, y_pred):
""" Return classification accuracy of input """
if len(y_true.shape) == 1:
return y_pred.argmax(1).eq(y_true).double().mean().item()
else:
raise NotImplementedError | python | {
"resource": ""
} |
q232925 | VisdomStreaming.on_epoch_end | train | def on_epoch_end(self, epoch_info):
""" Update data in visdom on push """
metrics_df = pd.DataFrame([epoch_info.result]).set_index('epoch_idx')
visdom_append_metrics(
self.vis,
metrics_df,
first_epoch=epoch_info.global_epoch_idx == 1
) | python | {
"resource": ""
} |
q232926 | VisdomStreaming.on_batch_end | train | def on_batch_end(self, batch_info):
""" Stream LR to visdom """
if self.settings.stream_lr:
iteration_idx = (
float(batch_info.epoch_number) +
float(batch_info.batch_number) / batch_info.batches_per_epoch
)
lr = bat... | python | {
"resource": ""
} |
q232927 | main | train | def main():
""" Paperboy entry point - parse the arguments and run a command """
parser = argparse.ArgumentParser(description='Paperboy deep learning launcher')
parser.add_argument('config', metavar='FILENAME', help='Configuration file for the run')
parser.add_argument('command', metavar='COMMAND', hel... | python | {
"resource": ""
} |
q232928 | set_seed | train | def set_seed(seed: int):
""" Set random seed for python, numpy and pytorch RNGs """
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed) | python | {
"resource": ""
} |
q232929 | better | train | def better(old_value, new_value, mode):
""" Check if new value is better than the old value"""
if (old_value is None or np.isnan(old_value)) and (new_value is not None and not np.isnan(new_value)):
return True
if mode == 'min':
return new_value < old_value
elif mode == 'max':
re... | python | {
"resource": ""
} |
q232930 | DeterministicCriticHead.reset_weights | train | def reset_weights(self):
""" Initialize weights to sane defaults """
init.uniform_(self.linear.weight, -3e-3, 3e-3)
init.zeros_(self.linear.bias) | python | {
"resource": ""
} |
q232931 | discount_bootstrap | train | def discount_bootstrap(rewards_buffer, dones_buffer, final_values, discount_factor, number_of_steps):
""" Calculate state values bootstrapping off the following state values """
true_value_buffer = torch.zeros_like(rewards_buffer)
# discount/bootstrap off value fn
current_value = final_values
for ... | python | {
"resource": ""
} |
q232932 | ModelConfig.find_project_directory | train | def find_project_directory(start_path) -> str:
""" Locate top-level project directory """
start_path = os.path.realpath(start_path)
possible_name = os.path.join(start_path, ModelConfig.PROJECT_FILE_NAME)
if os.path.exists(possible_name):
return start_path
else:
... | python | {
"resource": ""
} |
q232933 | ModelConfig.from_file | train | def from_file(cls, filename: str, run_number: int, continue_training: bool = False, seed: int = None,
device: str = 'cuda', params=None):
""" Create model config from file """
with open(filename, 'r') as fp:
model_config_contents = Parser.parse(fp)
project_config_p... | python | {
"resource": ""
} |
q232934 | ModelConfig.from_memory | train | def from_memory(cls, model_data: dict, run_number: int, project_dir: str,
continue_training=False, seed: int = None, device: str = 'cuda', params=None):
""" Create model config from supplied data """
return ModelConfig(
filename="[memory]",
configuration=model... | python | {
"resource": ""
} |
q232935 | ModelConfig.run_command | train | def run_command(self, command_name, varargs):
""" Instantiate model class """
command_descriptor = self.get_command(command_name)
return command_descriptor.run(*varargs) | python | {
"resource": ""
} |
q232936 | ModelConfig.project_data_dir | train | def project_data_dir(self, *args) -> str:
""" Directory where to store data """
return os.path.normpath(os.path.join(self.project_dir, 'data', *args)) | python | {
"resource": ""
} |
q232937 | ModelConfig.output_dir | train | def output_dir(self, *args) -> str:
""" Directory where to store output """
return os.path.join(self.project_dir, 'output', *args) | python | {
"resource": ""
} |
q232938 | ModelConfig.project_top_dir | train | def project_top_dir(self, *args) -> str:
""" Project top-level directory """
return os.path.join(self.project_dir, *args) | python | {
"resource": ""
} |
q232939 | ModelConfig.provide_with_default | train | def provide_with_default(self, name, default=None):
""" Return a dependency-injected instance """
return self.provider.instantiate_by_name_with_default(name, default_value=default) | python | {
"resource": ""
} |
q232940 | benchmark_method | train | def benchmark_method(f):
"decorator to turn f into a factory of benchmarks"
@wraps(f)
def inner(name, *args, **kwargs):
return Benchmark(name, f, args, kwargs)
return inner | python | {
"resource": ""
} |
q232941 | bench | train | def bench(participants=participants, benchmarks=benchmarks,
bench_time=BENCH_TIME):
"""Do you even lift?"""
mcs = [p.factory() for p in participants]
means = [[] for p in participants]
stddevs = [[] for p in participants]
# Have each lifter do one benchmark each
last_fn = None
fo... | python | {
"resource": ""
} |
q232942 | BaseResource.strip_datetime | train | def strip_datetime(value):
"""
Converts value to datetime if string or int.
"""
if isinstance(value, basestring):
try:
return parse_datetime(value)
except ValueError:
return
elif isinstance(value, integer_types):
... | python | {
"resource": ""
} |
q232943 | BaseClient.set_session_token | train | def set_session_token(self, session_token):
"""
Sets session token and new login time.
:param str session_token: Session token from request.
"""
self.session_token = session_token
self._login_time = datetime.datetime.now() | python | {
"resource": ""
} |
q232944 | BaseClient.get_password | train | def get_password(self):
"""
If password is not provided will look in environment variables
for username+'password'.
"""
if self.password is None:
if os.environ.get(self.username+'password'):
self.password = os.environ.get(self.username+'password')
... | python | {
"resource": ""
} |
q232945 | BaseClient.get_app_key | train | def get_app_key(self):
"""
If app_key is not provided will look in environment
variables for username.
"""
if self.app_key is None:
if os.environ.get(self.username):
self.app_key = os.environ.get(self.username)
else:
raise A... | python | {
"resource": ""
} |
q232946 | BaseClient.session_expired | train | def session_expired(self):
"""
Returns True if login_time not set or seconds since
login time is greater than 200 mins.
"""
if not self._login_time or (datetime.datetime.now()-self._login_time).total_seconds() > 12000:
return True | python | {
"resource": ""
} |
q232947 | check_status_code | train | def check_status_code(response, codes=None):
"""
Checks response.status_code is in codes.
:param requests.request response: Requests response
:param list codes: List of accepted codes or callable
:raises: StatusCodeError if code invalid
"""
codes = codes or [200]
if response.status_code... | python | {
"resource": ""
} |
q232948 | Betting.list_runner_book | train | def list_runner_book(self, market_id, selection_id, handicap=None, price_projection=None, order_projection=None,
match_projection=None, include_overall_position=None, partition_matched_by_strategy_ref=None,
customer_strategy_refs=None, currency_code=None, matched_since=... | python | {
"resource": ""
} |
q232949 | Betting.list_current_orders | train | def list_current_orders(self, bet_ids=None, market_ids=None, order_projection=None, customer_order_refs=None,
customer_strategy_refs=None, date_range=time_range(), order_by=None, sort_dir=None,
from_record=None, record_count=None, session=None, lightweight=None):
... | python | {
"resource": ""
} |
q232950 | Betting.list_cleared_orders | train | def list_cleared_orders(self, bet_status='SETTLED', event_type_ids=None, event_ids=None, market_ids=None,
runner_ids=None, bet_ids=None, customer_order_refs=None, customer_strategy_refs=None,
side=None, settled_date_range=time_range(), group_by=None, include_item_... | python | {
"resource": ""
} |
q232951 | Betting.list_market_profit_and_loss | train | def list_market_profit_and_loss(self, market_ids, include_settled_bets=None, include_bsp_bets=None,
net_of_commission=None, session=None, lightweight=None):
"""
Retrieve profit and loss for a given list of OPEN markets.
:param list market_ids: List of markets... | python | {
"resource": ""
} |
q232952 | Betting.place_orders | train | def place_orders(self, market_id, instructions, customer_ref=None, market_version=None,
customer_strategy_ref=None, async_=None, session=None, lightweight=None):
"""
Place new orders into market.
:param str market_id: The market id these orders are to be placed on
:... | python | {
"resource": ""
} |
q232953 | MarketBookCache.serialise | train | def serialise(self):
"""Creates standard market book json response,
will error if EX_MARKET_DEF not incl.
"""
return {
'marketId': self.market_id,
'totalAvailable': None,
'isMarketDataDelayed': None,
'lastMatchTime': None,
'betD... | python | {
"resource": ""
} |
q232954 | Scores.list_race_details | train | def list_race_details(self, meeting_ids=None, race_ids=None, session=None, lightweight=None):
"""
Search for races to get their details.
:param dict meeting_ids: Optionally restricts the results to the specified meeting IDs.
The unique Id for the meeting equivalent to the eventId for th... | python | {
"resource": ""
} |
q232955 | Scores.list_available_events | train | def list_available_events(self, event_ids=None, event_type_ids=None, event_status=None, session=None,
lightweight=None):
"""
Search for events that have live score data available.
:param list event_ids: Optionally restricts the results to the specified event IDs
... | python | {
"resource": ""
} |
q232956 | Scores.list_scores | train | def list_scores(self, update_keys, session=None, lightweight=None):
"""
Returns a list of current scores for the given events.
:param list update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'las... | python | {
"resource": ""
} |
q232957 | Scores.list_incidents | train | def list_incidents(self, update_keys, session=None, lightweight=None):
"""
Returns a list of incidents for the given events.
:param dict update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastU... | python | {
"resource": ""
} |
q232958 | InPlayService.get_event_timeline | train | def get_event_timeline(self, event_id, session=None, lightweight=None):
"""
Returns event timeline for event id provided.
:param int event_id: Event id to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a reso... | python | {
"resource": ""
} |
q232959 | InPlayService.get_event_timelines | train | def get_event_timelines(self, event_ids, session=None, lightweight=None):
"""
Returns a list of event timelines based on event id's
supplied.
:param list event_ids: List of event id's to return
:param requests.session session: Requests session object
:param bool lightwei... | python | {
"resource": ""
} |
q232960 | InPlayService.get_scores | train | def get_scores(self, event_ids, session=None, lightweight=None):
"""
Returns a list of scores based on event id's
supplied.
:param list event_ids: List of event id's to return
:param requests.session session: Requests session object
:param bool lightweight: If True will ... | python | {
"resource": ""
} |
q232961 | Streaming.create_stream | train | def create_stream(self, unique_id=0, listener=None, timeout=11, buffer_size=1024, description='BetfairSocket',
host=None):
"""
Creates BetfairStream.
:param dict unique_id: Id used to start unique id's of the stream (+1 before every request)
:param resources.Listen... | python | {
"resource": ""
} |
q232962 | Historic.get_my_data | train | def get_my_data(self, session=None):
"""
Returns a list of data descriptions for data which has been purchased by the signed in user.
:param requests.session session: Requests session object
:rtype: dict
"""
params = clean_locals(locals())
method = 'GetMyData'
... | python | {
"resource": ""
} |
q232963 | Historic.get_data_size | train | def get_data_size(self, sport, plan, from_day, from_month, from_year, to_day, to_month, to_year, event_id=None,
event_name=None, market_types_collection=None, countries_collection=None,
file_type_collection=None, session=None):
"""
Returns a dictionary of file... | python | {
"resource": ""
} |
q232964 | RaceCard.login | train | def login(self, session=None):
"""
Parses app key from betfair exchange site.
:param requests.session session: Requests session object
"""
session = session or self.client.session
try:
response = session.get(self.login_url)
except ConnectionError:
... | python | {
"resource": ""
} |
q232965 | RaceCard.get_race_card | train | def get_race_card(self, market_ids, data_entries=None, session=None, lightweight=None):
"""
Returns a list of race cards based on market ids provided.
:param list market_ids: The filter to select desired markets
:param str data_entries: Data to be returned
:param requests.sessio... | python | {
"resource": ""
} |
q232966 | StreamListener.on_data | train | def on_data(self, raw_data):
"""Called when raw data is received from connection.
Override this method if you wish to manually handle
the stream data
:param raw_data: Received raw data
:return: Return False to stop stream and close connection
"""
try:
... | python | {
"resource": ""
} |
q232967 | StreamListener._on_connection | train | def _on_connection(self, data, unique_id):
"""Called on collection operation
:param data: Received data
"""
if unique_id is None:
unique_id = self.stream_unique_id
self.connection_id = data.get('connectionId')
logger.info('[Connect: %s]: connection_id: %s' % ... | python | {
"resource": ""
} |
q232968 | StreamListener._on_status | train | def _on_status(data, unique_id):
"""Called on status operation
:param data: Received data
"""
status_code = data.get('statusCode')
logger.info('[Subscription: %s]: %s' % (unique_id, status_code)) | python | {
"resource": ""
} |
q232969 | StreamListener._error_handler | train | def _error_handler(data, unique_id):
"""Called when data first received
:param data: Received data
:param unique_id: Unique id
:return: True if error present
"""
if data.get('statusCode') == 'FAILURE':
logger.error('[Subscription: %s] %s: %s' % (unique_id, da... | python | {
"resource": ""
} |
q232970 | BetfairStream.stop | train | def stop(self):
"""Stops read loop and closes socket if it has been created.
"""
self._running = False
if self._socket is None:
return
try:
self._socket.shutdown(socket.SHUT_RDWR)
self._socket.close()
except socket.error:
p... | python | {
"resource": ""
} |
q232971 | BetfairStream.authenticate | train | def authenticate(self):
"""Authentication request.
"""
unique_id = self.new_unique_id()
message = {
'op': 'authentication',
'id': unique_id,
'appKey': self.app_key,
'session': self.session_token,
}
self._send(message)
... | python | {
"resource": ""
} |
q232972 | BetfairStream.heartbeat | train | def heartbeat(self):
"""Heartbeat request to keep session alive.
"""
unique_id = self.new_unique_id()
message = {
'op': 'heartbeat',
'id': unique_id,
}
self._send(message)
return unique_id | python | {
"resource": ""
} |
q232973 | BetfairStream.subscribe_to_markets | train | def subscribe_to_markets(self, market_filter, market_data_filter, initial_clk=None, clk=None,
conflate_ms=None, heartbeat_ms=None, segmentation_enabled=True):
"""
Market subscription request.
:param dict market_filter: Market filter
:param dict market_data_f... | python | {
"resource": ""
} |
q232974 | BetfairStream.subscribe_to_orders | train | def subscribe_to_orders(self, order_filter=None, initial_clk=None, clk=None, conflate_ms=None,
heartbeat_ms=None, segmentation_enabled=True):
"""
Order subscription request.
:param dict order_filter: Order filter to be applied
:param str initial_clk: Sequence... | python | {
"resource": ""
} |
q232975 | BetfairStream._create_socket | train | def _create_socket(self):
"""Creates ssl socket, connects to stream api and
sets timeout.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(s)
s.connect((self.host, self.__port))
s.settimeout(self.timeout)
return s | python | {
"resource": ""
} |
q232976 | BetfairStream._read_loop | train | def _read_loop(self):
"""Read loop, splits by CRLF and pushes received data
to _data.
"""
while self._running:
received_data_raw = self._receive_all()
if self._running:
self.receive_count += 1
self.datetime_last_received = datetime.... | python | {
"resource": ""
} |
q232977 | BetfairStream._receive_all | train | def _receive_all(self):
"""Whilst socket is running receives data from socket,
till CRLF is detected.
"""
(data, part) = ('', '')
if is_py3:
crlf_bytes = bytes(self.__CRLF, encoding=self.__encoding)
else:
crlf_bytes = self.__CRLF
while sel... | python | {
"resource": ""
} |
q232978 | BetfairStream._data | train | def _data(self, received_data):
"""Sends data to listener, if False is returned; socket
is closed.
:param received_data: Decoded data received from socket.
"""
if self.listener.on_data(received_data) is False:
self.stop()
raise ListenerError(self.listener... | python | {
"resource": ""
} |
q232979 | BetfairStream._send | train | def _send(self, message):
"""If not running connects socket and
authenticates. Adds CRLF and sends message
to Betfair.
:param message: Data to be sent to Betfair.
"""
if not self._running:
self._connect()
self.authenticate()
message_dumped... | python | {
"resource": ""
} |
q232980 | Pype.fit_transform | train | def fit_transform(self, X, y=None, **fit_params):
"""
Fit the model and transform with the final estimator
Fits all the transforms one after the other and transforms the
data, then uses fit_transform on transformed data with the final
estimator.
Parameters
------... | python | {
"resource": ""
} |
q232981 | Pype.predict | train | def predict(self, X):
"""
Apply transforms to the data, and predict with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
yp ... | python | {
"resource": ""
} |
q232982 | Pype.transform_predict | train | def transform_predict(self, X, y):
"""
Apply transforms to the data, and predict with the final estimator.
Unlike predict, this also returns the transformed target
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first... | python | {
"resource": ""
} |
q232983 | Pype.score | train | def score(self, X, y=None, sample_weight=None):
"""
Apply transforms, and score with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : iterable, default=No... | python | {
"resource": ""
} |
q232984 | Pype.predict_proba | train | def predict_proba(self, X):
"""
Apply transforms, and predict_proba of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
y_pro... | python | {
"resource": ""
} |
q232985 | Pype.decision_function | train | def decision_function(self, X):
"""
Apply transforms, and decision_function of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
... | python | {
"resource": ""
} |
q232986 | Pype.predict_log_proba | train | def predict_log_proba(self, X):
"""
Apply transforms, and predict_log_proba of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
... | python | {
"resource": ""
} |
q232987 | base_features | train | def base_features():
''' Returns dictionary of some basic features that can be calculated for segmented time
series data '''
features = {'mean': mean,
'median': median,
'abs_energy': abs_energy,
'std': std,
'var': var,
'min': mi... | python | {
"resource": ""
} |
q232988 | all_features | train | def all_features():
''' Returns dictionary of all features in the module
.. note:: Some of the features (hist4, corr) are relatively expensive to compute
'''
features = {'mean': mean,
'median': median,
'gmean': gmean,
'hmean': hmean,
'vec_... | python | {
"resource": ""
} |
q232989 | emg_features | train | def emg_features(threshold=0):
'''Return a dictionary of popular features used for EMG time series classification.'''
return {
'mean_abs_value': mean_abs,
'zero_crossings': zero_crossing(threshold),
'slope_sign_changes': slope_sign_changes(threshold),
'waveform_length': waveform_... | python | {
"resource": ""
} |
q232990 | means_abs_diff | train | def means_abs_diff(X):
''' mean absolute temporal derivative '''
return np.mean(np.abs(np.diff(X, axis=1)), axis=1) | python | {
"resource": ""
} |
q232991 | mse | train | def mse(X):
''' computes mean spectral energy for each variable in a segmented time series '''
return np.mean(np.square(np.abs(np.fft.fft(X, axis=1))), axis=1) | python | {
"resource": ""
} |
q232992 | mean_crossings | train | def mean_crossings(X):
''' Computes number of mean crossings for each variable in a segmented time series '''
X = np.atleast_3d(X)
N = X.shape[0]
D = X.shape[2]
mnx = np.zeros((N, D))
for i in range(D):
pos = X[:, :, i] > 0
npos = ~pos
c = (pos[:, :-1] & npos[:, 1:]) | (n... | python | {
"resource": ""
} |
q232993 | corr2 | train | def corr2(X):
''' computes correlations between all variable pairs in a segmented time series
.. note:: this feature is expensive to compute with the current implementation, and cannot be
used with univariate time series
'''
X = np.atleast_3d(X)
N = X.shape[0]
D = X.shape[2]
if D == 1:... | python | {
"resource": ""
} |
q232994 | waveform_length | train | def waveform_length(X):
''' cumulative length of the waveform over a segment for each variable in the segmented time
series '''
return np.sum(np.abs(np.diff(X, axis=1)), axis=1) | python | {
"resource": ""
} |
q232995 | root_mean_square | train | def root_mean_square(X):
''' root mean square for each variable in the segmented time series '''
segment_width = X.shape[1]
return np.sqrt(np.sum(X * X, axis=1) / segment_width) | python | {
"resource": ""
} |
q232996 | TemporalKFold.split | train | def split(self, X, y):
'''
Splits time series data and target arrays, and generates splitting indices
Parameters
----------
X : array-like, shape [n_series, ...]
Time series data and (optionally) contextual data
y : array-like shape [n_series, ]
ta... | python | {
"resource": ""
} |
q232997 | TemporalKFold._ts_slice | train | def _ts_slice(self, Xt, y):
''' takes time series data, and splits each series into temporal folds '''
Ns = len(Xt)
Xt_new = []
for i in range(self.n_splits):
for j in range(Ns):
Njs = int(len(Xt[j]) / self.n_splits)
Xt_new.append(Xt[j][(Njs * ... | python | {
"resource": ""
} |
q232998 | TemporalKFold._make_indices | train | def _make_indices(self, Ns):
''' makes indices for cross validation '''
N_new = int(Ns * self.n_splits)
test = [np.full(N_new, False) for i in range(self.n_splits)]
for i in range(self.n_splits):
test[i][np.arange(Ns * i, Ns * (i + 1))] = True
train = [np.logical_not... | python | {
"resource": ""
} |
q232999 | TargetRunLengthEncoder.transform | train | def transform(self, X, y, sample_weight=None):
'''
Transforms the time series data with run length encoding of the target variable
Note this transformation changes the number of samples in the data
If sample_weight is provided, it is transformed to align to the new target encoding
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.