code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _initialize_affine_weight(weight, output_size, input_size,
per_partition_size, partition_dim, init_method,
stride=1, return_master_weight=False):
"""Initialize affine weight for model parallel.
Build the master weight on all processes and scatter
... | Initialize affine weight for model parallel.
Build the master weight on all processes and scatter
the relevant chunk. | _initialize_affine_weight | python | THUDM/GLM | mpu/layers.py | https://github.com/THUDM/GLM/blob/master/mpu/layers.py | MIT |
def _reduce(input_):
"""All-reduce the the input tensor across model parallel group."""
group = get_model_parallel_group()
# Bypass the function if we are using only 1 GPU.
if torch.distributed.get_world_size(group=group) == 1:
return input_
# All-reduce.
torch.distributed.all_reduce(i... | All-reduce the the input tensor across model parallel group. | _reduce | python | THUDM/GLM | mpu/mappings.py | https://github.com/THUDM/GLM/blob/master/mpu/mappings.py | MIT |
def _split(input_):
"""Split the tensor along its last dimension and keep the
corresponding slice."""
group = get_model_parallel_group()
# Bypass the function if we are using only 1 GPU.
if torch.distributed.get_world_size(group=group) == 1:
return input_
# Split along last dimension.
... | Split the tensor along its last dimension and keep the
corresponding slice. | _split | python | THUDM/GLM | mpu/mappings.py | https://github.com/THUDM/GLM/blob/master/mpu/mappings.py | MIT |
def _gather(input_):
"""Gather tensors and concatinate along the last dimension."""
group = get_model_parallel_group()
# Bypass the function if we are using only 1 GPU.
if torch.distributed.get_world_size(group=group) == 1:
return input_
# Size and dimension.
last_dim = input_.dim() - ... | Gather tensors and concatinate along the last dimension. | _gather | python | THUDM/GLM | mpu/mappings.py | https://github.com/THUDM/GLM/blob/master/mpu/mappings.py | MIT |
def _set_cuda_rng_state(new_state, device=-1):
"""Sets the random number generator state of the current GPU.
Argumentss:
new_state (torch.ByteTensor): The desired state
This function is adapted from PyTorch repo (torch.cuda.set_rng_state)
with a single change: the input state is not cloned. Clo... | Sets the random number generator state of the current GPU.
Argumentss:
new_state (torch.ByteTensor): The desired state
This function is adapted from PyTorch repo (torch.cuda.set_rng_state)
with a single change: the input state is not cloned. Cloning caused
major performance issues for +4 GPU ca... | _set_cuda_rng_state | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def reset(self):
"""Set to the initial state (no tracker)."""
self.states_ = {}
self.seeds_ = set() | Set to the initial state (no tracker). | reset | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def get_states(self):
"""Get rng states. Copy the dictionary so we have direct
pointers to the states, not just a pointer to the dictionary."""
states = {}
for name in self.states_:
states[name] = self.states_[name]
return states | Get rng states. Copy the dictionary so we have direct
pointers to the states, not just a pointer to the dictionary. | get_states | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def fork(self, name=_MODEL_PARALLEL_RNG_TRACKER_NAME):
"""Fork the cuda rng state, perform operations, and exit with
the original state."""
# Check if we have added the state
if name not in self.states_:
raise Exception('cuda rng state {} is not added'.format(name))
#... | Fork the cuda rng state, perform operations, and exit with
the original state. | fork | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def model_parallel_cuda_manual_seed(seed):
"""Initialize model parallel cuda seed.
This function should be called after the model parallel is
initialized. Also, no torch.cuda.manual_seed should be called
after this function. Basically, this is replacement for that
function.
Two set of RNG state... | Initialize model parallel cuda seed.
This function should be called after the model parallel is
initialized. Also, no torch.cuda.manual_seed should be called
after this function. Basically, this is replacement for that
function.
Two set of RNG states are tracked:
default state: This is for ... | model_parallel_cuda_manual_seed | python | THUDM/GLM | mpu/random.py | https://github.com/THUDM/GLM/blob/master/mpu/random.py | MIT |
def _transpose_for_scores(self, tensor):
"""Transpose a 3D tensor [b, s, np*hn] into a 4D tensor with
size [b, np, s, hn].
"""
new_tensor_shape = tensor.size()[:-1] + \
(self.num_attention_heads_per_partition,
self.hidden_size_per_at... | Transpose a 3D tensor [b, s, np*hn] into a 4D tensor with
size [b, np, s, hn].
| _transpose_for_scores | python | THUDM/GLM | mpu/transformer.py | https://github.com/THUDM/GLM/blob/master/mpu/transformer.py | MIT |
def _transpose_for_scores(self, tensor):
"""Transpose a 3D tensor [b, s, np*hn] into a 4D tensor with
size [b, np, s, hn].
"""
new_tensor_shape = tensor.size()[:-1] + \
(self.num_attention_heads_per_partition,
self.hidden_size_per_at... | Transpose a 3D tensor [b, s, np*hn] into a 4D tensor with
size [b, np, s, hn].
| _transpose_for_scores | python | THUDM/GLM | mpu/transformer.py | https://github.com/THUDM/GLM/blob/master/mpu/transformer.py | MIT |
def scaled_init_method(sigma, num_layers):
"""Init method based on N(0, sigma/sqrt(2*num_layers)."""
std = sigma / math.sqrt(2.0 * num_layers)
def init_(tensor):
return torch.nn.init.normal_(tensor, mean=0.0, std=std)
return init_ | Init method based on N(0, sigma/sqrt(2*num_layers). | scaled_init_method | python | THUDM/GLM | mpu/transformer.py | https://github.com/THUDM/GLM/blob/master/mpu/transformer.py | MIT |
def divide(numerator, denominator):
"""Ensure that numerator is divisible by the denominator and return
the division value."""
ensure_divisibility(numerator, denominator)
return numerator // denominator | Ensure that numerator is divisible by the denominator and return
the division value. | divide | python | THUDM/GLM | mpu/utils.py | https://github.com/THUDM/GLM/blob/master/mpu/utils.py | MIT |
def split_tensor_along_last_dim(tensor, num_partitions,
contiguous_split_chunks=False):
"""Split a tensor along its last dimension.
Arguments:
tensor: input tensor.
num_partitions: number of partitions to split the tensor
contiguous_split_chunks: If True, ... | Split a tensor along its last dimension.
Arguments:
tensor: input tensor.
num_partitions: number of partitions to split the tensor
contiguous_split_chunks: If True, make each chunk contiguous
in memory.
| split_tensor_along_last_dim | python | THUDM/GLM | mpu/utils.py | https://github.com/THUDM/GLM/blob/master/mpu/utils.py | MIT |
def update_cmd(cmd, config):
'''
@param cmd str
@param configs list of dicts
'''
for k, v in config.items():
if v is None:
continue
if type(v) == bool:
if v:
cmd += "--{} ".format(k)
else:
cmd += "--{} {} ".format(k,... |
@param cmd str
@param configs list of dicts
| update_cmd | python | THUDM/GLM | scripts/dispatcher.py | https://github.com/THUDM/GLM/blob/master/scripts/dispatcher.py | MIT |
def clean_text(text):
"""Remove new lines and multiple spaces and adjust end of sentence dot."""
text = text.replace("\n", " ")
text = re.sub(r'\s+', ' ', text)
for _ in range(3):
text = text.replace(' . ', '. ')
return text | Remove new lines and multiple spaces and adjust end of sentence dot. | clean_text | python | THUDM/GLM | tasks/data_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/data_utils.py | MIT |
def __init__(self, guid, text_a, text_b=None, label=None, logits=None, meta: Optional[Dict] = None, idx=-1,
num_choices=1):
"""
Create a new InputExample.
:param guid: a unique textual identifier
:param text_a: the sequence of text
:param text_b: an optional, se... |
Create a new InputExample.
:param guid: a unique textual identifier
:param text_a: the sequence of text
:param text_b: an optional, second sequence of text
:param label: an optional label
:param logits: an optional list of per-class logits
:param meta: an option... | __init__ | python | THUDM/GLM | tasks/data_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/data_utils.py | MIT |
def build_sample(ids, types=None, paddings=None, positions=None, masks=None, label=None, unique_id=None, target=None,
logit_mask=None, segment_ids=None, prompt_ids=None):
"""Convert to numpy and return a sample consumed by the batch producer."""
ids_np = np.array(ids, dtype=np.int64)
sampl... | Convert to numpy and return a sample consumed by the batch producer. | build_sample | python | THUDM/GLM | tasks/data_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/data_utils.py | MIT |
def build_data_loader(dataset, batch_size, num_workers, drop_last, shuffle=True, only_rank0=False):
"""Data loader. Note that batch-size is the local (per GPU) batch-size."""
# Sampler.
if only_rank0:
rank, world_size = 0, 1
else:
world_size = mpu.get_data_parallel_world_size()
... | Data loader. Note that batch-size is the local (per GPU) batch-size. | build_data_loader | python | THUDM/GLM | tasks/data_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/data_utils.py | MIT |
def multichoice_evaluate(model, dataloader, example_dict, args):
"""Calculate correct over total answers and return prediction if the
`output_predictions` is true."""
model.eval()
results = {}
with torch.no_grad():
# For all the batches in the dataset.
for _, batch in enumerate(datal... | Calculate correct over total answers and return prediction if the
`output_predictions` is true. | multichoice_evaluate | python | THUDM/GLM | tasks/eval_utils.py | https://github.com/THUDM/GLM/blob/master/tasks/eval_utils.py | MIT |
def evaluate_and_print_results(data_loader, model, eval_metric, args):
"""Evaluate and print results on screen."""
# Evaluate and get results.
output, _ = evaluate(model, data_loader, eval_metric, args)
string = ""
if eval_metric == 'loss':
output = output['loss']
num_tokenized_tok... | Evaluate and print results on screen. | evaluate_and_print_results | python | THUDM/GLM | tasks/language_model/finetune.py | https://github.com/THUDM/GLM/blob/master/tasks/language_model/finetune.py | MIT |
def process_batch(batch, args):
"""Process batch and produce inputs for the model."""
if 'mask' in batch:
# finetune SQuAD
batch['attention_mask'] = batch.pop('mask')
batch['position_id'] = batch.pop('position')
tokens = batch['text'].long().cuda()
attention_mask = batch['attenti... | Process batch and produce inputs for the model. | process_batch | python | THUDM/GLM | tasks/seq2seq/evaluate.py | https://github.com/THUDM/GLM/blob/master/tasks/seq2seq/evaluate.py | MIT |
def evaluate(self, model, dataloader, example_dict, args):
"""Calculate correct over total answers and return prediction if the
`output_predictions` is true."""
model.eval()
local_predictions = {}
print_rank_0("Distributed store created")
with torch.no_grad():
... | Calculate correct over total answers and return prediction if the
`output_predictions` is true. | evaluate | python | THUDM/GLM | tasks/seq2seq/evaluate.py | https://github.com/THUDM/GLM/blob/master/tasks/seq2seq/evaluate.py | MIT |
def clean_text(text):
"""Remove new lines and multiple spaces and adjust end of sentence dot."""
text = text.replace("\n", " ")
text = re.sub(r'\s+', ' ', text)
for _ in range(3):
text = text.replace(' . ', '. ')
return text | Remove new lines and multiple spaces and adjust end of sentence dot. | clean_text | python | THUDM/GLM | tasks/superglue/dataset.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/dataset.py | MIT |
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuat... | Lower text and remove punctuation, articles and extra whitespace. | normalize_answer | python | THUDM/GLM | tasks/superglue/evaluate.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/evaluate.py | MIT |
def multirc_em(predictions, labels, examples: List[InputExample]):
"""Compute the exact match (EM) for a sequence of predictions and actual labels"""
question_ids = [example.meta["question_idx"] for example in examples]
unique_questions = set(question_ids)
q_actuals = list(zip(question_ids, labels))
... | Compute the exact match (EM) for a sequence of predictions and actual labels | multirc_em | python | THUDM/GLM | tasks/superglue/evaluate.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/evaluate.py | MIT |
def __init__(self, args, tokenizer, label_list, max_seq_length, pattern_id: int = 0, verbalizer_file: str = None,
seed: int = 42, is_multi_token=False, max_segment_length=0, fast_decode: bool = False, split='train',
num_prompt_tokens=0):
"""
Create a new PVP.
:... |
Create a new PVP.
:param args: the args
:param tokenizer: the tokenizer
:param label_list: the list of labels
:param max_seq_length: the maximum length of the sequence
:param pattern_id: the pattern id to use
:param seed: a seed to be used for generating random ... | __init__ | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def encode(self, example: InputExample, priming: bool = False, labeled: bool = False):
"""
Encode an input example using this pattern-verbalizer pair.
:param example: the input example to encode
:param priming: whether to use this example for priming
:param labeled: if ``priming... |
Encode an input example using this pattern-verbalizer pair.
:param example: the input example to encode
:param priming: whether to use this example for priming
:param labeled: if ``priming=True``, whether the label should be appended to this example
:return: A tuple, consisting... | encode | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def truncate(self, parts_a: List[Tuple[List[int], bool]], parts_b: List[Tuple[List[int], bool]], answer: List[int],
max_length: int):
"""Truncate two sequences of text to a predefined total maximum length"""
total_len = self._seq_length(parts_a) + self._seq_length(parts_b)
if an... | Truncate two sequences of text to a predefined total maximum length | truncate | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def encode(self, example: InputExample, priming: bool = False, labeled: bool = False):
"""
Encode an input example using this pattern-verbalizer pair.
:param example: the input example to encode
:param priming: whether to use this example for priming
:param labeled: if ``priming... |
Encode an input example using this pattern-verbalizer pair.
:param example: the input example to encode
:param priming: whether to use this example for priming
:param labeled: if ``priming=True``, whether the label should be appended to this example
:return: A tuple, consisting... | encode | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def encode(self, example: InputExample, priming: bool = False, labeled: bool = False):
"""
Encode an input example using this pattern-verbalizer pair.
:param example: the input example to encode
:param priming: whether to use this example for priming
:param labeled: if ``priming... |
Encode an input example using this pattern-verbalizer pair.
:param example: the input example to encode
:param priming: whether to use this example for priming
:param labeled: if ``priming=True``, whether the label should be appended to this example
:return: A tuple, consisting... | encode | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def get_verbalization_ids(word: str, tokenizer, force_single_token: bool) -> Union[int, List[int]]:
"""
Get the token ids corresponding to a verbalization
:param word: the verbalization
:param tokenizer: the tokenizer to use
:param force_single_token: whether it should be enforced that the verbaliz... |
Get the token ids corresponding to a verbalization
:param word: the verbalization
:param tokenizer: the tokenizer to use
:param force_single_token: whether it should be enforced that the verbalization corresponds to a single token.
If set to true, this method returns a single int instead of... | get_verbalization_ids | python | THUDM/GLM | tasks/superglue/pvp.py | https://github.com/THUDM/GLM/blob/master/tasks/superglue/pvp.py | MIT |
def search_github_code_byapi(token: str, peer_page: int = 50, page: int = 1, excludes: list = []) -> list[str]:
"""
curl -Ls -o response.json -H "Authorization: Bearer <token>" https://api.github.com/search/code?q=%22%2Fapi%2Fv1%2Fclient%2Fsubscribe%3Ftoken%3D%22&sort=indexed&order=desc&per_page=30&page=1
"... |
curl -Ls -o response.json -H "Authorization: Bearer <token>" https://api.github.com/search/code?q=%22%2Fapi%2Fv1%2Fclient%2Fsubscribe%3Ftoken%3D%22&sort=indexed&order=desc&per_page=30&page=1
| search_github_code_byapi | python | wzdnzd/aggregator | subscribe/crawl.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/crawl.py | Apache-2.0 |
def download_mmdb(repo: str, target: str, filepath: str, retry: int = 3) -> bool:
"""
Download GeoLite2-City.mmdb from github release
"""
repo = utils.trim(text=repo)
if not repo or len(repo.split("/", maxsplit=1)) != 2:
logger.error(f"invalid github repo name: {repo}")
return False
... |
Download GeoLite2-City.mmdb from github release
| download_mmdb | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def download(url: str, filepath: str, filename: str, retry: int = 3) -> bool:
"""Download file from url to filepath with filename"""
if retry < 0:
logger.error(f"archieved max retry count for download, url: {url}")
return False
url = utils.trim(text=url)
if not url:
logger.erro... | Download file from url to filepath with filename | download | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def query_ip_country(ip: str, reader: database.Reader) -> str:
"""
Query country information for an IP address using mmdb database
Args:
ip: The IP address to query
reader: The mmdb database reader
Returns:
The country name in Chinese
"""
if not ip or not reader:
... |
Query country information for an IP address using mmdb database
Args:
ip: The IP address to query
reader: The mmdb database reader
Returns:
The country name in Chinese
| query_ip_country | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def get_listening_ports() -> set:
"""Get the set of listening ports in the system, cross-platform compatible"""
listening_ports = set()
try:
# Windows system
if os.name == "nt":
try:
# Use 'cp437' encoding to handle Windows command line output
out... | Get the set of listening ports in the system, cross-platform compatible | get_listening_ports | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def scan_ports_batch(start_port: int, count: int = 100) -> dict:
"""Batch scan port statuses, return a dictionary of port statuses"""
global _PORT_STATUS_CACHE, _AVAILABLE_PORTS
# Create a list of ports to scan (excluding ports with known status)
ports_to_scan = [p for p in range(start_port, start_port... | Batch scan port statuses, return a dictionary of port statuses | scan_ports_batch | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def check_single_port(port: int) -> bool:
"""Helper function for checking a single port, checks if the port is listening"""
try:
# Use socket to check TCP port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.2)
result = sock.connect_ex(("127.0.0.1", por... | Helper function for checking a single port, checks if the port is listening | check_single_port | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def is_port_in_use(port: int) -> bool:
"""Check if a port is in use (using cache)"""
global _PORT_STATUS_CACHE, _AVAILABLE_PORTS
# If port is known to be available, return directly
if port in _AVAILABLE_PORTS:
return False
# If port status is already cached, return directly
if port in ... | Check if a port is in use (using cache) | is_port_in_use | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def generate_mihomo_config(proxies: list[dict]) -> tuple[dict, dict]:
"""Generate mihomo configuration for the given proxies"""
# Base configuration
config = {
"mixed-port": 7890,
"allow-lan": True,
"mode": "global",
"log-level": "error",
"proxies": proxies,
"... | Generate mihomo configuration for the given proxies | generate_mihomo_config | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def make_proxy_request(port: int, url: str, max_retries: int = 5, timeout: int = 10) -> tuple[bool, dict]:
"""
Make an HTTP request through a proxy and return the response
Args:
port: The port of the proxy
url: The URL to request
max_retries: Maximum number of retry attempts
... |
Make an HTTP request through a proxy and return the response
Args:
port: The port of the proxy
url: The URL to request
max_retries: Maximum number of retry attempts
timeout: Timeout for the request in seconds
Returns:
A tuple of (success, data) where:
- suc... | make_proxy_request | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def get_ipv4(port: int, max_retries: int = 5) -> str:
"""
Get the IPv4 address by accessing https://api.ipify.org?format=json through a proxy
Args:
port: The port of the proxy
max_retries: Maximum number of retry attempts
Returns:
The IPv4 address or empty string if failed
... |
Get the IPv4 address by accessing https://api.ipify.org?format=json through a proxy
Args:
port: The port of the proxy
max_retries: Maximum number of retry attempts
Returns:
The IPv4 address or empty string if failed
| get_ipv4 | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def locate_by_ipinfo(name: str, port: int, reader: database.Reader = None) -> dict:
"""Check the location of a single proxy by making a request through it"""
result = {"name": name, "country": ""}
if not port:
logger.warning(f"No port found for proxy {name}")
return result
if reader:
... | Check the location of a single proxy by making a request through it | locate_by_ipinfo | python | wzdnzd/aggregator | subscribe/location.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/location.py | Apache-2.0 |
def get_messages(self, account: Account) -> list:
"""download a list of messages currently in the account."""
if not account or not self.auth_headers:
return []
content = utils.http_get(
url="{}/messages?page={}".format(self.api_address, 1),
headers=self.auth... | download a list of messages currently in the account. | get_messages | python | wzdnzd/aggregator | subscribe/mailtm.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/mailtm.py | Apache-2.0 |
def delete_account(self, account: Account) -> bool:
"""try to delete the account. returns True if it succeeds."""
if account is None or not self.auth_headers:
return False
try:
request = urllib.request.Request(
url=f"{self.api_address}/accounts/{account.i... | try to delete the account. returns True if it succeeds. | delete_account | python | wzdnzd/aggregator | subscribe/mailtm.py | https://github.com/wzdnzd/aggregator/blob/master/subscribe/mailtm.py | Apache-2.0 |
def download_mmdb(repo: str, target: str, filepath: str, retry: int = 3):
"""
Download GeoLite2-City.mmdb from github release
"""
repo = trim(text=repo)
if not repo or len(repo.split("/", maxsplit=1)) != 2:
raise ValueError(f"invalid github repo name: {repo}")
target = trim(target)
... |
Download GeoLite2-City.mmdb from github release
| download_mmdb | python | wzdnzd/aggregator | tools/clean.py | https://github.com/wzdnzd/aggregator/blob/master/tools/clean.py | Apache-2.0 |
def download(url: str, filepath: str, filename: str, retry: int = 3) -> None:
"""Download file from url to filepath with filename"""
if retry < 0:
raise Exception("archieved max retry count for download")
url = trim(url)
if not url:
raise ValueError("invalid download url")
filepat... | Download file from url to filepath with filename | download | python | wzdnzd/aggregator | tools/clean.py | https://github.com/wzdnzd/aggregator/blob/master/tools/clean.py | Apache-2.0 |
def download_mmdb(target: str, filepath: str, retry: int = 3):
"""
Download GeoLite2-City.mmdb from github release
"""
target = trim(target)
if not target:
raise ValueError("invalid download target")
# extract download url from github release page
release_api = "https://api.github.... |
Download GeoLite2-City.mmdb from github release
| download_mmdb | python | wzdnzd/aggregator | tools/ip-location.py | https://github.com/wzdnzd/aggregator/blob/master/tools/ip-location.py | Apache-2.0 |
def download(url: str, filepath: str, filename: str, retry: int = 3, timeout: int = 10) -> None:
"""Download file from url to filepath with filename"""
if retry < 0:
raise Exception("archieved max retry count for download")
url = trim(url)
if not url:
raise ValueError("invalid download... | Download file from url to filepath with filename | download | python | wzdnzd/aggregator | tools/ip-location.py | https://github.com/wzdnzd/aggregator/blob/master/tools/ip-location.py | Apache-2.0 |
def download_mmdb(repo: str, target: str, filepath: str, retry: int = 3):
"""
Download GeoLite2-City.mmdb from github release
"""
repo = trim(text=repo)
if not repo or len(repo.split("/", maxsplit=1)) != 2:
raise ValueError(f"invalid github repo name: {repo}")
target = trim(target)
... |
Download GeoLite2-City.mmdb from github release
| download_mmdb | python | wzdnzd/aggregator | tools/xui.py | https://github.com/wzdnzd/aggregator/blob/master/tools/xui.py | Apache-2.0 |
def download(url: str, filepath: str, filename: str, retry: int = 3) -> None:
"""Download file from url to filepath with filename"""
if retry < 0:
raise Exception("archieved max retry count for download")
url = trim(url)
if not url:
raise ValueError("invalid download url")
filepat... | Download file from url to filepath with filename | download | python | wzdnzd/aggregator | tools/xui.py | https://github.com/wzdnzd/aggregator/blob/master/tools/xui.py | Apache-2.0 |
def test_synthetic_arange_random_n_data():
"""Test if correct data quantity is generated by synthetic_arange_random."""
n_list = [10, 20]
for n in n_list:
y_pred, y_std, y_true, x = synthetic_arange_random(n)
assert len(y_pred) == n
assert len(y_std) == n
assert len(y_true) =... | Test if correct data quantity is generated by synthetic_arange_random. | test_synthetic_arange_random_n_data | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_data.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_data.py | MIT |
def test_synthetic_sine_heteroscedastic_n_data():
"""Test if correct data quantity is generated by synthetic_sine_heteroscedastic."""
n_list = [10, 20]
for n in n_list:
y_pred, y_std, y_true, x = synthetic_sine_heteroscedastic(n)
assert len(y_pred) == n
assert len(y_std) == n
... | Test if correct data quantity is generated by synthetic_sine_heteroscedastic. | test_synthetic_sine_heteroscedastic_n_data | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_data.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_data.py | MIT |
def test_get_all_accuracy_metrics_returns(get_test_set):
"""Test if correct accuracy metrics are returned."""
y_pred, y_std, y_true = get_test_set
met_dict = get_all_accuracy_metrics(y_pred, y_true)
met_keys = met_dict.keys()
assert len(met_keys) == 6
met_str_list = ["mae", "rmse", "mdae", "mar... | Test if correct accuracy metrics are returned. | test_get_all_accuracy_metrics_returns | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics.py | MIT |
def test_get_all_average_calibration_returns(get_test_set):
"""Test if correct average calibration metrics are returned."""
n_bins = 20
met_dict = get_all_average_calibration(*get_test_set, n_bins)
met_keys = met_dict.keys()
assert len(met_keys) == 3
met_str_list = ["rms_cal", "ma_cal", "miscal... | Test if correct average calibration metrics are returned. | test_get_all_average_calibration_returns | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics.py | MIT |
def test_get_all_adversarial_group_calibration_returns(get_test_set):
"""Test if correct adversarial group calibration metrics are returned."""
n_bins = 20
met_dict = get_all_adversarial_group_calibration(*get_test_set, n_bins)
met_keys = met_dict.keys()
assert len(met_keys) == 2
met_str_list =... | Test if correct adversarial group calibration metrics are returned. | test_get_all_adversarial_group_calibration_returns | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics.py | MIT |
def test_get_all_sharpness_metrics_returns(get_test_set):
"""Test if correct sharpness metrics are returned."""
y_pred, y_std, y_true = get_test_set
met_dict = get_all_sharpness_metrics(y_std)
met_keys = met_dict.keys()
assert len(met_keys) == 1
assert "sharp" in met_keys | Test if correct sharpness metrics are returned. | test_get_all_sharpness_metrics_returns | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics.py | MIT |
def test_get_all_scoring_rule_metrics_returns(get_test_set):
"""Test if correct scoring rule metrics are returned."""
resolution = 99
scaled = True
met_dict = get_all_scoring_rule_metrics(*get_test_set, resolution, scaled)
met_keys = met_dict.keys()
assert len(met_keys) == 4
met_str_list = ... | Test if correct scoring rule metrics are returned. | test_get_all_scoring_rule_metrics_returns | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics.py | MIT |
def test_get_all_metrics_returns(get_test_set):
"""Test if correct metrics are returned by get_all_metrics function."""
met_dict = get_all_metrics(*get_test_set)
met_keys = met_dict.keys()
assert len(met_keys) == 5
met_str_list = [
"accuracy",
"avg_calibration",
"adv_group_c... | Test if correct metrics are returned by get_all_metrics function. | test_get_all_metrics_returns | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics.py | MIT |
def test_prediction_error_metric_fields(get_test_set):
"""Test if prediction error metrics have correct fields."""
y_pred, y_std, y_true = get_test_set
met_dict = prediction_error_metrics(y_pred, y_true)
met_keys = met_dict.keys()
assert len(met_keys) == 6
met_str_list = ["mae", "rmse", "mdae",... | Test if prediction error metrics have correct fields. | test_prediction_error_metric_fields | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_accuracy.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_accuracy.py | MIT |
def test_prediction_error_metric_values(get_test_set):
"""Test if prediction error metrics have correct values."""
y_pred, y_std, y_true = get_test_set
met_dict = prediction_error_metrics(y_pred, y_true)
print(met_dict)
assert met_dict["mae"] > 0.21 and met_dict["mae"] < 0.22
assert met_dict["rm... | Test if prediction error metrics have correct values. | test_prediction_error_metric_values | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_accuracy.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_accuracy.py | MIT |
def test_sharpness_on_test_set(supply_test_set):
"""Test sharpness on the test set for some dummy values."""
_, test_std, _ = supply_test_set
assert np.abs(sharpness(test_std) - 0.648074069840786) < 1e-6 | Test sharpness on the test set for some dummy values. | test_sharpness_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_root_mean_squared_calibration_error_on_test_set(supply_test_set):
"""Test root mean squared calibration error on some dummy values."""
test_rmsce_nonvectorized_interval = root_mean_squared_calibration_error(
*supply_test_set,
num_bins=100,
vectorized=False,
recal_model=N... | Test root mean squared calibration error on some dummy values. | test_root_mean_squared_calibration_error_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_mean_absolute_calibration_error_on_test_set(supply_test_set):
"""Test mean absolute calibration error on some dummy values."""
test_mace_nonvectorized_interval = mean_absolute_calibration_error(
*supply_test_set,
num_bins=100,
vectorized=False,
recal_model=None,
... | Test mean absolute calibration error on some dummy values. | test_mean_absolute_calibration_error_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_adversarial_group_calibration_on_test_set(supply_test_set):
"""Test adversarial group calibration on test set for some dummy values."""
test_out_interval = adversarial_group_calibration(
*supply_test_set,
cali_type="mean_abs",
prop_type="interval",
num_bins=100,
... | Test adversarial group calibration on test set for some dummy values. | test_adversarial_group_calibration_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_miscalibration_area_on_test_set(supply_test_set):
"""Test miscalibration area on some dummy values."""
test_miscal_area_nonvectorized_interval = miscalibration_area(
*supply_test_set,
num_bins=100,
vectorized=False,
recal_model=None,
prop_type="interval"
)
... | Test miscalibration area on some dummy values. | test_miscalibration_area_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_vectorization_for_proportion_list_on_test_set(supply_test_set):
"""Test vectorization in get_proportion_lists on the test set for some dummy values."""
(
test_exp_props_nonvec_interval,
test_obs_props_nonvec_interval,
) = get_proportion_lists(
*supply_test_set, num_bins=100,... | Test vectorization in get_proportion_lists on the test set for some dummy values. | test_vectorization_for_proportion_list_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_get_proportion_lists_vectorized_on_test_set(supply_test_set):
"""Test get_proportion_lists_vectorized on the test set for some dummy values."""
(
test_exp_props_interval,
test_obs_props_interval,
) = get_proportion_lists_vectorized(
*supply_test_set, num_bins=100, recal_mode... | Test get_proportion_lists_vectorized on the test set for some dummy values. | test_get_proportion_lists_vectorized_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_get_proportion_lists_on_test_set(supply_test_set):
"""Test get_proportion_lists on the test set for some dummy values."""
test_exp_props_interval, test_obs_props_interval = get_proportion_lists(
*supply_test_set, num_bins=100, recal_model=None, prop_type="interval"
)
assert len(test_exp... | Test get_proportion_lists on the test set for some dummy values. | test_get_proportion_lists_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_get_proportion_in_interval_on_test_set(supply_test_set):
"""Test get_proportion_in_interval on the test set for some dummy values."""
test_quantile_value_list = [
(0.0, 0.0),
(0.25, 0.0),
(0.5, 0.0),
(0.75, 0.3333333333333333),
(1.0, 1.0),
]
for test_q, t... | Test get_proportion_in_interval on the test set for some dummy values. | test_get_proportion_in_interval_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_get_proportion_under_quantile_on_test_set(supply_test_set):
"""Test get_proportion_in_interval on the test set for some dummy values."""
test_quantile_value_list = [
(0.0, 0.0),
(0.25, 0.6666666666666666),
(0.5, 0.6666666666666666),
(0.75, 0.6666666666666666),
(1... | Test get_proportion_in_interval on the test set for some dummy values. | test_get_proportion_under_quantile_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_get_prediction_interval_on_test_set(supply_test_set):
"""Test get_prediction_interval on the test set for some dummy values."""
test_quantile_value_list = [
(
0.01,
np.array([1.00125335, 2.00626673, 3.01253347]),
np.array([0.99874665, 1.99373327, 2.98746653])... | Test get_prediction_interval on the test set for some dummy values. | test_get_prediction_interval_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_get_quantile_on_test_set(supply_test_set):
"""Test get_prediction_interval on the test set for some dummy values."""
test_quantile_value_list = [
(0.01, np.array([0.76736521, 0.83682606, 0.67365213])),
(
0.25,
np.array([0.93255102, 1.66275512, 2.32551025]),
... | Test get_prediction_interval on the test set for some dummy values. | test_get_quantile_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_calibration.py | MIT |
def test_nll_gaussian_on_one_pt():
"""Sanity check by testing one point at mean of gaussian."""
y_pred = np.array([0])
y_true = np.array([0])
y_std = np.array([1 / np.sqrt(2 * np.pi)])
assert np.abs(nll_gaussian(y_pred, y_std, y_true)) < 1e-6 | Sanity check by testing one point at mean of gaussian. | test_nll_gaussian_on_one_pt | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_scoring_rule.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_scoring_rule.py | MIT |
def test_check_score_on_one_pt():
"""Sanity check to show that check score is minimized (i.e. 0) if data
occurs at the exact requested quantile."""
y_pred = np.array([0])
y_true = np.array([1])
y_std = np.array([1])
score = check_score(
y_pred=y_pred,
y_std=y_std,
y_true=... | Sanity check to show that check score is minimized (i.e. 0) if data
occurs at the exact requested quantile. | test_check_score_on_one_pt | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_scoring_rule.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_scoring_rule.py | MIT |
def test_interval_score_on_one_pt():
"""Sanity check on interval score. For one point in the center of the
distribution and intervals one standard deviation and two standard
deviations away, should return ((1 std) * 2 + (2 std) * 2) / 2 = 3.
"""
y_pred = np.array([0])
y_true = np.array([0])
... | Sanity check on interval score. For one point in the center of the
distribution and intervals one standard deviation and two standard
deviations away, should return ((1 std) * 2 + (2 std) * 2) / 2 = 3.
| test_interval_score_on_one_pt | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_metrics_scoring_rule.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_metrics_scoring_rule.py | MIT |
def test_recal_model_mace_criterion_on_test_set(supply_test_set):
"""
Test recalibration on mean absolute calibration error on the test set
for some dummy values.
"""
test_mace = mean_absolute_calibration_error(
*supply_test_set, num_bins=100, vectorized=True, recal_model=None
)
test... |
Test recalibration on mean absolute calibration error on the test set
for some dummy values.
| test_recal_model_mace_criterion_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_recal_model_rmce_criterion_on_test_set(supply_test_set):
"""
Test recalibration on root mean squared calibration error on the test set
for some dummy values.
"""
test_rmsce = root_mean_squared_calibration_error(
*supply_test_set, num_bins=100, vectorized=True, recal_model=None
)... |
Test recalibration on root mean squared calibration error on the test set
for some dummy values.
| test_recal_model_rmce_criterion_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_recal_model_miscal_area_criterion_on_test_set(supply_test_set):
"""
Test recalibration on miscalibration area on the test set
for some dummy values.
"""
test_miscal_area = miscalibration_area(
*supply_test_set, num_bins=100, vectorized=True, recal_model=None
)
test_exp_props... |
Test recalibration on miscalibration area on the test set
for some dummy values.
| test_recal_model_miscal_area_criterion_on_test_set | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_optimize_recalibration_ratio_mace_criterion(supply_test_set):
"""
Test standard deviation recalibration on mean absolute calibration error
on the test set for some dummy values.
"""
random.seed(0)
np.random.seed(seed=0)
y_pred, y_std, y_true = supply_test_set
ma_cal_ratio = opt... |
Test standard deviation recalibration on mean absolute calibration error
on the test set for some dummy values.
| test_optimize_recalibration_ratio_mace_criterion | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_optimize_recalibration_ratio_rmce_criterion(supply_test_set):
"""
Test standard deviation recalibration on root mean squared calibration error
on the test set for some dummy values.
"""
random.seed(0)
np.random.seed(seed=0)
y_pred, y_std, y_true = supply_test_set
rms_cal_ratio ... |
Test standard deviation recalibration on root mean squared calibration error
on the test set for some dummy values.
| test_optimize_recalibration_ratio_rmce_criterion | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_optimize_recalibration_ratio_miscal_area_criterion(supply_test_set):
"""
Test standard deviation recalibration on miscalibration area
on the test set for some dummy values.
"""
random.seed(0)
np.random.seed(seed=0)
y_pred, y_std, y_true = supply_test_set
miscal_ratio = optimize... |
Test standard deviation recalibration on miscalibration area
on the test set for some dummy values.
| test_optimize_recalibration_ratio_miscal_area_criterion | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_get_prediction_interval_recalibrated(supply_test_set):
"""
Test standard deviation recalibration on miscalibration area
on the test set for some dummy values.
"""
random.seed(0)
np.random.seed(seed=0)
y_pred, y_std, y_true = supply_test_set
test_exp_props, test_obs_props = get_... |
Test standard deviation recalibration on miscalibration area
on the test set for some dummy values.
| test_get_prediction_interval_recalibrated | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_get_std_recalibrator(supply_test_set):
"""
Test get_std_recalibration on the test set for some dummy values.
"""
random.seed(0)
np.random.seed(seed=0)
y_pred, y_std, y_true = supply_test_set
test_quantile_prop_list = [
(0.01, 0.00, 0.00),
(0.25, 0.06, 0.00),
... |
Test get_std_recalibration on the test set for some dummy values.
| test_get_std_recalibrator | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_get_quantile_recalibrator(supply_test_set):
"""
Test get_std_recalibration on the test set for some dummy values.
"""
random.seed(0)
np.random.seed(seed=0)
y_pred, y_std, y_true = supply_test_set
test_quantile_prop_list = [
(0.01, 0.00),
(0.25, 0.00),
(0.50... |
Test get_std_recalibration on the test set for some dummy values.
| test_get_quantile_recalibrator | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_get_interval_recalibrator(supply_test_set):
"""
Test get_std_recalibration on the test set for some dummy values.
"""
random.seed(0)
np.random.seed(seed=0)
y_pred, y_std, y_true = supply_test_set
test_quantile_prop_list = [
(0.01, 0.00),
(0.25, 0.25),
(0.50... |
Test get_std_recalibration on the test set for some dummy values.
| test_get_interval_recalibrator | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_recalibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_recalibration.py | MIT |
def test_filter_subset(get_test_set):
"""Test if filter_subset returns correct number of subset elements."""
y_pred, y_std, y_true, _ = get_test_set
_test_n_subset = 2
[y_pred, y_std, y_true] = filter_subset([y_pred, y_std, y_true], _test_n_subset)
assert len(y_pred) == _test_n_subset
assert len... | Test if filter_subset returns correct number of subset elements. | test_filter_subset | python | uncertainty-toolbox/uncertainty-toolbox | tests/test_viz.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/tests/test_viz.py | MIT |
def synthetic_arange_random(
num_points: int = 10,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Dataset of evenly spaced points and identity function (with some randomization).
This function returns predictions and predictive uncertainties (given as standard
deviations) from some hypo... | Dataset of evenly spaced points and identity function (with some randomization).
This function returns predictions and predictive uncertainties (given as standard
deviations) from some hypothetical uncertainty model, along with true input x and
output y data points.
Args:
num_points: The numbe... | synthetic_arange_random | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/data.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/data.py | MIT |
def synthetic_sine_heteroscedastic(
n_points: int = 10,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Return samples from "synthetic sine" heteroscedastic noisy function.
This returns a synthetic dataset which can be used to train and assess a predictive
uncertainty model.
Args:
... | Return samples from "synthetic sine" heteroscedastic noisy function.
This returns a synthetic dataset which can be used to train and assess a predictive
uncertainty model.
Args:
n_points: The number of data points in the set.
Returns:
- Predicted output points y.
- Predictive ... | synthetic_sine_heteroscedastic | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/data.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/data.py | MIT |
def get_all_accuracy_metrics(
y_pred: np.ndarray,
y_true: np.ndarray,
verbose: bool = True,
) -> Dict[str, float]:
"""Compute all accuracy metrics.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
... | Compute all accuracy metrics.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
verbose: Activate verbose mode.
Returns:
The evaluations for all accuracy related metrics.
| get_all_accuracy_metrics | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics.py | MIT |
def get_all_average_calibration(
y_pred: np.ndarray,
y_std: np.ndarray,
y_true: np.ndarray,
num_bins: int,
verbose: bool = True,
) -> Dict[str, float]:
"""Compute all metrics for average calibration.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_s... | Compute all metrics for average calibration.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_std: 1D array of he predicted standard deviations for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
num_bins: The number of bin... | get_all_average_calibration | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics.py | MIT |
def get_all_adversarial_group_calibration(
y_pred: np.ndarray,
y_std: np.ndarray,
y_true: np.ndarray,
num_bins: int,
verbose: bool = True,
) -> Dict[str, Dict[str, np.ndarray]]:
"""Compute all metrics for adversarial group calibration.
Args:
y_pred: 1D array of the predicted means f... | Compute all metrics for adversarial group calibration.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_std: 1D array of he predicted standard deviations for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
num_bins: The num... | get_all_adversarial_group_calibration | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics.py | MIT |
def get_all_sharpness_metrics(
y_std: np.ndarray,
verbose: bool = True,
) -> Dict[str, float]:
"""Compute all sharpness metrics
Args:
y_std: 1D array of he predicted standard deviations for the held out dataset.
verbose: Activate verbose mode.
Returns:
The evaluations for a... | Compute all sharpness metrics
Args:
y_std: 1D array of he predicted standard deviations for the held out dataset.
verbose: Activate verbose mode.
Returns:
The evaluations for all sharpness metrics.
| get_all_sharpness_metrics | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics.py | MIT |
def get_all_scoring_rule_metrics(
y_pred: np.ndarray,
y_std: np.ndarray,
y_true: np.ndarray,
resolution: int,
scaled: bool,
verbose: bool = True,
) -> Dict[str, float]:
"""Compute all scoring rule metrics
Args:
y_pred: 1D array of the predicted means for the held out dataset.
... | Compute all scoring rule metrics
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_std: 1D array of he predicted standard deviations for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
resolution: The number of quantiles to ... | get_all_scoring_rule_metrics | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics.py | MIT |
def get_all_metrics(
y_pred: np.ndarray,
y_std: np.ndarray,
y_true: np.ndarray,
num_bins: int = 100,
resolution: int = 99,
scaled: bool = True,
verbose: bool = True,
) -> Dict[str, Any]:
"""Compute all metrics.
Args:
y_pred: 1D array of the predicted means for the held out d... | Compute all metrics.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_std: 1D array of he predicted standard deviations for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
num_bins: The number of bins to use for discretizat... | get_all_metrics | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics.py | MIT |
def prediction_error_metrics(
y_pred: np.ndarray,
y_true: np.ndarray,
) -> Dict[str, float]:
"""Get all prediction error metrics.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
Returns:
A ... | Get all prediction error metrics.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
Returns:
A dictionary with Mean average error ('mae'), Root mean squared
error ('rmse'), Median absolute error ... | prediction_error_metrics | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics_accuracy.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_accuracy.py | MIT |
def sharpness(y_std: np.ndarray) -> float:
"""Return sharpness (a single measure of the overall confidence).
Args:
y_std: 1D array of the predicted standard deviations for the held out dataset.
Returns:
A single scalar which quantifies the average of the standard deviations.
"""
# ... | Return sharpness (a single measure of the overall confidence).
Args:
y_std: 1D array of the predicted standard deviations for the held out dataset.
Returns:
A single scalar which quantifies the average of the standard deviations.
| sharpness | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py | MIT |
def root_mean_squared_calibration_error(
y_pred: np.ndarray,
y_std: np.ndarray,
y_true: np.ndarray,
num_bins: int = 100,
vectorized: bool = False,
recal_model: IsotonicRegression = None,
prop_type: str = "interval",
) -> float:
"""Root mean squared calibration error.
Args:
y... | Root mean squared calibration error.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_std: 1D array of the predicted standard deviations for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
num_bins: number of discretization... | root_mean_squared_calibration_error | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py | MIT |
def mean_absolute_calibration_error(
y_pred: np.ndarray,
y_std: np.ndarray,
y_true: np.ndarray,
num_bins: int = 100,
vectorized: bool = False,
recal_model: IsotonicRegression = None,
prop_type: str = "interval",
) -> float:
"""Mean absolute calibration error; identical to ECE.
Args:... | Mean absolute calibration error; identical to ECE.
Args:
y_pred: 1D array of the predicted means for the held out dataset.
y_std: 1D array of the predicted standard deviations for the held out dataset.
y_true: 1D array of the true labels in the held out dataset.
num_bins: number of ... | mean_absolute_calibration_error | python | uncertainty-toolbox/uncertainty-toolbox | uncertainty_toolbox/metrics_calibration.py | https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.