partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Classifier.predict
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 predicted probabilities as well Returns: Y_p: An n-dim np.ndarray ...
metal/classifier.py
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...
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...
[ "Predicts", "(", "int", ")", "labels", "for", "an", "input", "X", "on", "all", "tasks" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L90-L107
[ "def", "predict", "(", "self", ",", "X", ",", "break_ties", "=", "\"random\"", ",", "return_probs", "=", "False", ",", "*", "*", "kwargs", ")", ":", "Y_s", "=", "self", ".", "_to_numpy", "(", "self", ".", "predict_proba", "(", "X", ",", "*", "*", "...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier.score
Scores the predictive performance of the Classifier on all tasks Args: data: a Pytorch DataLoader, Dataset, or tuple with Tensors (X,Y): X: The input for the predict method Y: An [n] or [n, 1] torch.Tensor or np.ndarray of target labels in {1,...,...
metal/classifier.py
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...
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...
[ "Scores", "the", "predictive", "performance", "of", "the", "Classifier", "on", "all", "tasks" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L109-L159
[ "def", "score", "(", "self", ",", "data", ",", "metric", "=", "\"accuracy\"", ",", "break_ties", "=", "\"random\"", ",", "verbose", "=", "True", ",", "print_confusion_matrix", "=", "True", ",", "*", "*", "kwargs", ",", ")", ":", "Y_p", ",", "Y", ",", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier._train_model
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 (labels) for the train split loss_fn: the loss function to minimize (maps *data -> loss) valid_data: a t...
metal/classifier.py
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...
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...
[ "The", "internal", "training", "routine", "called", "by", "train_model", "()", "after", "setup" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L172-L289
[ "def", "_train_model", "(", "self", ",", "train_data", ",", "loss_fn", ",", "valid_data", "=", "None", ",", "log_writer", "=", "None", ",", "restore_state", "=", "{", "}", ")", ":", "# Set model to train mode", "self", ".", "train", "(", ")", "train_config",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier.save
Serialize and save a model. Example: end_model = EndModel(...) end_model.train_model(...) end_model.save("my_end_model.pkl")
metal/classifier.py
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)
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)
[ "Serialize", "and", "save", "a", "model", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L299-L308
[ "def", "save", "(", "self", ",", "destination", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "destination", ",", "\"wb\"", ")", "as", "f", ":", "torch", ".", "save", "(", "self", ",", "f", ",", "*", "*", "kwargs", ")" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier.load
Deserialize and load a model. Example: end_model = EndModel.load("my_end_model.pkl") end_model.score(...)
metal/classifier.py
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)
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)
[ "Deserialize", "and", "load", "a", "model", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L311-L319
[ "def", "load", "(", "source", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "source", ",", "\"rb\"", ")", "as", "f", ":", "return", "torch", ".", "load", "(", "f", ",", "*", "*", "kwargs", ")" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier.resume_training
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 train split model_path: the path to the saved checpoint for resumin...
metal/classifier.py
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 ...
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 ...
[ "This", "model", "resume", "training", "of", "a", "classifier", "by", "reloading", "the", "appropriate", "state_dicts", "for", "each", "model" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L335-L353
[ "def", "resume_training", "(", "self", ",", "train_data", ",", "model_path", ",", "valid_data", "=", "None", ")", ":", "restore_state", "=", "self", ".", "checkpointer", ".", "restore", "(", "model_path", ")", "loss_fn", "=", "self", ".", "_get_loss_fn", "("...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier._restore_training_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
metal/classifier.py
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 """ ...
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 """ ...
[ "Restores", "the", "model", "and", "optimizer", "states" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L355-L384
[ "def", "_restore_training_state", "(", "self", ",", "restore_state", ")", ":", "self", ".", "load_state_dict", "(", "restore_state", "[", "\"model\"", "]", ")", "self", ".", "optimizer", ".", "load_state_dict", "(", "restore_state", "[", "\"optimizer\"", "]", ")...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier._create_dataset
Converts input data to the appropriate Dataset
metal/classifier.py
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)
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", "to", "the", "appropriate", "Dataset" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L386-L390
[ "def", "_create_dataset", "(", "self", ",", "*", "data", ")", ":", "# Make sure data is a tuple of dense tensors", "data", "=", "[", "self", ".", "_to_torch", "(", "x", ",", "dtype", "=", "torch", ".", "FloatTensor", ")", "for", "x", "in", "data", "]", "re...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier._create_data_loader
Converts input data into a DataLoader
metal/classifier.py
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...
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...
[ "Converts", "input", "data", "into", "a", "DataLoader" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L392-L412
[ "def", "_create_data_loader", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "if", "data", "is", "None", ":", "return", "None", "# Set DataLoader config", "# NOTE: Not applicable if data is already a DataLoader", "config", "=", "{", "*", "*", "self",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier._get_predictions
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] or [n, 1] torch.Tensor or np.ndarray of target labels in {1,...,k} ...
metal/classifier.py
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...
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...
[ "Computes", "predictions", "in", "batch", "given", "a", "labeled", "dataset" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L561-L601
[ "def", "_get_predictions", "(", "self", ",", "data", ",", "break_ties", "=", "\"random\"", ",", "return_probs", "=", "False", ",", "*", "*", "kwargs", ")", ":", "data_loader", "=", "self", ".", "_create_data_loader", "(", "data", ")", "Y_p", "=", "[", "]...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier._break_ties
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) "random": randomly choose among the tied options ...
metal/classifier.py
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...
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...
[ "Break", "ties", "in", "each", "row", "of", "a", "tensor", "according", "to", "the", "specified", "policy" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L603-L633
[ "def", "_break_ties", "(", "self", ",", "Y_s", ",", "break_ties", "=", "\"random\"", ")", ":", "n", ",", "k", "=", "Y_s", ".", "shape", "Y_h", "=", "np", ".", "zeros", "(", "n", ")", "diffs", "=", "np", ".", "abs", "(", "Y_s", "-", "Y_s", ".", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier._to_numpy
Converts a None, list, np.ndarray, or torch.Tensor to np.ndarray; also handles converting sparse input to dense.
metal/classifier.py
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 ...
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", "np", ".", "ndarray", ";", "also", "handles", "converting", "sparse", "input", "to", "dense", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L636-L654
[ "def", "_to_numpy", "(", "Z", ")", ":", "if", "Z", "is", "None", ":", "return", "Z", "elif", "issparse", "(", "Z", ")", ":", "return", "Z", ".", "toarray", "(", ")", "elif", "isinstance", "(", "Z", ",", "np", ".", "ndarray", ")", ":", "return", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier._to_torch
Converts a None, list, np.ndarray, or torch.Tensor to torch.Tensor; also handles converting sparse input to dense.
metal/classifier.py
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...
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...
[ "Converts", "a", "None", "list", "np", ".", "ndarray", "or", "torch", ".", "Tensor", "to", "torch", ".", "Tensor", ";", "also", "handles", "converting", "sparse", "input", "to", "dense", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L657-L677
[ "def", "_to_torch", "(", "Z", ",", "dtype", "=", "None", ")", ":", "if", "Z", "is", "None", ":", "return", "None", "elif", "issparse", "(", "Z", ")", ":", "Z", "=", "torch", ".", "from_numpy", "(", "Z", ".", "toarray", "(", ")", ")", "elif", "i...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier.warn_once
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.
metal/classifier.py
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...
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...
[ "Prints", "a", "warning", "statement", "just", "once" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L698-L710
[ "def", "warn_once", "(", "self", ",", "msg", ",", "msg_name", "=", "None", ")", ":", "assert", "isinstance", "(", "msg", ",", "str", ")", "msg_name", "=", "msg_name", "if", "msg_name", "else", "msg", "if", "msg_name", "not", "in", "warnings_given", ":", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
Classifier._stack_batches
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.
metal/classifier.py
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...
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...
[ "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", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L713-L723
[ "def", "_stack_batches", "(", "X", ")", ":", "X", "=", "[", "Classifier", ".", "_to_numpy", "(", "Xb", ")", "for", "Xb", "in", "X", "]", "if", "len", "(", "X", "[", "0", "]", ".", "shape", ")", "==", "1", ":", "return", "np", ".", "hstack", "...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
EndModel._build
TBD
metal/end_model/end_model.py
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...
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...
[ "TBD" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/end_model/end_model.py#L60-L89
[ "def", "_build", "(", "self", ",", "input_module", ",", "middle_modules", ",", "head_module", ")", ":", "input_layer", "=", "self", ".", "_build_input_layer", "(", "input_module", ")", "middle_layers", "=", "self", ".", "_build_middle_layers", "(", "middle_modules...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
EndModel._preprocess_Y
Convert Y to prob labels if necessary
metal/end_model/end_model.py
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
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
[ "Convert", "Y", "to", "prob", "labels", "if", "necessary" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/end_model/end_model.py#L179-L186
[ "def", "_preprocess_Y", "(", "self", ",", "Y", ",", "k", ")", ":", "Y", "=", "Y", ".", "clone", "(", ")", "# If preds, convert to probs", "if", "Y", ".", "dim", "(", ")", "==", "1", "or", "Y", ".", "shape", "[", "1", "]", "==", "1", ":", "Y", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
EndModel.predict_proba
Returns a [n, k] tensor of probs (probabilistic labels).
metal/end_model/end_model.py
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()
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()
[ "Returns", "a", "[", "n", "k", "]", "tensor", "of", "probs", "(", "probabilistic", "labels", ")", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/end_model/end_model.py#L220-L222
[ "def", "predict_proba", "(", "self", ",", "X", ")", ":", "return", "F", ".", "softmax", "(", "self", ".", "forward", "(", "X", ")", ",", "dim", "=", "1", ")", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
SparseLinearModule.forward
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.
metal/contrib/modules/sparse_linear_module.py
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...
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...
[ "Execute", "sparse", "linear", "layer" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/contrib/modules/sparse_linear_module.py#L25-L33
[ "def", "forward", "(", "self", ",", "X", ")", ":", "return", "self", ".", "W", "(", "X", ")", ".", "sum", "(", "dim", "=", "1", ")", "+", "self", ".", "b" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
SnorkelDataset.splits
Create train/dev/test splits (mapped to split numbers) :param conn_str: :param candidate_def: :param word_dict: :param train: :param dev: :param test: :param use_lfs: :param pretrained_word_dict: :param max_seq_len: :return:
metal/contrib/backends/wrapper.py
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...
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...
[ "Create", "train", "/", "dev", "/", "test", "splits", "(", "mapped", "to", "split", "numbers", ")" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/contrib/backends/wrapper.py#L100-L155
[ "def", "splits", "(", "cls", ",", "conn_str", ",", "candidate_def", ",", "word_dict", "=", "None", ",", "train", "=", "0", ",", "dev", "=", "1", ",", "test", "=", "2", ",", "use_lfs", "=", "(", "0", ",", "0", ",", "0", ")", ",", "pretrained_word_...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
SnorkelDataset._mark_entities
Convert Snorkel candidates to marked up sequences :param c: :param markers: :return:
metal/contrib/backends/wrapper.py
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...
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...
[ "Convert", "Snorkel", "candidates", "to", "marked", "up", "sequences" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/contrib/backends/wrapper.py#L157-L172
[ "def", "_mark_entities", "(", "self", ",", "c", ",", "markers", ")", ":", "sent", "=", "c", ".", "get_parent", "(", ")", ".", "words", "positions", "=", "[", "[", "c", "[", "i", "]", ".", "get_word_start", "(", ")", ",", "c", "[", "i", "]", "."...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
SnorkelDataset._include_pretrained_vocab
Include terms available via pretrained embeddings :param pretrained_word_dict: :param candidates: :return:
metal/contrib/backends/wrapper.py
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...
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...
[ "Include", "terms", "available", "via", "pretrained", "embeddings" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/contrib/backends/wrapper.py#L174-L188
[ "def", "_include_pretrained_vocab", "(", "self", ",", "pretrained_word_dict", ",", "candidates", ")", ":", "terms", "=", "Counter", "(", ")", "for", "c", "in", "candidates", ":", "for", "w", "in", "c", ".", "get_parent", "(", ")", ".", "words", ":", "if"...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
SnorkelDataset._build_vocab
Initalize symbol table dictionary :param sentences: :param markers: :return:
metal/contrib/backends/wrapper.py
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...
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...
[ "Initalize", "symbol", "table", "dictionary" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/contrib/backends/wrapper.py#L190-L208
[ "def", "_build_vocab", "(", "self", ",", "sentences", ",", "markers", "=", "[", "]", ")", ":", "from", "snorkel", ".", "learning", ".", "pytorch", ".", "rnn", ".", "utils", "import", "SymbolTable", "vocab", "=", "Counter", "(", ")", "for", "sent", "in"...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel._check_L
Run some basic checks on L.
metal/label_model/label_model.py
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}.")
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}.")
[ "Run", "some", "basic", "checks", "on", "L", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L31-L39
[ "def", "_check_L", "(", "self", ",", "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", "<", "...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel._create_L_ind
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 required for 0 (abstain) labels.
metal/label_model/label_model.py
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...
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...
[ "Convert", "a", "label", "matrix", "with", "labels", "in", "0", "...", "k", "to", "a", "one", "-", "hot", "format" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L41-L62
[ "def", "_create_L_ind", "(", "self", ",", "L", ")", ":", "# TODO: Update LabelModel to keep L variants as sparse matrices", "# throughout and remove this line.", "if", "issparse", "(", "L", ")", ":", "L", "=", "L", ".", "todense", "(", ")", "L_ind", "=", "np", "."...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel._get_augmented_label_matrix
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,...,k}
metal/label_model/label_model.py
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,...
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,...
[ "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", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L64-L139
[ "def", "_get_augmented_label_matrix", "(", "self", ",", "L", ",", "higher_order", "=", "False", ")", ":", "# Create a helper data structure which maps cliques (as tuples of member", "# sources) --> {start_index, end_index, maximal_cliques}, where", "# the last value is a set of indices i...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel._build_mask
Build mask applied to O^{-1}, O for the matrix approx constraint
metal/label_model/label_model.py
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 =...
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 =...
[ "Build", "mask", "applied", "to", "O^", "{", "-", "1", "}", "O", "for", "the", "matrix", "approx", "constraint" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L141-L153
[ "def", "_build_mask", "(", "self", ")", ":", "self", ".", "mask", "=", "torch", ".", "ones", "(", "self", ".", "d", ",", "self", ".", "d", ")", ".", "byte", "(", ")", "for", "ci", "in", "self", ".", "c_data", ".", "values", "(", ")", ":", "si...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel._generate_O
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
metal/label_model/label_model.py
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 """ ...
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", "overlaps", "matrix", "which", "is", "just", "all", "the", "different", "observed", "combinations", "of", "values", "of", "pairs", "of", "sources" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L155-L164
[ "def", "_generate_O", "(", "self", ",", "L", ")", ":", "L_aug", "=", "self", ".", "_get_augmented_label_matrix", "(", "L", ")", "self", ".", "d", "=", "L_aug", ".", "shape", "[", "1", "]", "self", ".", "O", "=", "torch", ".", "from_numpy", "(", "L_...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel._generate_O_inv
Form the *inverse* overlaps matrix
metal/label_model/label_model.py
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()
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()
[ "Form", "the", "*", "inverse", "*", "overlaps", "matrix" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L166-L169
[ "def", "_generate_O_inv", "(", "self", ",", "L", ")", ":", "self", ".", "_generate_O", "(", "L", ")", "self", ".", "O_inv", "=", "torch", ".", "from_numpy", "(", "np", ".", "linalg", ".", "inv", "(", "self", ".", "O", ".", "numpy", "(", ")", ")",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel._init_params
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*self.k + j, y] = P(\lambda_i = j |...
metal/label_model/label_model.py
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...
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...
[ "Initialize", "the", "learned", "params" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L171-L218
[ "def", "_init_params", "(", "self", ")", ":", "train_config", "=", "self", ".", "config", "[", "\"train_config\"", "]", "# Initialize mu so as to break basic reflective symmetry", "# Note that we are given either a single or per-LF initial precision", "# value, prec_i = P(Y=y|\\lf=y)...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel.get_conditional_probs
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_probs[i*(k+1) + ly, y] = P(\lambda_i = ly | Y = y) ...
metal/label_model/label_model.py
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...
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", "full", "conditional", "probabilities", "table", "as", "a", "numpy", "array", "where", "row", "i", "*", "(", "k", "+", "1", ")", "+", "ly", "is", "the", "conditional", "probabilities", "of", "source", "i", "emmiting", "label", "ly", "("...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L220-L251
[ "def", "get_conditional_probs", "(", "self", ",", "source", "=", "None", ")", ":", "c_probs", "=", "np", ".", "zeros", "(", "(", "self", ".", "m", "*", "(", "self", ".", "k", "+", "1", ")", ",", "self", ".", "k", ")", ")", "mu", "=", "self", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel.predict_proba
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}
metal/label_model/label_model.py
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...
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...
[ "Returns", "the", "[", "n", "k", "]", "matrix", "of", "label", "probabilities", "P", "(", "Y", "|", "\\", "lambda", ")" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L253-L283
[ "def", "predict_proba", "(", "self", ",", "L", ")", ":", "self", ".", "_set_constants", "(", "L", ")", "L_aug", "=", "self", ".", "_get_augmented_label_matrix", "(", "L", ")", "mu", "=", "np", ".", "clip", "(", "self", ".", "mu", ".", "detach", "(", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel.get_Q
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).
metal/label_model/label_model.py
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...
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...
[ "Get", "the", "model", "s", "estimate", "of", "Q", "=", "\\", "mu", "P", "\\", "mu^T" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L285-L294
[ "def", "get_Q", "(", "self", ")", ":", "Z", "=", "self", ".", "Z", ".", "detach", "(", ")", ".", "clone", "(", ")", ".", "numpy", "(", ")", "O", "=", "self", ".", "O", ".", "numpy", "(", ")", "I_k", "=", "np", ".", "eye", "(", "self", "."...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel.loss_l2
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 strengths to use
metal/label_model/label_model.py
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...
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...
[ "L2", "loss", "centered", "around", "mu_init", "scaled", "optionally", "per", "-", "source", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L300-L317
[ "def", "loss_l2", "(", "self", ",", "l2", "=", "0", ")", ":", "if", "isinstance", "(", "l2", ",", "(", "int", ",", "float", ")", ")", ":", "D", "=", "l2", "*", "torch", ".", "eye", "(", "self", ".", "d", ")", "else", ":", "D", "=", "torch",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel._set_class_balance
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
metal/label_model/label_model.py
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...
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...
[ "Set", "a", "prior", "for", "the", "class", "balance" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L332-L348
[ "def", "_set_class_balance", "(", "self", ",", "class_balance", ",", "Y_dev", ")", ":", "if", "class_balance", "is", "not", "None", ":", "self", ".", "p", "=", "np", ".", "array", "(", "class_balance", ")", "elif", "Y_dev", "is", "not", "None", ":", "c...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LabelModel.train_model
Train the model (i.e. estimate mu) in one of two ways, depending on whether source dependencies are provided or not: Args: L_train: An [n,m] scipy.sparse matrix with values in {0,1,...,k} corresponding to labels from supervision sources on the training set ...
metal/label_model/label_model.py
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: ...
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: ...
[ "Train", "the", "model", "(", "i", ".", "e", ".", "estimate", "mu", ")", "in", "one", "of", "two", "ways", "depending", "on", "whether", "source", "dependencies", "are", "provided", "or", "not", ":" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/label_model.py#L359-L446
[ "def", "train_model", "(", "self", ",", "L_train", ",", "Y_dev", "=", "None", ",", "deps", "=", "[", "]", ",", "class_balance", "=", "None", ",", "log_writer", "=", "None", ",", "*", "*", "kwargs", ",", ")", ":", "self", ".", "config", "=", "recurs...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
ClassBalanceModel._get_overlaps_tensor
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 data points Outputs: O: ...
metal/label_model/class_balance.py
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...
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...
[ "Transforms", "the", "input", "label", "matrix", "to", "a", "three", "-", "way", "overlaps", "tensor", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/class_balance.py#L36-L60
[ "def", "_get_overlaps_tensor", "(", "self", ",", "L", ")", ":", "n", ",", "m", "=", "L", ".", "shape", "# Convert from a (n,m) matrix of ints to a (k_lf, n, m) indicator tensor", "LY", "=", "np", ".", "array", "(", "[", "np", ".", "where", "(", "L", "==", "y...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
ClassBalanceModel.get_mask
Get the mask for the three-way overlaps matrix O, which is 0 when indices i,j,k are not unique
metal/label_model/class_balance.py
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: ...
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: ...
[ "Get", "the", "mask", "for", "the", "three", "-", "way", "overlaps", "matrix", "O", "which", "is", "0", "when", "indices", "i", "j", "k", "are", "not", "unique" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/class_balance.py#L62-L69
[ "def", "get_mask", "(", "self", ",", "m", ")", ":", "mask", "=", "torch", ".", "ones", "(", "(", "m", ",", "m", ",", "m", ",", "self", ".", "k_lf", ",", "self", ".", "k_lf", ",", "self", ".", "k_lf", ")", ")", ".", "byte", "(", ")", "for", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
EntityMention._get_char_offsets
Store or calculate char_offsets, adding the offset of the doc end
metal/contrib/info_extraction/mentions.py
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) ...
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) ...
[ "Store", "or", "calculate", "char_offsets", "adding", "the", "offset", "of", "the", "doc", "end" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/contrib/info_extraction/mentions.py#L54-L65
[ "def", "_get_char_offsets", "(", "self", ",", "char_offsets", ")", ":", "if", "char_offsets", ":", "char_offsets", "=", "char_offsets", "char_offsets", ".", "append", "(", "len", "(", "self", ".", "text", ")", ")", "else", ":", "char_offsets", "=", "np", "...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
RandomVoter.predict_proba
Args: L: An [n, m] scipy.sparse matrix of labels Returns: output: A [n, k] np.ndarray of probabilistic labels
metal/label_model/baselines.py
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...
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", ":", "L", ":", "An", "[", "n", "m", "]", "scipy", ".", "sparse", "matrix", "of", "labels", "Returns", ":", "output", ":", "A", "[", "n", "k", "]", "np", ".", "ndarray", "of", "probabilistic", "labels" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/baselines.py#L14-L24
[ "def", "predict_proba", "(", "self", ",", "L", ")", ":", "n", "=", "L", ".", "shape", "[", "0", "]", "Y_p", "=", "np", ".", "random", ".", "rand", "(", "n", ",", "self", ".", "k", ")", "Y_p", "/=", "Y_p", ".", "sum", "(", "axis", "=", "1", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
MajorityClassVoter.train_model
Args: balance: A 1d arraylike that sums to 1, corresponding to the (possibly estimated) class balance.
metal/label_model/baselines.py
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)
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)
[ "Args", ":", "balance", ":", "A", "1d", "arraylike", "that", "sums", "to", "1", "corresponding", "to", "the", "(", "possibly", "estimated", ")", "class", "balance", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/baselines.py#L35-L41
[ "def", "train_model", "(", "self", ",", "balance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "balance", "=", "np", ".", "array", "(", "balance", ")" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
TaskGraph.feasible_set
Iterator over values in feasible set
metal/multitask/task_graph.py
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)
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)
[ "Iterator", "over", "values", "in", "feasible", "set" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/multitask/task_graph.py#L58-L61
[ "def", "feasible_set", "(", "self", ")", ":", "for", "y", "in", "itertools", ".", "product", "(", "*", "[", "range", "(", "1", ",", "k", "+", "1", ")", "for", "k", "in", "self", ".", "K", "]", ")", ":", "yield", "np", ".", "array", "(", "y", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
accuracy_score
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 e...
metal/metrics.py
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 ...
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", "(", "micro", ")", "accuracy", ".", "Args", ":", "gold", ":", "A", "1d", "array", "-", "like", "of", "gold", "labels", "pred", ":", "A", "1d", "array", "-", "like", "of", "predicted", "labels", "(", "assuming", "abstain", "=", "0", ")", ...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/metrics.py#L8-L29
[ "def", "accuracy_score", "(", "gold", ",", "pred", ",", "ignore_in_gold", "=", "[", "]", ",", "ignore_in_pred", "=", "[", "]", ")", ":", "gold", ",", "pred", "=", "_preprocess", "(", "gold", ",", "pred", ",", "ignore_in_gold", ",", "ignore_in_pred", ")",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
coverage_score
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 ...
metal/metrics.py
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 ...
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", "(", "global", ")", "coverage", ".", "Args", ":", "gold", ":", "A", "1d", "array", "-", "like", "of", "gold", "labels", "pred", ":", "A", "1d", "array", "-", "like", "of", "predicted", "labels", "(", "assuming", "abstain", "=", "0", ")",...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/metrics.py#L32-L48
[ "def", "coverage_score", "(", "gold", ",", "pred", ",", "ignore_in_gold", "=", "[", "]", ",", "ignore_in_pred", "=", "[", "]", ")", ":", "gold", ",", "pred", "=", "_preprocess", "(", "gold", ",", "pred", ",", "ignore_in_gold", ",", "ignore_in_pred", ")",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
precision_score
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...
metal/metrics.py
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...
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", "precision", "for", "a", "single", "class", ".", "Args", ":", "gold", ":", "A", "1d", "array", "-", "like", "of", "gold", "labels", "pred", ":", "A", "1d", "array", "-", "like", "of", "predicted", "labels", "(", "assuming", "abstain", "=",...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/metrics.py#L51-L78
[ "def", "precision_score", "(", "gold", ",", "pred", ",", "pos_label", "=", "1", ",", "ignore_in_gold", "=", "[", "]", ",", "ignore_in_pred", "=", "[", "]", ")", ":", "gold", ",", "pred", "=", "_preprocess", "(", "gold", ",", "pred", ",", "ignore_in_gol...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
recall_score
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 fo...
metal/metrics.py
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...
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", "=", ...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/metrics.py#L81-L108
[ "def", "recall_score", "(", "gold", ",", "pred", ",", "pos_label", "=", "1", ",", "ignore_in_gold", "=", "[", "]", ",", "ignore_in_pred", "=", "[", "]", ")", ":", "gold", ",", "pred", "=", "_preprocess", "(", "gold", ",", "pred", ",", "ignore_in_gold",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
fbeta_score
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 fo...
metal/metrics.py
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...
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...
[ "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", "=", ...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/metrics.py#L111-L138
[ "def", "fbeta_score", "(", "gold", ",", "pred", ",", "pos_label", "=", "1", ",", "beta", "=", "1.0", ",", "ignore_in_gold", "=", "[", "]", ",", "ignore_in_pred", "=", "[", "]", ")", ":", "gold", ",", "pred", "=", "_preprocess", "(", "gold", ",", "p...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
roc_auc_score
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 having that gold label will be ignored. Returns: ro...
metal/metrics.py
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...
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...
[ "Compute", "the", "ROC", "AUC", "score", "given", "the", "gold", "labels", "and", "predicted", "probs", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/metrics.py#L145-L169
[ "def", "roc_auc_score", "(", "gold", ",", "probs", ",", "ignore_in_gold", "=", "[", "]", ",", "ignore_in_pred", "=", "[", "]", ")", ":", "gold", "=", "arraylike_to_numpy", "(", "gold", ")", "# Filter out the ignore_in_gold (but not ignore_in_pred)", "# Note the curr...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
_drop_ignored
Remove from gold and pred all items with labels designated to ignore.
metal/metrics.py
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...
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...
[ "Remove", "from", "gold", "and", "pred", "all", "items", "with", "labels", "designated", "to", "ignore", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/metrics.py#L172-L182
[ "def", "_drop_ignored", "(", "gold", ",", "pred", ",", "ignore_in_gold", ",", "ignore_in_pred", ")", ":", "keepers", "=", "np", ".", "ones_like", "(", "gold", ")", ".", "astype", "(", "bool", ")", "for", "x", "in", "ignore_in_gold", ":", "keepers", "*=",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
LogWriter.write
Dump JSON to file
metal/logging/writer.py
def write(self): """Dump JSON to file""" with open(self.log_path, "w") as f: json.dump(self.log_dict, f, indent=1)
def write(self): """Dump JSON to file""" with open(self.log_path, "w") as f: json.dump(self.log_dict, f, indent=1)
[ "Dump", "JSON", "to", "file" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/logging/writer.py#L88-L91
[ "def", "write", "(", "self", ")", ":", "with", "open", "(", "self", ".", "log_path", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "self", ".", "log_dict", ",", "f", ",", "indent", "=", "1", ")" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
MTClassifier.predict
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 Returns: Y_p: A t-length list of n-dim np.ndarrays of predictions i...
metal/multitask/mt_classifier.py
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 ...
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 ...
[ "Predicts", "int", "labels", "for", "an", "input", "X", "on", "all", "tasks" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/multitask/mt_classifier.py#L52-L77
[ "def", "predict", "(", "self", ",", "X", ",", "break_ties", "=", "\"random\"", ",", "return_probs", "=", "False", ",", "*", "*", "kwargs", ")", ":", "Y_s", "=", "self", ".", "predict_proba", "(", "X", ",", "*", "*", "kwargs", ")", "self", ".", "_ch...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
MTClassifier.score
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 ...
metal/multitask/mt_classifier.py
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...
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", "all", "tasks", "Args", ":", "data", ":", "either", "a", "Pytorch", "Dataset", "DataLoader", "or", "tuple", "supplying", "(", "X", "Y", ")", ":", "X", ":", "The", "input", "fo...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/multitask/mt_classifier.py#L79-L153
[ "def", "score", "(", "self", ",", "data", ",", "metric", "=", "\"accuracy\"", ",", "validation_task", "=", "None", ",", "reduce", "=", "\"mean\"", ",", "break_ties", "=", "\"random\"", ",", "verbose", "=", "True", ",", "print_confusion_matrix", "=", "False",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
MTClassifier.score_task
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} t: The task index to score metric: The metric with which to sc...
metal/multitask/mt_classifier.py
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}...
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}...
[ "Scores", "the", "predictive", "performance", "of", "the", "Classifier", "on", "task", "t" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/multitask/mt_classifier.py#L155-L176
[ "def", "score_task", "(", "self", ",", "X", ",", "Y", ",", "t", "=", "0", ",", "metric", "=", "\"accuracy\"", ",", "verbose", "=", "True", ",", "*", "*", "kwargs", ")", ":", "Y", "=", "self", ".", "_to_numpy", "(", "Y", ")", "Y_tp", "=", "self"...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
MTClassifier.predict_task
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
metal/multitask/mt_classifier.py
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...
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", "int", "labels", "for", "an", "input", "X", "on", "task", "t" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/multitask/mt_classifier.py#L178-L189
[ "def", "predict_task", "(", "self", ",", "X", ",", "t", "=", "0", ",", "break_ties", "=", "\"random\"", ",", "*", "*", "kwargs", ")", ":", "Y_tp", "=", "self", ".", "predict_task_proba", "(", "X", ",", "t", "=", "t", ",", "*", "*", "kwargs", ")",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
MTClassifier.predict_task_proba
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 predictions for task t NOTE: By default, this method calls pr...
metal/multitask/mt_classifier.py
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...
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...
[ "Predicts", "probabilistic", "labels", "for", "an", "input", "X", "on", "task", "t" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/multitask/mt_classifier.py#L191-L203
[ "def", "predict_task_proba", "(", "self", ",", "X", ",", "t", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "predict_proba", "(", "X", ",", "*", "*", "kwargs", ")", "[", "t", "]" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
MTClassifier._to_torch
Converts a None, list, np.ndarray, or torch.Tensor to torch.Tensor
metal/multitask/mt_classifier.py
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)
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", "torch", ".", "Tensor" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/multitask/mt_classifier.py#L213-L218
[ "def", "_to_torch", "(", "Z", ",", "dtype", "=", "None", ")", ":", "if", "isinstance", "(", "Z", ",", "list", ")", ":", "return", "[", "Classifier", ".", "_to_torch", "(", "z", ",", "dtype", "=", "dtype", ")", "for", "z", "in", "Z", "]", "else", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
MTClassifier._to_numpy
Converts a None, list, np.ndarray, or torch.Tensor to np.ndarray
metal/multitask/mt_classifier.py
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)
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)
[ "Converts", "a", "None", "list", "np", ".", "ndarray", "or", "torch", ".", "Tensor", "to", "np", ".", "ndarray" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/multitask/mt_classifier.py#L221-L226
[ "def", "_to_numpy", "(", "Z", ")", ":", "if", "isinstance", "(", "Z", ",", "list", ")", ":", "return", "[", "Classifier", ".", "_to_numpy", "(", "z", ")", "for", "z", "in", "Z", "]", "else", ":", "return", "Classifier", ".", "_to_numpy", "(", "Z", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
HyperbandTuner.pretty_print_schedule
Prints scheduler for user to read.
metal/tuners/hyperband_tuner.py
def pretty_print_schedule(self, hyperband_schedule, describe_hyperband=True): """ Prints scheduler for user to read. """ print("=========================================") print("| Hyperband Schedule |") print("========================================="...
def pretty_print_schedule(self, hyperband_schedule, describe_hyperband=True): """ Prints scheduler for user to read. """ print("=========================================") print("| Hyperband Schedule |") print("========================================="...
[ "Prints", "scheduler", "for", "user", "to", "read", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/hyperband_tuner.py#L64-L94
[ "def", "pretty_print_schedule", "(", "self", ",", "hyperband_schedule", ",", "describe_hyperband", "=", "True", ")", ":", "print", "(", "\"=========================================\"", ")", "print", "(", "\"| Hyperband Schedule |\"", ")", "print", "(", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
HyperbandTuner.get_largest_schedule_within_budget
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. Args: budget: total budget of th...
metal/tuners/hyperband_tuner.py
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...
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...
[ "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", "(...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/hyperband_tuner.py#L96-L120
[ "def", "get_largest_schedule_within_budget", "(", "self", ",", "budget", ",", "proportion_discard", ")", ":", "# Exhaustively generate schedules and check if", "# they're within budget, adding to a list.", "valid_schedules_and_costs", "=", "[", "]", "for", "R", "in", "range", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
HyperbandTuner.generate_hyperband_schedule
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 schedule, which is represented as a list of brackets, wher...
metal/tuners/hyperband_tuner.py
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...
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...
[ "Generate", "hyperband", "schedule", "according", "to", "the", "paper", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/hyperband_tuner.py#L127-L154
[ "def", "generate_hyperband_schedule", "(", "self", ",", "R", ",", "eta", ")", ":", "schedule", "=", "[", "]", "s_max", "=", "int", "(", "math", ".", "floor", "(", "math", ".", "log", "(", "R", ",", "eta", ")", ")", ")", "# B = (s_max + 1) * R", "for"...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
HyperbandTuner.search
Performs hyperband search according to the generated schedule. At the beginning of each bracket, we generate a list of random configurations and perform successive halving on it; we repeat this process for the number of brackets in the schedule. Args: init_args: (li...
metal/tuners/hyperband_tuner.py
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...
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...
[ "Performs", "hyperband", "search", "according", "to", "the", "generated", "schedule", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/hyperband_tuner.py#L156-L267
[ "def", "search", "(", "self", ",", "search_space", ",", "valid_data", ",", "init_args", "=", "[", "]", ",", "train_args", "=", "[", "]", ",", "init_kwargs", "=", "{", "}", ",", "train_kwargs", "=", "{", "}", ",", "module_args", "=", "{", "}", ",", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
mark_entities
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 ranges of the entities in order. (Assumes each entity has only one...
metal/contrib/info_extraction/utils.py
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...
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...
[ "Adds", "special", "markers", "around", "tokens", "at", "specific", "positions", "(", "e", ".", "g", ".", "entities", ")" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/contrib/info_extraction/utils.py#L1-L76
[ "def", "mark_entities", "(", "tokens", ",", "positions", ",", "markers", "=", "[", "]", ",", "style", "=", "\"insert\"", ")", ":", "if", "markers", "and", "len", "(", "markers", ")", "!=", "2", "*", "len", "(", "positions", ")", ":", "msg", "=", "(...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
ModelTuner._clear_state
Clears the state, starts clock
metal/tuners/tuner.py
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...
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...
[ "Clears", "the", "state", "starts", "clock" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/tuner.py#L78-L91
[ "def", "_clear_state", "(", "self", ",", "seed", "=", "None", ")", ":", "self", ".", "start_time", "=", "time", "(", ")", "self", ".", "run_stats", "=", "[", "]", "self", ".", "best_index", "=", "-", "1", "self", ".", "best_score", "=", "-", "1", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
ModelTuner.run_stats_df
Returns self.run_stats over search params as pandas dataframe.
metal/tuners/tuner.py
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...
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...
[ "Returns", "self", ".", "run_stats", "over", "search", "params", "as", "pandas", "dataframe", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/tuner.py#L209-L217
[ "def", "run_stats_df", "(", "self", ")", ":", "run_stats_df", "=", "[", "]", "for", "x", "in", "self", ".", "run_stats", ":", "search_results", "=", "{", "*", "*", "x", "[", "\"search_params\"", "]", "}", "search_results", "[", "\"score\"", "]", "=", "...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
ModelTuner.search
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) positiona...
metal/tuners/tuner.py
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, ): ...
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, ): ...
[ "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", "...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/tuner.py#L219-L255
[ "def", "search", "(", "self", ",", "search_space", ",", "valid_data", ",", "init_args", "=", "[", "]", ",", "train_args", "=", "[", "]", ",", "init_kwargs", "=", "{", "}", ",", "train_kwargs", "=", "{", "}", ",", "module_args", "=", "{", "}", ",", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
ModelTuner.config_generator
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 configurations to search. If max_search is None, do a full gr...
metal/tuners/tuner.py
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...
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...
[ "Generates", "config", "dicts", "from", "the", "given", "search", "space" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/tuner.py#L258-L351
[ "def", "config_generator", "(", "search_space", ",", "max_search", ",", "rng", ",", "shuffle", "=", "True", ")", ":", "def", "dict_product", "(", "d", ")", ":", "keys", "=", "d", ".", "keys", "(", ")", "for", "element", "in", "product", "(", "*", "d"...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
compute_mu
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 balance
metal/label_model/utils.py
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...
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", "true", "mu", "params", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/utils.py#L4-L21
[ "def", "compute_mu", "(", "L_aug", ",", "Y", ",", "k", ",", "p", ")", ":", "n", ",", "d", "=", "L_aug", ".", "shape", "assert", "Y", ".", "shape", "[", "0", "]", "==", "n", "# Compute mu", "mu", "=", "np", ".", "zeros", "(", "(", "d", ",", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
compute_covariance
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 class balance
metal/label_model/utils.py
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...
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_aug", "and", "labels", "Y", "compute", "the", "covariance", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/utils.py#L24-L36
[ "def", "compute_covariance", "(", "L_aug", ",", "Y", ",", "k", ",", "p", ")", ":", "n", ",", "d", "=", "L_aug", ".", "shape", "assert", "Y", ".", "shape", "[", "0", "]", "==", "n", "mu", "=", "compute_mu", "(", "L_aug", ",", "Y", ",", "k", ",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
compute_inv_covariance
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}
metal/label_model/utils.py
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))
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))
[ "Given", "label", "matrix", "L", "and", "labels", "Y", "compute", "the", "covariance", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/utils.py#L39-L46
[ "def", "compute_inv_covariance", "(", "L_aug", ",", "Y", ",", "k", ",", "p", ")", ":", "return", "np", ".", "linalg", ".", "inv", "(", "compute_covariance", "(", "L_aug", ",", "Y", ",", "k", ",", "p", ")", ")" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
print_matrix
Pretty printing for numpy matrix X
metal/label_model/utils.py
def print_matrix(X, decimals=1): """Pretty printing for numpy matrix X""" for row in np.round(X, decimals=decimals): print(row)
def print_matrix(X, decimals=1): """Pretty printing for numpy matrix X""" for row in np.round(X, decimals=decimals): print(row)
[ "Pretty", "printing", "for", "numpy", "matrix", "X" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/utils.py#L49-L52
[ "def", "print_matrix", "(", "X", ",", "decimals", "=", "1", ")", ":", "for", "row", "in", "np", ".", "round", "(", "X", ",", "decimals", "=", "decimals", ")", ":", "print", "(", "row", ")" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
_conflicted_data_points
Returns an indicator vector where ith element = 1 if x_i is labeled by at least two LFs that give it disagreeing labels.
metal/analysis.py
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())
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())
[ "Returns", "an", "indicator", "vector", "where", "ith", "element", "=", "1", "if", "x_i", "is", "labeled", "by", "at", "least", "two", "LFs", "that", "give", "it", "disagreeing", "labels", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L25-L29
[ "def", "_conflicted_data_points", "(", "L", ")", ":", "m", "=", "sparse", ".", "diags", "(", "np", ".", "ravel", "(", "L", ".", "max", "(", "axis", "=", "1", ")", ".", "todense", "(", ")", ")", ")", "return", "np", ".", "ravel", "(", "np", ".",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
lf_polarities
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
metal/analysis.py
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])] ...
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", "polarities", "of", "each", "LF", "based", "on", "evidence", "in", "a", "label", "matrix", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L60-L68
[ "def", "lf_polarities", "(", "L", ")", ":", "polarities", "=", "[", "sorted", "(", "list", "(", "set", "(", "L", "[", ":", ",", "i", "]", ".", "data", ")", ")", ")", "for", "i", "in", "range", "(", "L", ".", "shape", "[", "1", "]", ")", "]"...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
lf_overlaps
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: L: an n x m scipy.sparse matrix where L_{i,j} is th...
metal/analysis.py
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: ...
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", "labeled", "by", "at", "least", "one", "other", "LF", ".", "**" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L80-L96
[ "def", "lf_overlaps", "(", "L", ",", "normalize_by_coverage", "=", "False", ")", ":", "overlaps", "=", "(", "L", "!=", "0", ")", ".", "T", "@", "_overlapped_data_points", "(", "L", ")", "/", "L", ".", "shape", "[", "0", "]", "if", "normalize_by_coverag...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
lf_conflicts
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=True`, in which case it is 1. Args: ...
metal/analysis.py
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=...
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", "**", "fraction", "of", "items", "each", "LF", "labels", "that", "are", "also", "given", "a", "different", "(", "non", "-", "abstain", ")", "label", "by", "at", "least", "one", "other", "LF", ".", "**" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L99-L116
[ "def", "lf_conflicts", "(", "L", ",", "normalize_by_overlaps", "=", "False", ")", ":", "conflicts", "=", "(", "L", "!=", "0", ")", ".", "T", "@", "_conflicted_data_points", "(", "L", ")", "/", "L", ".", "shape", "[", "0", "]", "if", "normalize_by_overl...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
lf_empirical_accuracies
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
metal/analysis.py
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 ...
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 ...
[ "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", ...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L119-L131
[ "def", "lf_empirical_accuracies", "(", "L", ",", "Y", ")", ":", "# Assume labeled set is small, work with dense matrices", "Y", "=", "arraylike_to_numpy", "(", "Y", ")", "L", "=", "L", ".", "toarray", "(", ")", "X", "=", "np", ".", "where", "(", "L", "==", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
lf_summary
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. If provided, the empirical accuracy for each LF will be cal...
metal/analysis.py
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. ...
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. ...
[ "Returns", "a", "pandas", "DataFrame", "with", "the", "various", "per", "-", "LF", "statistics", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L134-L177
[ "def", "lf_summary", "(", "L", ",", "Y", "=", "None", ",", "lf_names", "=", "None", ",", "est_accs", "=", "None", ")", ":", "n", ",", "m", "=", "L", ".", "shape", "if", "lf_names", "is", "not", "None", ":", "col_names", "=", "[", "\"j\"", "]", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
single_lf_summary
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)
metal/analysis.py
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)...
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)...
[ "Calculates", "coverage", "overlap", "conflicts", "and", "accuracy", "for", "a", "single", "LF" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L180-L188
[ "def", "single_lf_summary", "(", "Y_p", ",", "Y", "=", "None", ")", ":", "L", "=", "sparse", ".", "csr_matrix", "(", "arraylike_to_numpy", "(", "Y_p", ")", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", "return", "lf_summary", "(", "L", ",", "Y...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
error_buckets
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 predicted label i and true label j. If X is Non...
metal/analysis.py
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...
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...
[ "Group", "items", "by", "error", "buckets" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L191-L214
[ "def", "error_buckets", "(", "gold", ",", "pred", ",", "X", "=", "None", ")", ":", "buckets", "=", "defaultdict", "(", "list", ")", "gold", "=", "arraylike_to_numpy", "(", "gold", ")", "pred", "=", "arraylike_to_numpy", "(", "pred", ")", "for", "i", ",...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
confusion_matrix
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, include the row corresponding to null predictions null_gold: If True, include the col corresponding to null go...
metal/analysis.py
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...
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...
[ "A", "shortcut", "method", "for", "building", "a", "confusion", "matrix", "all", "at", "once", "." ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L217-L242
[ "def", "confusion_matrix", "(", "gold", ",", "pred", ",", "null_pred", "=", "False", ",", "null_gold", "=", "False", ",", "normalize", "=", "False", ",", "pretty_print", "=", "True", ")", ":", "conf", "=", "ConfusionMatrix", "(", "null_pred", "=", "null_pr...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
ConfusionMatrix.add
Args: gold: a np.ndarray of gold labels (ints) pred: a np.ndarray of predictions (ints)
metal/analysis.py
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))
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", ":", "gold", ":", "a", "np", ".", "ndarray", "of", "gold", "labels", "(", "ints", ")", "pred", ":", "a", "np", ".", "ndarray", "of", "predictions", "(", "ints", ")" ]
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L271-L277
[ "def", "add", "(", "self", ",", "gold", ",", "pred", ")", ":", "self", ".", "counter", ".", "update", "(", "zip", "(", "gold", ",", "pred", ")", ")" ]
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
RandomSearchTuner.search
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) positiona...
metal/tuners/random_tuner.py
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...
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...
[ "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", "...
HazyResearch/metal
python
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/random_tuner.py#L14-L86
[ "def", "search", "(", "self", ",", "search_space", ",", "valid_data", ",", "init_args", "=", "[", "]", ",", "train_args", "=", "[", "]", ",", "init_kwargs", "=", "{", "}", ",", "train_kwargs", "=", "{", "}", ",", "module_args", "=", "{", "}", ",", ...
c24e3772e25ac6d0917b8b7af4c1bcb92928f84a
train
config
Configure osmnx by setting the default global vars to desired values. Parameters --------- data_folder : string where to save and load data files logs_folder : string where to write the log files imgs_folder : string where to save figures cache_folder : string wh...
osmnx/utils.py
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...
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...
[ "Configure", "osmnx", "by", "setting", "the", "default", "global", "vars", "to", "desired", "values", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L45-L139
[ "def", "config", "(", "data_folder", "=", "settings", ".", "data_folder", ",", "logs_folder", "=", "settings", ".", "logs_folder", ",", "imgs_folder", "=", "settings", ".", "imgs_folder", ",", "cache_folder", "=", "settings", ".", "cache_folder", ",", "use_cache...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
log
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 the logger filename : string name of the log file Re...
osmnx/utils.py
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...
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...
[ "Write", "a", "message", "to", "the", "log", "file", "and", "/", "or", "print", "to", "the", "the", "console", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L142-L196
[ "def", "log", "(", "message", ",", "level", "=", "None", ",", "name", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "level", "is", "None", ":", "level", "=", "settings", ".", "log_level", "if", "name", "is", "None", ":", "name", "=", ...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
get_logger
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 Returns ------- logger.logger
osmnx/utils.py
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 ...
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 ...
[ "Create", "a", "logger", "or", "return", "the", "current", "one", "if", "already", "instantiated", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L200-L246
[ "def", "get_logger", "(", "level", "=", "None", ",", "name", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "level", "is", "None", ":", "level", "=", "settings", ".", "log_level", "if", "name", "is", "None", ":", "name", "=", "settings", ...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
induce_subgraph
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
osmnx/utils.py
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...
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...
[ "Induce", "a", "subgraph", "of", "G", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L272-L307
[ "def", "induce_subgraph", "(", "G", ",", "node_subset", ")", ":", "node_subset", "=", "set", "(", "node_subset", ")", "# copy nodes into new graph", "G2", "=", "G", ".", "__class__", "(", ")", "G2", ".", "add_nodes_from", "(", "(", "n", ",", "G", ".", "n...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
get_largest_component
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 component Returns ------- G : networkx multidi...
osmnx/utils.py
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...
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...
[ "Return", "a", "subgraph", "of", "the", "largest", "weakly", "or", "strongly", "connected", "component", "from", "a", "directed", "graph", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L311-L357
[ "def", "get_largest_component", "(", "G", ",", "strongly", "=", "False", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "original_len", "=", "len", "(", "list", "(", "G", ".", "nodes", "(", ")", ")", ")", "if", "strongly", ":", "# if the...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
great_circle_vec
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 : float or array of float lng2 : float or array of float earth_radius : n...
osmnx/utils.py
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 :...
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", "great", "-", "circle", "distance", "between", "two", "points", "or", "between", "vectors", "of", "points", "using", "haversine", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L361-L398
[ "def", "great_circle_vec", "(", "lat1", ",", "lng1", ",", "lat2", ",", "lng2", ",", "earth_radius", "=", "6371009", ")", ":", "phi1", "=", "np", ".", "deg2rad", "(", "lat1", ")", "phi2", "=", "np", ".", "deg2rad", "(", "lat2", ")", "d_phi", "=", "p...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
euclidean_dist_vec
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 float Returns ------- distance : float or...
osmnx/utils.py
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...
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...
[ "Vectorized", "function", "to", "calculate", "the", "euclidean", "distance", "between", "two", "points", "or", "between", "vectors", "of", "points", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L402-L422
[ "def", "euclidean_dist_vec", "(", "y1", ",", "x1", ",", "y2", ",", "x2", ")", ":", "# euclid's formula", "distance", "=", "(", "(", "x1", "-", "x2", ")", "**", "2", "+", "(", "y1", "-", "y2", ")", "**", "2", ")", "**", "0.5", "return", "distance"...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
get_nearest_node
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 ---------- G : networkx multidigraph point : tuple The (lat, lng)...
osmnx/utils.py
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 ...
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", "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", ...
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L426-L498
[ "def", "get_nearest_node", "(", "G", ",", "point", ",", "method", "=", "'haversine'", ",", "return_dist", "=", "False", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "if", "not", "G", "or", "(", "G", ".", "number_of_nodes", "(", ")", "=...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
get_nearest_edge
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 ...
osmnx/utils.py
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...
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", "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...
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L501-L544
[ "def", "get_nearest_edge", "(", "G", ",", "point", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "gdf", "=", "graph_to_gdfs", "(", "G", ",", "nodes", "=", "False", ",", "fill_edge_geometry", "=", "True", ")", "graph_edges", "=", "gdf", "[...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
get_nearest_nodes
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 ...
osmnx/utils.py
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...
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", "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", ...
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L547-L628
[ "def", "get_nearest_nodes", "(", "G", ",", "X", ",", "Y", ",", "method", "=", "None", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "if", "method", "is", "None", ":", "# calculate nearest node one at a time for each point", "nn", "=", "[", "g...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
get_nearest_edges
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 ...
osmnx/utils.py
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...
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...
[ "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", ...
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L631-L753
[ "def", "get_nearest_edges", "(", "G", ",", "X", ",", "Y", ",", "method", "=", "None", ",", "dist", "=", "0.0001", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "if", "method", "is", "None", ":", "# calculate nearest edge one at a time for eac...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
redistribute_vertices
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. This code is adapted from an answer...
osmnx/utils.py
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...
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...
[ "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"...
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L756-L789
[ "def", "redistribute_vertices", "(", "geom", ",", "dist", ")", ":", "if", "geom", ".", "geom_type", "==", "'LineString'", ":", "num_vert", "=", "int", "(", "round", "(", "geom", ".", "length", "/", "dist", ")", ")", "if", "num_vert", "==", "0", ":", ...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
get_bearing
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 compass bearing in decimal degrees from the origin point ...
osmnx/utils.py
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...
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", "bearing", "between", "two", "lat", "-", "long", "points", ".", "Each", "tuple", "should", "represent", "(", "lat", "lng", ")", "as", "decimal", "degrees", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L792-L826
[ "def", "get_bearing", "(", "origin_point", ",", "destination_point", ")", ":", "if", "not", "(", "isinstance", "(", "origin_point", ",", "tuple", ")", "and", "isinstance", "(", "destination_point", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "'or...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
add_edge_bearings
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
osmnx/utils.py
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 """ ...
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 """ ...
[ "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", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L830-L859
[ "def", "add_edge_bearings", "(", "G", ")", ":", "for", "u", ",", "v", ",", "data", "in", "G", ".", "edges", "(", "keys", "=", "False", ",", "data", "=", "True", ")", ":", "if", "u", "==", "v", ":", "# a self-loop has an undefined compass bearing", "dat...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
geocode
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
osmnx/utils.py
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 ...
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 ...
[ "Geocode", "a", "query", "string", "to", "(", "lat", "lon", ")", "with", "the", "Nominatim", "geocoder", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L863-L892
[ "def", "geocode", "(", "query", ")", ":", "# send the query to the nominatim geocoder and parse the json response", "url_template", "=", "'https://nominatim.openstreetmap.org/search?format=json&limit=1&q={}'", "url", "=", "url_template", ".", "format", "(", "query", ")", "respons...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
get_route_edge_attributes
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 name of the attribute to get the value of for each edge. If not specified, the complete data dict is returned...
osmnx/utils.py
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...
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...
[ "Get", "a", "list", "of", "attribute", "values", "for", "each", "edge", "in", "a", "path", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L896-L932
[ "def", "get_route_edge_attributes", "(", "G", ",", "route", ",", "attribute", "=", "None", ",", "minimize_key", "=", "'length'", ",", "retrieve_default", "=", "None", ")", ":", "attribute_values", "=", "[", "]", "for", "u", ",", "v", "in", "zip", "(", "r...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
count_streets_per_node
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 : iterable the set of node IDs to get counts for Re...
osmnx/utils.py
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...
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...
[ "Count", "how", "many", "street", "segments", "emanate", "from", "each", "node", "(", "i", ".", "e", ".", "intersections", "and", "dead", "-", "ends", ")", "in", "this", "graph", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L936-L999
[ "def", "count_streets_per_node", "(", "G", ",", "nodes", "=", "None", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "# to calculate the counts, get undirected representation of the graph. for", "# each node, get the list of the set of unique u,v,key edges, including...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
round_polygon_coords
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 ------- new_poly : shapely Polygon the polygon w...
osmnx/utils.py
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 ------- ...
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", "Polygon", "to", "some", "decimal", "precision", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L1003-L1031
[ "def", "round_polygon_coords", "(", "p", ",", "precision", ")", ":", "# round the coordinates of the Polygon exterior", "new_exterior", "=", "[", "[", "round", "(", "x", ",", "precision", ")", "for", "x", "in", "c", "]", "for", "c", "in", "p", ".", "exterior...
be59fd313bcb68af8fc79242c56194f1247e26e2
train
round_point_coords
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 ------- Point
osmnx/utils.py
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...
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...
[ "Round", "the", "coordinates", "of", "a", "shapely", "Point", "to", "some", "decimal", "precision", "." ]
gboeing/osmnx
python
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L1055-L1071
[ "def", "round_point_coords", "(", "pt", ",", "precision", ")", ":", "return", "Point", "(", "[", "round", "(", "x", ",", "precision", ")", "for", "x", "in", "pt", ".", "coords", "[", "0", "]", "]", ")" ]
be59fd313bcb68af8fc79242c56194f1247e26e2