INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Predicts ( int ) labels for an input X on all tasks
def predict(self, X, break_ties="random", return_probs=False, **kwargs): """Predicts (int) labels for an input X on all tasks Args: X: The input for the predict_proba method break_ties: A tie-breaking policy (see Classifier._break_ties()) return_probs: Return the pre...
Scores the predictive performance of the Classifier on all tasks
def score( self, data, metric="accuracy", break_ties="random", verbose=True, print_confusion_matrix=True, **kwargs, ): """Scores the predictive performance of the Classifier on all tasks Args: data: a Pytorch DataLoader, Dataset, o...
The internal training routine called by train_model () after setup
def _train_model( self, train_data, loss_fn, valid_data=None, log_writer=None, restore_state={} ): """The internal training routine called by train_model() after setup Args: train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of X (data) and Y (label...
Serialize and save a model.
def save(self, destination, **kwargs): """Serialize and save a model. Example: end_model = EndModel(...) end_model.train_model(...) end_model.save("my_end_model.pkl") """ with open(destination, "wb") as f: torch.save(self, f, **kwargs)
Deserialize and load a model.
def load(source, **kwargs): """Deserialize and load a model. Example: end_model = EndModel.load("my_end_model.pkl") end_model.score(...) """ with open(source, "rb") as f: return torch.load(f, **kwargs)
This model resume training of a classifier by reloading the appropriate state_dicts for each model
def resume_training(self, train_data, model_path, valid_data=None): """This model resume training of a classifier by reloading the appropriate state_dicts for each model Args: train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of X (data) and Y (labels) for the ...
Restores the model and optimizer states
def _restore_training_state(self, restore_state): """Restores the model and optimizer states This helper function restores the model's state to a given iteration so that a user can resume training at any epoch. Args: restore_state: a state_dict dictionary """ ...
Converts input data to the appropriate Dataset
def _create_dataset(self, *data): """Converts input data to the appropriate Dataset""" # Make sure data is a tuple of dense tensors data = [self._to_torch(x, dtype=torch.FloatTensor) for x in data] return TensorDataset(*data)
Converts input data into a DataLoader
def _create_data_loader(self, data, **kwargs): """Converts input data into a DataLoader""" if data is None: return None # Set DataLoader config # NOTE: Not applicable if data is already a DataLoader config = { **self.config["train_config"]["data_loader_co...
Computes predictions in batch given a labeled dataset
def _get_predictions(self, data, break_ties="random", return_probs=False, **kwargs): """Computes predictions in batch, given a labeled dataset Args: data: a Pytorch DataLoader, Dataset, or tuple with Tensors (X,Y): X: The input for the predict method Y: An [n...
Break ties in each row of a tensor according to the specified policy
def _break_ties(self, Y_s, break_ties="random"): """Break ties in each row of a tensor according to the specified policy Args: Y_s: An [n, k] np.ndarray of probabilities break_ties: A tie-breaking policy: "abstain": return an abstain vote (0) "ran...
Converts a None list np. ndarray or torch. Tensor to np. ndarray ; also handles converting sparse input to dense.
def _to_numpy(Z): """Converts a None, list, np.ndarray, or torch.Tensor to np.ndarray; also handles converting sparse input to dense.""" if Z is None: return Z elif issparse(Z): return Z.toarray() elif isinstance(Z, np.ndarray): return Z ...
Converts a None list np. ndarray or torch. Tensor to torch. Tensor ; also handles converting sparse input to dense.
def _to_torch(Z, dtype=None): """Converts a None, list, np.ndarray, or torch.Tensor to torch.Tensor; also handles converting sparse input to dense.""" if Z is None: return None elif issparse(Z): Z = torch.from_numpy(Z.toarray()) elif isinstance(Z, torch.Te...
Prints a warning statement just once
def warn_once(self, msg, msg_name=None): """Prints a warning statement just once Args: msg: The warning message msg_name: [optional] The name of the warning. If None, the msg_name will be the msg itself. """ assert isinstance(msg, str) msg...
Stack a list of np. ndarrays along the first axis returning an np. ndarray ; note this is mainly for smooth hanlding of the multi - task setting.
def _stack_batches(X): """Stack a list of np.ndarrays along the first axis, returning an np.ndarray; note this is mainly for smooth hanlding of the multi-task setting.""" X = [Classifier._to_numpy(Xb) for Xb in X] if len(X[0].shape) == 1: return np.hstack(X) e...
TBD
def _build(self, input_module, middle_modules, head_module): """ TBD """ input_layer = self._build_input_layer(input_module) middle_layers = self._build_middle_layers(middle_modules) # Construct list of layers layers = [input_layer] if middle_layers is no...
Convert Y to prob labels if necessary
def _preprocess_Y(self, Y, k): """Convert Y to prob labels if necessary""" Y = Y.clone() # If preds, convert to probs if Y.dim() == 1 or Y.shape[1] == 1: Y = pred_to_prob(Y.long(), k=k) return Y
Returns a [ n k ] tensor of probs ( probabilistic labels ).
def predict_proba(self, X): """Returns a [n, k] tensor of probs (probabilistic labels).""" return F.softmax(self.forward(X), dim=1).data.cpu().numpy()
Execute sparse linear layer
def forward(self, X): """Execute sparse linear layer Args: X: an [n, h] torch.LongTensor containing up to h indices of features whose weights should be looked up and used in a sparse linear multiplication. """ return self.W(X).sum(dim=1) + sel...
Create train/ dev/ test splits ( mapped to split numbers )
def splits( cls, conn_str, candidate_def, word_dict=None, train=0, dev=1, test=2, use_lfs=(0, 0, 0), pretrained_word_dict=None, max_seq_len=125, ): """ Create train/dev/test splits (mapped to split numbers) :par...
Convert Snorkel candidates to marked up sequences
def _mark_entities(self, c, markers): """ Convert Snorkel candidates to marked up sequences :param c: :param markers: :return: """ sent = c.get_parent().words positions = [ [c[i].get_word_start(), c[i].get_word_end()] for i in ran...
Include terms available via pretrained embeddings
def _include_pretrained_vocab(self, pretrained_word_dict, candidates): """ Include terms available via pretrained embeddings :param pretrained_word_dict: :param candidates: :return: """ terms = Counter() for c in candidates: for w in c.get_pa...
Initalize symbol table dictionary
def _build_vocab(self, sentences, markers=[]): """ Initalize symbol table dictionary :param sentences: :param markers: :return: """ from snorkel.learning.pytorch.rnn.utils import SymbolTable vocab = Counter() for sent in sentences: f...
Run some basic checks on L.
def _check_L(self, L): """Run some basic checks on L.""" # TODO: Take this out? if issparse(L): L = L.todense() # Check for correct values, e.g. warning if in {-1,0,1} if np.any(L < 0): raise ValueError("L must have values in {0,1,...,k}.")
Convert a label matrix with labels in 0... k to a one - hot format
def _create_L_ind(self, L): """Convert a label matrix with labels in 0...k to a one-hot format Args: L: An [n,m] scipy.sparse label matrix with values in {0,1,...,k} Returns: L_ind: An [n,m*k] dense np.ndarray with values in {0,1} Note that no column is require...
Returns an augmented version of L where each column is an indicator for whether a certain source or clique of sources voted in a certain pattern.
def _get_augmented_label_matrix(self, L, higher_order=False): """Returns an augmented version of L where each column is an indicator for whether a certain source or clique of sources voted in a certain pattern. Args: L: An [n,m] scipy.sparse label matrix with values in {0,1,...
Build mask applied to O^ { - 1 } O for the matrix approx constraint
def _build_mask(self): """Build mask applied to O^{-1}, O for the matrix approx constraint""" self.mask = torch.ones(self.d, self.d).byte() for ci in self.c_data.values(): si, ei = ci["start_index"], ci["end_index"] for cj in self.c_data.values(): sj, ej =...
Form the overlaps matrix which is just all the different observed combinations of values of pairs of sources
def _generate_O(self, L): """Form the overlaps matrix, which is just all the different observed combinations of values of pairs of sources Note that we only include the k non-abstain values of each source, otherwise the model not minimal --> leads to singular matrix """ ...
Form the * inverse * overlaps matrix
def _generate_O_inv(self, L): """Form the *inverse* overlaps matrix""" self._generate_O(L) self.O_inv = torch.from_numpy(np.linalg.inv(self.O.numpy())).float()
Initialize the learned params
def _init_params(self): """Initialize the learned params - \mu is the primary learned parameter, where each row corresponds to the probability of a clique C emitting a specific combination of labels, conditioned on different values of Y (for each column); that is: self.mu[i...
Returns the full conditional probabilities table as a numpy array where row i * ( k + 1 ) + ly is the conditional probabilities of source i emmiting label ly ( including abstains 0 ) conditioned on different values of Y i. e.:
def get_conditional_probs(self, source=None): """Returns the full conditional probabilities table as a numpy array, where row i*(k+1) + ly is the conditional probabilities of source i emmiting label ly (including abstains 0), conditioned on different values of Y, i.e.: c_pro...
Returns the [ n k ] matrix of label probabilities P ( Y | \ lambda )
def predict_proba(self, L): """Returns the [n,k] matrix of label probabilities P(Y | \lambda) Args: L: An [n,m] scipy.sparse label matrix with values in {0,1,...,k} """ self._set_constants(L) L_aug = self._get_augmented_label_matrix(L) mu = np.clip(self.mu.d...
Get the model s estimate of Q = \ mu P \ mu^T
def get_Q(self): """Get the model's estimate of Q = \mu P \mu^T We can then separately extract \mu subject to additional constraints, e.g. \mu P 1 = diag(O). """ Z = self.Z.detach().clone().numpy() O = self.O.numpy() I_k = np.eye(self.k) return O @ Z @ np...
L2 loss centered around mu_init scaled optionally per - source.
def loss_l2(self, l2=0): """L2 loss centered around mu_init, scaled optionally per-source. In other words, diagonal Tikhonov regularization, ||D(\mu-\mu_{init})||_2^2 where D is diagonal. Args: - l2: A float or np.array representing the per-source regularization...
Set a prior for the class balance
def _set_class_balance(self, class_balance, Y_dev): """Set a prior for the class balance In order of preference: 1) Use user-provided class_balance 2) Estimate balance from Y_dev 3) Assume uniform class distribution """ if class_balance is not None: s...
Train the model ( i. e. estimate mu ) in one of two ways depending on whether source dependencies are provided or not:
def train_model( self, L_train, Y_dev=None, deps=[], class_balance=None, log_writer=None, **kwargs, ): """Train the model (i.e. estimate mu) in one of two ways, depending on whether source dependencies are provided or not: Args: ...
Transforms the input label matrix to a three - way overlaps tensor.
def _get_overlaps_tensor(self, L): """Transforms the input label matrix to a three-way overlaps tensor. Args: L: (np.array) An n x m array of LF output labels, in {0,...,k} if self.abstains, else in {1,...,k}, generated by m conditionally independent LFs on n...
Get the mask for the three - way overlaps matrix O which is 0 when indices i j k are not unique
def get_mask(self, m): """Get the mask for the three-way overlaps matrix O, which is 0 when indices i,j,k are not unique""" mask = torch.ones((m, m, m, self.k_lf, self.k_lf, self.k_lf)).byte() for i, j, k in product(range(m), repeat=3): if len(set((i, j, k))) < 3: ...
Store or calculate char_offsets adding the offset of the doc end
def _get_char_offsets(self, char_offsets): """Store or calculate char_offsets, adding the offset of the doc end""" if char_offsets: char_offsets = char_offsets char_offsets.append(len(self.text)) else: char_offsets = np.zeros(len(self.tokens) + 1) ...
Args: L: An [ n m ] scipy. sparse matrix of labels Returns: output: A [ n k ] np. ndarray of probabilistic labels
def predict_proba(self, L): """ Args: L: An [n, m] scipy.sparse matrix of labels Returns: output: A [n, k] np.ndarray of probabilistic labels """ n = L.shape[0] Y_p = np.random.rand(n, self.k) Y_p /= Y_p.sum(axis=1).reshape(-1, 1) r...
Args: balance: A 1d arraylike that sums to 1 corresponding to the ( possibly estimated ) class balance.
def train_model(self, balance, *args, **kwargs): """ Args: balance: A 1d arraylike that sums to 1, corresponding to the (possibly estimated) class balance. """ self.balance = np.array(balance)
Iterator over values in feasible set
def feasible_set(self): """Iterator over values in feasible set""" for y in itertools.product(*[range(1, k + 1) for k in self.K]): yield np.array(y)
Calculate ( micro ) accuracy. Args: gold: A 1d array - like of gold labels pred: A 1d array - like of predicted labels ( assuming abstain = 0 ) ignore_in_gold: A list of labels for which elements having that gold label will be ignored. ignore_in_pred: A list of labels for which elements having that pred label will be i...
def accuracy_score(gold, pred, ignore_in_gold=[], ignore_in_pred=[]): """ Calculate (micro) accuracy. Args: gold: A 1d array-like of gold labels pred: A 1d array-like of predicted labels (assuming abstain = 0) ignore_in_gold: A list of labels for which elements having that gold ...
Calculate ( global ) coverage. Args: gold: A 1d array - like of gold labels pred: A 1d array - like of predicted labels ( assuming abstain = 0 ) ignore_in_gold: A list of labels for which elements having that gold label will be ignored. ignore_in_pred: A list of labels for which elements having that pred label will be ...
def coverage_score(gold, pred, ignore_in_gold=[], ignore_in_pred=[]): """ Calculate (global) coverage. Args: gold: A 1d array-like of gold labels pred: A 1d array-like of predicted labels (assuming abstain = 0) ignore_in_gold: A list of labels for which elements having that gold ...
Calculate precision for a single class. Args: gold: A 1d array - like of gold labels pred: A 1d array - like of predicted labels ( assuming abstain = 0 ) ignore_in_gold: A list of labels for which elements having that gold label will be ignored. ignore_in_pred: A list of labels for which elements having that pred label...
def precision_score(gold, pred, pos_label=1, ignore_in_gold=[], ignore_in_pred=[]): """ Calculate precision for a single class. Args: gold: A 1d array-like of gold labels pred: A 1d array-like of predicted labels (assuming abstain = 0) ignore_in_gold: A list of labels for which eleme...
Calculate recall for a single class. Args: gold: A 1d array - like of gold labels pred: A 1d array - like of predicted labels ( assuming abstain = 0 ) ignore_in_gold: A list of labels for which elements having that gold label will be ignored. ignore_in_pred: A list of labels for which elements having that pred label wi...
def recall_score(gold, pred, pos_label=1, ignore_in_gold=[], ignore_in_pred=[]): """ Calculate recall for a single class. Args: gold: A 1d array-like of gold labels pred: A 1d array-like of predicted labels (assuming abstain = 0) ignore_in_gold: A list of labels for which elements ha...
Calculate recall for a single class. Args: gold: A 1d array - like of gold labels pred: A 1d array - like of predicted labels ( assuming abstain = 0 ) ignore_in_gold: A list of labels for which elements having that gold label will be ignored. ignore_in_pred: A list of labels for which elements having that pred label wi...
def fbeta_score( gold, pred, pos_label=1, beta=1.0, ignore_in_gold=[], ignore_in_pred=[] ): """ Calculate recall for a single class. Args: gold: A 1d array-like of gold labels pred: A 1d array-like of predicted labels (assuming abstain = 0) ignore_in_gold: A list of labels for wh...
Compute the ROC AUC score given the gold labels and predicted probs.
def roc_auc_score(gold, probs, ignore_in_gold=[], ignore_in_pred=[]): """Compute the ROC AUC score, given the gold labels and predicted probs. Args: gold: A 1d array-like of gold labels probs: A 2d array-like of predicted probabilities ignore_in_gold: A list of labels for which elements...
Remove from gold and pred all items with labels designated to ignore.
def _drop_ignored(gold, pred, ignore_in_gold, ignore_in_pred): """Remove from gold and pred all items with labels designated to ignore.""" keepers = np.ones_like(gold).astype(bool) for x in ignore_in_gold: keepers *= np.where(gold != x, 1, 0).astype(bool) for x in ignore_in_pred: keepers...
Dump JSON to file
def write(self): """Dump JSON to file""" with open(self.log_path, "w") as f: json.dump(self.log_dict, f, indent=1)
Predicts int labels for an input X on all tasks
def predict(self, X, break_ties="random", return_probs=False, **kwargs): """Predicts int labels for an input X on all tasks Args: X: The input for the predict_proba method break_ties: A tie-breaking policy return_probs: Return the predicted probabilities as well ...
Scores the predictive performance of the Classifier on all tasks Args: data: either a Pytorch Dataset DataLoader or tuple supplying ( X Y ): X: The input for the predict method Y: A t - length list of [ n ] or [ n 1 ] np. ndarrays or torch. Tensors of gold labels in { 1... K_t } metric: The metric with which to score p...
def score( self, data, metric="accuracy", validation_task=None, reduce="mean", break_ties="random", verbose=True, print_confusion_matrix=False, **kwargs, ): """Scores the predictive performance of the Classifier on all tasks Arg...
Scores the predictive performance of the Classifier on task t
def score_task(self, X, Y, t=0, metric="accuracy", verbose=True, **kwargs): """Scores the predictive performance of the Classifier on task t Args: X: The input for the predict_task method Y: A [n] or [n, 1] np.ndarray or torch.Tensor of gold labels in {1,...,K_t}...
Predicts int labels for an input X on task t
def predict_task(self, X, t=0, break_ties="random", **kwargs): """Predicts int labels for an input X on task t Args: X: The input for the predict_task_proba method t: The task index to predict Returns: An n-dim tensor of int predictions for the specified task...
Predicts probabilistic labels for an input X on task t
def predict_task_proba(self, X, t=0, **kwargs): """Predicts probabilistic labels for an input X on task t Args: X: The input for the predict_proba method t: The task index to predict for which to predict probabilities Returns: An [n, K_t] tensor of prediction...
Converts a None list np. ndarray or torch. Tensor to torch. Tensor
def _to_torch(Z, dtype=None): """Converts a None, list, np.ndarray, or torch.Tensor to torch.Tensor""" if isinstance(Z, list): return [Classifier._to_torch(z, dtype=dtype) for z in Z] else: return Classifier._to_torch(Z)
Converts a None list np. ndarray or torch. Tensor to np. ndarray
def _to_numpy(Z): """Converts a None, list, np.ndarray, or torch.Tensor to np.ndarray""" if isinstance(Z, list): return [Classifier._to_numpy(z) for z in Z] else: return Classifier._to_numpy(Z)
Prints scheduler for user to read.
def pretty_print_schedule(self, hyperband_schedule, describe_hyperband=True): """ Prints scheduler for user to read. """ print("=========================================") print("| Hyperband Schedule |") print("========================================="...
Gets the largest hyperband schedule within target_budget. This is required since the original hyperband algorithm uses R the maximum number of resources per configuration. TODO ( maxlam ): Possibly binary search it if this becomes a bottleneck.
def get_largest_schedule_within_budget(self, budget, proportion_discard): """ Gets the largest hyperband schedule within target_budget. This is required since the original hyperband algorithm uses R, the maximum number of resources per configuration. TODO(maxlam): Possibly binary...
Generate hyperband schedule according to the paper.
def generate_hyperband_schedule(self, R, eta): """ Generate hyperband schedule according to the paper. Args: R: maximum resources per config. eta: proportion of configruations to discard per iteration of successive halving. Returns: hyperband sch...
Performs hyperband search according to the generated schedule.
def search( self, search_space, valid_data, init_args=[], train_args=[], init_kwargs={}, train_kwargs={}, module_args={}, module_kwargs={}, max_search=None, shuffle=True, verbose=True, seed=None, **score_kwar...
Adds special markers around tokens at specific positions ( e. g. entities )
def mark_entities(tokens, positions, markers=[], style="insert"): """Adds special markers around tokens at specific positions (e.g., entities) Args: tokens: A list of tokens (the sentence) positions: 1) A list of inclusive ranges (tuples) corresponding to the token range...
Clears the state starts clock
def _clear_state(self, seed=None): """Clears the state, starts clock""" self.start_time = time() self.run_stats = [] self.best_index = -1 self.best_score = -1 self.best_config = None # Note: These must be set at the start of self.search() self.search_spac...
Returns self. run_stats over search params as pandas dataframe.
def run_stats_df(self): """Returns self.run_stats over search params as pandas dataframe.""" run_stats_df = [] for x in self.run_stats: search_results = {**x["search_params"]} search_results["score"] = x["score"] run_stats_df.append(search_results) re...
Args: search_space: see config_generator () documentation valid_data: a tuple of Tensors ( X Y ) a Dataset or a DataLoader of X ( data ) and Y ( labels ) for the dev split init_args: ( list ) positional args for initializing the model train_args: ( list ) positional args for training the model init_kwargs: ( dict ) key...
def search( self, search_space, valid_data, init_args=[], train_args=[], init_kwargs={}, train_kwargs={}, module_args={}, module_kwargs={}, max_search=None, shuffle=True, verbose=True, **score_kwargs, ): ...
Generates config dicts from the given search space
def config_generator(search_space, max_search, rng, shuffle=True): """Generates config dicts from the given search space Args: search_space: (dict) A dictionary of parameters to search over. See note below for more details. max_search: (int) The maximum number of...
Given label matrix L_aug and labels Y compute the true mu params.
def compute_mu(L_aug, Y, k, p): """Given label matrix L_aug and labels Y, compute the true mu params. Args: L: (np.array {0,1}) [n, d] The augmented (indicator) label matrix Y: (np.array int) [n] The true labels in {1,...,k} k: (int) Cardinality p: (np.array float) [k] The class...
Given label matrix L_aug and labels Y compute the covariance.
def compute_covariance(L_aug, Y, k, p): """Given label matrix L_aug and labels Y, compute the covariance. Args: L: (np.array {0,1}) [n, d] The augmented (indicator) label matrix Y: (np.array int) [n] The true labels in {1,...,k} k: (int) Cardinality p: (np.array float) [k] The c...
Given label matrix L and labels Y compute the covariance.
def compute_inv_covariance(L_aug, Y, k, p): """Given label matrix L and labels Y, compute the covariance. Args: L: (np.array) [n, d] The augmented (indicator) label matrix Y: (np.array int) [n] The true labels in {1,...,k} """ return np.linalg.inv(compute_covariance(L_aug, Y, k, p))
Pretty printing for numpy matrix X
def print_matrix(X, decimals=1): """Pretty printing for numpy matrix X""" for row in np.round(X, decimals=decimals): print(row)
Returns an indicator vector where ith element = 1 if x_i is labeled by at least two LFs that give it disagreeing labels.
def _conflicted_data_points(L): """Returns an indicator vector where ith element = 1 if x_i is labeled by at least two LFs that give it disagreeing labels.""" m = sparse.diags(np.ravel(L.max(axis=1).todense())) return np.ravel(np.max(m @ (L != 0) != L, axis=1).astype(int).todense())
Return the polarities of each LF based on evidence in a label matrix.
def lf_polarities(L): """Return the polarities of each LF based on evidence in a label matrix. Args: L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the jth LF to the ith candidate """ polarities = [sorted(list(set(L[:, i].data))) for i in range(L.shape[1])] ...
Return the ** fraction of items each LF labels that are also labeled by at least one other LF. **
def lf_overlaps(L, normalize_by_coverage=False): """Return the **fraction of items each LF labels that are also labeled by at least one other LF.** Note that the maximum possible overlap fraction for an LF is the LF's coverage, unless `normalize_by_coverage=True`, in which case it is 1. Args: ...
Return the ** fraction of items each LF labels that are also given a different ( non - abstain ) label by at least one other LF. **
def lf_conflicts(L, normalize_by_overlaps=False): """Return the **fraction of items each LF labels that are also given a different (non-abstain) label by at least one other LF.** Note that the maximum possible conflict fraction for an LF is the LF's overlaps fraction, unless `normalize_by_overlaps=...
Return the ** empirical accuracy ** against a set of labels Y ( e. g. dev set ) for each LF. Args: L: an n x m scipy. sparse matrix where L_ { i j } is the label given by the jth LF to the ith candidate Y: an [ n ] or [ n 1 ] np. ndarray of gold labels
def lf_empirical_accuracies(L, Y): """Return the **empirical accuracy** against a set of labels Y (e.g. dev set) for each LF. Args: L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the jth LF to the ith candidate Y: an [n] or [n, 1] np.ndarray of gold labels ...
Returns a pandas DataFrame with the various per - LF statistics.
def lf_summary(L, Y=None, lf_names=None, est_accs=None): """Returns a pandas DataFrame with the various per-LF statistics. Args: L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the jth LF to the ith candidate Y: an [n] or [n, 1] np.ndarray of gold labels. ...
Calculates coverage overlap conflicts and accuracy for a single LF
def single_lf_summary(Y_p, Y=None): """Calculates coverage, overlap, conflicts, and accuracy for a single LF Args: Y_p: a np.array or torch.Tensor of predicted labels Y: a np.array or torch.Tensor of true labels (if known) """ L = sparse.csr_matrix(arraylike_to_numpy(Y_p).reshape(-1, 1)...
Group items by error buckets
def error_buckets(gold, pred, X=None): """Group items by error buckets Args: gold: an array-like of gold labels (ints) pred: an array-like of predictions (ints) X: an iterable of items Returns: buckets: A dict of items where buckets[i,j] is a list of items with p...
A shortcut method for building a confusion matrix all at once.
def confusion_matrix( gold, pred, null_pred=False, null_gold=False, normalize=False, pretty_print=True ): """A shortcut method for building a confusion matrix all at once. Args: gold: an array-like of gold labels (ints) pred: an array-like of predictions (ints) null_pred: If True, i...
Args: gold: a np. ndarray of gold labels ( ints ) pred: a np. ndarray of predictions ( ints )
def add(self, gold, pred): """ Args: gold: a np.ndarray of gold labels (ints) pred: a np.ndarray of predictions (ints) """ self.counter.update(zip(gold, pred))
Args: search_space: see config_generator () documentation valid_data: a tuple of Tensors ( X Y ) a Dataset or a DataLoader of X ( data ) and Y ( labels ) for the dev split init_args: ( list ) positional args for initializing the model train_args: ( list ) positional args for training the model init_kwargs: ( dict ) key...
def search( self, search_space, valid_data, init_args=[], train_args=[], init_kwargs={}, train_kwargs={}, module_args={}, module_kwargs={}, max_search=None, shuffle=True, verbose=True, clean_up=True, seed=Non...
Configure osmnx by setting the default global vars to desired values.
def config(data_folder=settings.data_folder, logs_folder=settings.logs_folder, imgs_folder=settings.imgs_folder, cache_folder=settings.cache_folder, use_cache=settings.use_cache, log_file=settings.log_file, log_console=settings.log_console, lo...
Write a message to the log file and/ or print to the the console.
def log(message, level=None, name=None, filename=None): """ Write a message to the log file and/or print to the the console. Parameters ---------- message : string the content of the message to log level : int one of the logger.level constants name : string name of t...
Create a logger or return the current one if already instantiated.
def get_logger(level=None, name=None, filename=None): """ Create a logger or return the current one if already instantiated. Parameters ---------- level : int one of the logger.level constants name : string name of the logger filename : string name of the log file ...
Induce a subgraph of G.
def induce_subgraph(G, node_subset): """ Induce a subgraph of G. Parameters ---------- G : networkx multidigraph node_subset : list-like the subset of nodes to induce a subgraph of G Returns ------- G2 : networkx multidigraph the subgraph of G induced by node_subset...
Return a subgraph of the largest weakly or strongly connected component from a directed graph.
def get_largest_component(G, strongly=False): """ Return a subgraph of the largest weakly or strongly connected component from a directed graph. Parameters ---------- G : networkx multidigraph strongly : bool if True, return the largest strongly instead of weakly connected c...
Vectorized function to calculate the great - circle distance between two points or between vectors of points using haversine.
def great_circle_vec(lat1, lng1, lat2, lng2, earth_radius=6371009): """ Vectorized function to calculate the great-circle distance between two points or between vectors of points, using haversine. Parameters ---------- lat1 : float or array of float lng1 : float or array of float lat2 :...
Vectorized function to calculate the euclidean distance between two points or between vectors of points.
def euclidean_dist_vec(y1, x1, y2, x2): """ Vectorized function to calculate the euclidean distance between two points or between vectors of points. Parameters ---------- y1 : float or array of float x1 : float or array of float y2 : float or array of float x2 : float or array of fl...
Return the graph node nearest to some specified ( lat lng ) or ( y x ) point and optionally the distance between the node and the point. This function can use either a haversine or euclidean distance calculator.
def get_nearest_node(G, point, method='haversine', return_dist=False): """ Return the graph node nearest to some specified (lat, lng) or (y, x) point, and optionally the distance between the node and the point. This function can use either a haversine or euclidean distance calculator. Parameters ...
Return the nearest edge to a pair of coordinates. Pass in a graph and a tuple with the coordinates. We first get all the edges in the graph. Secondly we compute the euclidean distance from the coordinates to the segments determined by each edge. The last step is to sort the edge segments in ascending order based on the...
def get_nearest_edge(G, point): """ Return the nearest edge to a pair of coordinates. Pass in a graph and a tuple with the coordinates. We first get all the edges in the graph. Secondly we compute the euclidean distance from the coordinates to the segments determined by each edge. The last step is t...
Return the graph nodes nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The kdtree method is by far the fastest with large data sets but only finds approximate nearest nodes if working in unprojected coordinates like lat - lng ( it precisely finds the nearest node if working in pr...
def get_nearest_nodes(G, X, Y, method=None): """ Return the graph nodes nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest nodes if working in unprojected coordinat...
Return the graph edges nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The kdtree method is by far the fastest with large data sets but only finds approximate nearest edges if working in unprojected coordinates like lat - lng ( it precisely finds the nearest edge if working in pr...
def get_nearest_edges(G, X, Y, method=None, dist=0.0001): """ Return the graph edges nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest edges if working in unprojec...
Redistribute the vertices on a projected LineString or MultiLineString. The distance argument is only approximate since the total distance of the linestring may not be a multiple of the preferred distance. This function works on only [ Multi ] LineString geometry types.
def redistribute_vertices(geom, dist): """ Redistribute the vertices on a projected LineString or MultiLineString. The distance argument is only approximate since the total distance of the linestring may not be a multiple of the preferred distance. This function works on only [Multi]LineString geome...
Calculate the bearing between two lat - long points. Each tuple should represent ( lat lng ) as decimal degrees.
def get_bearing(origin_point, destination_point): """ Calculate the bearing between two lat-long points. Each tuple should represent (lat, lng) as decimal degrees. Parameters ---------- origin_point : tuple destination_point : tuple Returns ------- bearing : float the c...
Calculate the compass bearing from origin node to destination node for each edge in the directed graph then add each bearing as a new edge attribute.
def add_edge_bearings(G): """ Calculate the compass bearing from origin node to destination node for each edge in the directed graph then add each bearing as a new edge attribute. Parameters ---------- G : networkx multidigraph Returns ------- G : networkx multidigraph """ ...
Geocode a query string to ( lat lon ) with the Nominatim geocoder.
def geocode(query): """ Geocode a query string to (lat, lon) with the Nominatim geocoder. Parameters ---------- query : string the query string to geocode Returns ------- point : tuple the (lat, lon) coordinates returned by the geocoder """ # send the query to ...
Get a list of attribute values for each edge in a path.
def get_route_edge_attributes(G, route, attribute=None, minimize_key='length', retrieve_default=None): """ Get a list of attribute values for each edge in a path. Parameters ---------- G : networkx multidigraph route : list list of nodes in the path attribute : string the na...
Count how many street segments emanate from each node ( i. e. intersections and dead - ends ) in this graph.
def count_streets_per_node(G, nodes=None): """ Count how many street segments emanate from each node (i.e., intersections and dead-ends) in this graph. If nodes is passed, then only count the nodes in the graph with those IDs. Parameters ---------- G : networkx multidigraph nodes : iterabl...
Round the coordinates of a shapely Polygon to some decimal precision.
def round_polygon_coords(p, precision): """ Round the coordinates of a shapely Polygon to some decimal precision. Parameters ---------- p : shapely Polygon the polygon to round the coordinates of precision : int decimal precision to round coordinates to Returns ------- ...
Round the coordinates of a shapely Point to some decimal precision.
def round_point_coords(pt, precision): """ Round the coordinates of a shapely Point to some decimal precision. Parameters ---------- pt : shapely Point the Point to round the coordinates of precision : int decimal precision to round coordinates to Returns ------- Po...